@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.
- package/dist/src/acp-agent.d.ts +6 -0
- package/dist/src/acp-agent.js +15 -4
- package/dist/src/agent-definitions.js +29 -6
- package/dist/src/agent-execution.js +15 -10
- package/dist/src/agent-mcp-catalog.js +1 -0
- package/dist/src/agent-mcp.d.ts +4 -1
- package/dist/src/agent-mcp.js +46 -10
- package/dist/src/andorra/entry.d.ts +10 -0
- package/dist/src/andorra/entry.js +18 -4
- package/dist/src/andorra/hosted.d.ts +2 -1
- package/dist/src/andorra/hosted.js +2 -1
- package/dist/src/andorra/notices.d.ts +5 -0
- package/dist/src/andorra/notices.js +7 -0
- package/dist/src/andorra/state.d.ts +3 -2
- package/dist/src/andorra/state.js +4 -4
- package/dist/src/andorra/terminal.js +7 -2
- package/dist/src/anthropic-credentials.js +2 -0
- package/dist/src/app-server/error.d.ts +5 -0
- package/dist/src/app-server/error.js +7 -0
- package/dist/src/app-server/protocol.d.ts +22 -44
- package/dist/src/app-server/protocol.js +5 -1
- package/dist/src/app-server/workspace.d.ts +89 -0
- package/dist/src/app-server/workspace.js +457 -11
- package/dist/src/app-server.d.ts +465 -32
- package/dist/src/app-server.js +3308 -517
- package/dist/src/auth/deployment.js +2 -2
- package/dist/src/bridge/cloud.d.ts +27 -0
- package/dist/src/bridge/cloud.js +187 -0
- package/dist/src/bridge/command.d.ts +30 -0
- package/dist/src/bridge/command.js +347 -0
- package/dist/src/bridge/control.d.ts +68 -0
- package/dist/src/bridge/control.js +233 -0
- package/dist/src/bridge/engines.d.ts +90 -0
- package/dist/src/bridge/engines.js +601 -0
- package/dist/src/bridge/host-ops.d.ts +9 -0
- package/dist/src/bridge/host-ops.js +129 -0
- package/dist/src/bridge/host.d.ts +47 -0
- package/dist/src/bridge/host.js +540 -0
- package/dist/src/bridge/link.d.ts +38 -0
- package/dist/src/bridge/link.js +508 -0
- package/dist/src/bridge/login-link.d.ts +29 -0
- package/dist/src/bridge/login-link.js +54 -0
- package/dist/src/bridge/protocol.d.ts +136 -0
- package/dist/src/bridge/protocol.js +11 -0
- package/dist/src/bridge/store.d.ts +12 -0
- package/dist/src/bridge/store.js +61 -0
- package/dist/src/bridge/wording.d.ts +6 -0
- package/dist/src/bridge/wording.js +10 -0
- package/dist/src/browser-runner.js +1 -0
- package/dist/src/browser-server.js +7 -1
- package/dist/src/browser-ui/style.css +3 -3
- package/dist/src/browser-ui/tokens.css +28 -17
- package/dist/src/change-authors.d.ts +41 -0
- package/dist/src/change-authors.js +146 -0
- package/dist/src/claude-provider.js +3 -1
- package/dist/src/cli.js +202 -38
- package/dist/src/codex-errors.js +4 -1
- package/dist/src/coding-tools.js +15 -15
- package/dist/src/command-screens.d.ts +6 -0
- package/dist/src/command-screens.js +19 -14
- package/dist/src/commands.d.ts +14 -1
- package/dist/src/compaction-phrases.d.ts +4 -0
- package/dist/src/compaction-phrases.js +20 -0
- package/dist/src/completion.js +82 -5
- package/dist/src/config.d.ts +71 -3
- package/dist/src/config.js +202 -77
- package/dist/src/context-compaction.js +2 -1
- package/dist/src/deadline.js +13 -1
- package/dist/src/decision/DecisionManager.js +3 -2
- package/dist/src/decision/checks.js +1 -1
- package/dist/src/decision/requestPhrases.d.ts +4 -0
- package/dist/src/decision/requestPhrases.js +22 -0
- package/dist/src/default-graph.js +1 -1
- package/dist/src/file-diff.d.ts +4 -0
- package/dist/src/file-diff.js +2 -1
- package/dist/src/github-app/agent-writes.d.ts +102 -0
- package/dist/src/github-app/agent-writes.js +320 -0
- package/dist/src/github-app/client.d.ts +349 -0
- package/dist/src/github-app/client.js +810 -0
- package/dist/src/github-app/event-source.d.ts +208 -0
- package/dist/src/github-app/event-source.js +684 -0
- package/dist/src/github-app/metrics.d.ts +32 -0
- package/dist/src/github-app/metrics.js +49 -0
- package/dist/src/github-app/review-loop.d.ts +274 -0
- package/dist/src/github-app/review-loop.js +1177 -0
- package/dist/src/github-app/review-node.d.ts +81 -0
- package/dist/src/github-app/review-node.js +205 -0
- package/dist/src/github-app/review-post.d.ts +73 -0
- package/dist/src/github-app/review-post.js +139 -0
- package/dist/src/github-app/review-text.d.ts +107 -0
- package/dist/src/github-app/review-text.js +1133 -0
- package/dist/src/github-app/review-threads.d.ts +47 -0
- package/dist/src/github-app/review-threads.js +107 -0
- package/dist/src/github-app/reviewer.d.ts +121 -0
- package/dist/src/github-app/reviewer.js +598 -0
- package/dist/src/github-app/store.d.ts +59 -0
- package/dist/src/github-app/store.js +148 -0
- package/dist/src/github-app/triggers.d.ts +141 -0
- package/dist/src/github-app/triggers.js +441 -0
- package/dist/src/github-inbox.d.ts +55 -0
- package/dist/src/github-inbox.js +153 -0
- package/dist/src/github-names.d.ts +8 -0
- package/dist/src/github-names.js +8 -0
- package/dist/src/glob-search.d.ts +61 -0
- package/dist/src/glob-search.js +180 -0
- package/dist/src/graph-health.js +13 -4
- package/dist/src/graph-manager-chat.js +1 -1
- package/dist/src/graph-preview.d.ts +46 -0
- package/dist/src/graph-preview.js +55 -0
- package/dist/src/graph-provider-portability.js +34 -11
- package/dist/src/graph-quota.d.ts +29 -2
- package/dist/src/graph-quota.js +68 -10
- package/dist/src/graph-runner.js +88 -10
- package/dist/src/graph-server.d.ts +1 -1
- package/dist/src/graph-server.js +11 -9
- package/dist/src/graph-sync.js +3 -3
- package/dist/src/graph-ui/app.js +201 -40
- package/dist/src/graph-ui/controls.css +1 -0
- package/dist/src/graph-ui/embed.js +2 -2
- package/dist/src/graph-ui/icons.js +3 -1
- package/dist/src/graph-ui/index.html +1 -1
- package/dist/src/graph-ui/manager.css +1 -1
- package/dist/src/graph-ui/manager.js +2 -2
- package/dist/src/graph-ui/sidebar.js +30 -0
- package/dist/src/graph-ui/studio-canvas.js +26 -13
- package/dist/src/graph-ui/studio.css +15 -7
- package/dist/src/graph-ui/studio.js +26 -5
- package/dist/src/graph-ui/style.css +77 -45
- package/dist/src/graph-ui/theme.js +3 -36
- package/dist/src/graph-ui/tokens.css +28 -20
- package/dist/src/graphs.d.ts +34 -1
- package/dist/src/graphs.js +162 -17
- package/dist/src/image-input.d.ts +16 -0
- package/dist/src/image-input.js +41 -0
- package/dist/src/membership.d.ts +30 -1
- package/dist/src/membership.js +48 -8
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.d.ts +7 -1
- package/dist/src/model-metadata.js +39 -17
- package/dist/src/model-relay/local.d.ts +116 -0
- package/dist/src/model-relay/local.js +468 -0
- package/dist/src/model-relay/remote.d.ts +129 -0
- package/dist/src/model-relay/remote.js +252 -0
- package/dist/src/model-relay/runs.d.ts +34 -0
- package/dist/src/model-relay/runs.js +146 -0
- package/dist/src/model-relay/wire.d.ts +5 -0
- package/dist/src/model-relay/wire.js +5 -0
- package/dist/src/plan-pass.d.ts +59 -0
- package/dist/src/plan-pass.js +165 -0
- package/dist/src/project-registry.d.ts +21 -0
- package/dist/src/project-registry.js +74 -0
- package/dist/src/provider-engine.js +3 -0
- package/dist/src/provider-import.d.ts +0 -12
- package/dist/src/provider-import.js +7 -195
- package/dist/src/providers.d.ts +40 -2
- package/dist/src/providers.js +93 -23
- package/dist/src/pull-request-checks.d.ts +26 -0
- package/dist/src/pull-request-checks.js +56 -0
- package/dist/src/pull-request-conversation.d.ts +134 -0
- package/dist/src/pull-request-conversation.js +221 -0
- package/dist/src/pull-request-create.d.ts +175 -0
- package/dist/src/pull-request-create.js +392 -0
- package/dist/src/pull-request-details.d.ts +242 -0
- package/dist/src/pull-request-details.js +614 -0
- package/dist/src/pull-request-edit.d.ts +23 -0
- package/dist/src/pull-request-edit.js +91 -0
- package/dist/src/pull-request-logs.d.ts +87 -0
- package/dist/src/pull-request-logs.js +183 -0
- package/dist/src/pull-request-merge.d.ts +112 -0
- package/dist/src/pull-request-merge.js +258 -0
- package/dist/src/pull-request-review.d.ts +137 -0
- package/dist/src/pull-request-review.js +401 -0
- package/dist/src/pull-requests.d.ts +369 -8
- package/dist/src/pull-requests.js +524 -55
- package/dist/src/react-runtime.js +38 -5
- package/dist/src/remote/engine-pool.d.ts +88 -4
- package/dist/src/remote/engine-pool.js +379 -90
- package/dist/src/remote/roots.d.ts +19 -0
- package/dist/src/remote/roots.js +45 -7
- package/dist/src/remote/types.d.ts +0 -44
- package/dist/src/run-control.d.ts +17 -0
- package/dist/src/run-control.js +47 -0
- package/dist/src/run-progress.d.ts +10 -0
- package/dist/src/run-progress.js +122 -0
- package/dist/src/run-records.d.ts +7 -2
- package/dist/src/run-records.js +71 -6
- package/dist/src/runtime.d.ts +9 -1
- package/dist/src/runtime.js +24 -4
- package/dist/src/session-changes.d.ts +35 -0
- package/dist/src/session-changes.js +194 -6
- package/dist/src/session-monitor.js +2 -1
- package/dist/src/session-reaper.d.ts +1 -1
- package/dist/src/session-reaper.js +6 -1
- package/dist/src/session-summary.d.ts +2 -1
- package/dist/src/session-summary.js +2 -1
- package/dist/src/sessions.d.ts +11 -1
- package/dist/src/sessions.js +17 -4
- package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
- package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
- package/dist/src/skills/bundled/provenance.json +2 -2
- package/dist/src/skills/runtime-skills.js +1 -1
- package/dist/src/subagent-run.js +1 -0
- package/dist/src/telemetry/capture-core.d.ts +17 -0
- package/dist/src/telemetry/capture-core.js +59 -1
- package/dist/src/telemetry/classify.d.ts +3 -1
- package/dist/src/telemetry/classify.js +37 -0
- package/dist/src/telemetry/emitter.d.ts +17 -0
- package/dist/src/telemetry/emitter.js +76 -5
- package/dist/src/telemetry/schema.d.ts +47 -2
- package/dist/src/telemetry/schema.js +120 -5
- package/dist/src/telemetry/surface.d.ts +3 -1
- package/dist/src/telemetry/surface.js +4 -1
- package/dist/src/telemetry/uploader.d.ts +6 -1
- package/dist/src/telemetry/uploader.js +22 -3
- package/dist/src/terminal-ui.d.ts +1 -0
- package/dist/src/terminal-ui.js +10 -3
- package/dist/src/test-edit-guard.d.ts +7 -0
- package/dist/src/test-edit-guard.js +49 -1
- package/dist/src/timers.d.ts +2 -0
- package/dist/src/tools.js +59 -9
- package/dist/src/transcript.js +8 -2
- package/dist/src/types.d.ts +7 -0
- package/dist/src/usage-analytics.js +18 -10
- package/package.json +6 -1
- package/dist/src/remote/cert.d.ts +0 -11
- package/dist/src/remote/cert.js +0 -87
- package/dist/src/remote/client.d.ts +0 -119
- package/dist/src/remote/client.js +0 -544
- package/dist/src/remote/command.d.ts +0 -4
- package/dist/src/remote/command.js +0 -194
- package/dist/src/remote/errors.d.ts +0 -11
- package/dist/src/remote/errors.js +0 -14
- package/dist/src/remote/network.d.ts +0 -22
- package/dist/src/remote/network.js +0 -102
- package/dist/src/remote/pairing.d.ts +0 -63
- package/dist/src/remote/pairing.js +0 -299
- package/dist/src/remote/pem.d.ts +0 -2
- package/dist/src/remote/pem.js +0 -7
- package/dist/src/remote/serve.d.ts +0 -68
- package/dist/src/remote/serve.js +0 -244
- package/dist/src/remote/server.d.ts +0 -21
- package/dist/src/remote/server.js +0 -406
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ProviderRequestError, RetryableProviderError } from '../providers.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 const RELAY_PAYLOAD_LIMIT_BYTES = 12 * 1024 * 1024;
|
|
5
|
+
/** An unclaimed request is announced again this often, so a desktop that attaches later still sees it. */
|
|
6
|
+
export const RELAY_REANNOUNCE_MS = 5_000;
|
|
7
|
+
/** A claim with no progress for this long is released and the request is announced again. */
|
|
8
|
+
export const RELAY_CLAIM_SILENCE_MS = 45_000;
|
|
9
|
+
/** A request without a sign of life from a desktop for this long shows the run as awaiting-desktop. */
|
|
10
|
+
export const RELAY_AWAY_MS = 600_000;
|
|
11
|
+
/** One reasoning delta may be this large; a longer one is cut to whole characters that fit. */
|
|
12
|
+
export const RELAY_DELTA_LIMIT_BYTES = 64 * 1024;
|
|
13
|
+
export const RELAY_PAYLOAD_TOO_LARGE = 'This step\'s context is too large to send to your computer (limit 12 MiB).';
|
|
14
|
+
const CANCELLED = 'Provider request cancelled.';
|
|
15
|
+
/** The form a relayed failure's telemetry code must have. */
|
|
16
|
+
export const RELAY_FAILURE_CODE = /^[a-z0-9_]{1,64}$/;
|
|
17
|
+
function wirePayload(provider, request, sessionId) {
|
|
18
|
+
return {
|
|
19
|
+
model: request.model, messages: request.messages, tools: request.tools,
|
|
20
|
+
...(request.maxTokens === undefined ? {} : { maxTokens: request.maxTokens }),
|
|
21
|
+
...(request.mutableTail === undefined ? {} : { mutableTail: request.mutableTail }),
|
|
22
|
+
...(request.toolChoice === undefined ? {} : { toolChoice: request.toolChoice }),
|
|
23
|
+
...(request.context === undefined ? {} : { context: request.context }),
|
|
24
|
+
...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
|
|
25
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function readableToolCall(call) {
|
|
29
|
+
if (!call || typeof call !== 'object' || Array.isArray(call))
|
|
30
|
+
return false;
|
|
31
|
+
const value = call;
|
|
32
|
+
return typeof value.name === 'string' && typeof value.arguments === 'string' && (value.id === undefined || typeof value.id === 'string');
|
|
33
|
+
}
|
|
34
|
+
function readable(response) {
|
|
35
|
+
if (!response || typeof response !== 'object' || Array.isArray(response))
|
|
36
|
+
return false;
|
|
37
|
+
const value = response;
|
|
38
|
+
return typeof value.text === 'string' && Array.isArray(value.toolCalls) && value.toolCalls.every(readableToolCall);
|
|
39
|
+
}
|
|
40
|
+
/** `delta` cut to the whole characters that fit in RELAY_DELTA_LIMIT_BYTES. */
|
|
41
|
+
function boundedDelta(delta) {
|
|
42
|
+
if (Buffer.byteLength(delta) <= RELAY_DELTA_LIMIT_BYTES)
|
|
43
|
+
return delta;
|
|
44
|
+
return delta.slice(0, new TextEncoder().encodeInto(delta, new Uint8Array(RELAY_DELTA_LIMIT_BYTES)).read);
|
|
45
|
+
}
|
|
46
|
+
function failure(error) {
|
|
47
|
+
const message = typeof error?.message === 'string' && error.message.trim() ? error.message : 'The model request failed on your computer.';
|
|
48
|
+
const code = typeof error?.code === 'string' && RELAY_FAILURE_CODE.test(error.code) ? error.code : undefined;
|
|
49
|
+
let failed;
|
|
50
|
+
if (error?.kind === 'retryable')
|
|
51
|
+
failed = new RetryableProviderError(message);
|
|
52
|
+
else if (error?.kind === 'provider-request')
|
|
53
|
+
failed = new ProviderRequestError(message, error.contextOverflow === true);
|
|
54
|
+
else
|
|
55
|
+
return new Error(message);
|
|
56
|
+
if (code !== undefined)
|
|
57
|
+
failed.telemetryCode = code;
|
|
58
|
+
return failed;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The remote engine's half of the model relay: a relayed provider's `generate()` becomes a
|
|
62
|
+
* `model.relay.request` event that a desktop claims and answers with `model.relay.result`.
|
|
63
|
+
* A request never fails because no desktop is there; it waits, and the run shows awaiting-desktop.
|
|
64
|
+
*/
|
|
65
|
+
export class ModelRelayBroker {
|
|
66
|
+
deps;
|
|
67
|
+
pending = new Map();
|
|
68
|
+
timers;
|
|
69
|
+
constructor(deps) {
|
|
70
|
+
this.deps = deps;
|
|
71
|
+
this.timers = deps.timers ?? globalThis;
|
|
72
|
+
}
|
|
73
|
+
adapter(provider, runId, sessionId) {
|
|
74
|
+
return { generate: request => this.generate(provider, runId, request, sessionId) };
|
|
75
|
+
}
|
|
76
|
+
generate(provider, runId, request, sessionId) {
|
|
77
|
+
if (request.signal.aborted)
|
|
78
|
+
return Promise.reject(new Error(CANCELLED));
|
|
79
|
+
const payload = wirePayload(provider, request, sessionId);
|
|
80
|
+
const bytes = Buffer.byteLength(JSON.stringify(payload));
|
|
81
|
+
if (bytes > RELAY_PAYLOAD_LIMIT_BYTES)
|
|
82
|
+
return Promise.reject(new Error(RELAY_PAYLOAD_TOO_LARGE));
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
const entry = {
|
|
85
|
+
id: randomUUID(), runId, provider: provider.id, payload, bytes, request, away: false,
|
|
86
|
+
resolve: response => { this.finish(entry); resolve(response); },
|
|
87
|
+
reject: error => { this.finish(entry); reject(error); },
|
|
88
|
+
onAbort: () => {
|
|
89
|
+
if (!this.pending.has(entry.id))
|
|
90
|
+
return;
|
|
91
|
+
this.deps.emit('model.relay.cancel', { id: entry.id, runId });
|
|
92
|
+
entry.reject(new Error(CANCELLED));
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
this.pending.set(entry.id, entry);
|
|
96
|
+
request.signal.addEventListener('abort', entry.onAbort, { once: true });
|
|
97
|
+
this.touch(entry);
|
|
98
|
+
this.announce(entry);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** Takes a request for `claimant`; the payload is handed over only here, once the claim holds. */
|
|
102
|
+
claim(params) {
|
|
103
|
+
const entry = this.lookup(params.id, params.runId);
|
|
104
|
+
if (!entry || (entry.claimant !== undefined && entry.claimant !== params.claimant))
|
|
105
|
+
return { claimed: false };
|
|
106
|
+
if (entry.claimant === undefined) {
|
|
107
|
+
entry.claimant = params.claimant;
|
|
108
|
+
if (entry.announceTimer !== undefined) {
|
|
109
|
+
this.timers.clearInterval(entry.announceTimer);
|
|
110
|
+
entry.announceTimer = undefined;
|
|
111
|
+
}
|
|
112
|
+
entry.resumeBudget?.();
|
|
113
|
+
entry.resumeBudget = undefined;
|
|
114
|
+
}
|
|
115
|
+
this.touch(entry);
|
|
116
|
+
this.listen(entry);
|
|
117
|
+
return { claimed: true, payload: entry.payload };
|
|
118
|
+
}
|
|
119
|
+
progress(params) {
|
|
120
|
+
const entry = this.owned(params);
|
|
121
|
+
if (!entry)
|
|
122
|
+
return { ok: false };
|
|
123
|
+
this.touch(entry);
|
|
124
|
+
this.listen(entry);
|
|
125
|
+
const { request } = entry;
|
|
126
|
+
if (params.kind === 'request')
|
|
127
|
+
request.onRequest?.();
|
|
128
|
+
else if (params.kind === 'reasoning' && typeof params.delta === 'string')
|
|
129
|
+
request.onReasoning?.(boundedDelta(params.delta));
|
|
130
|
+
// A provider failure the desktop's adapter recovered from (a forced tool choice or streaming refused, then resent):
|
|
131
|
+
// only its telemetry code travels, in the form a relayed failure's code has.
|
|
132
|
+
else if (params.kind === 'recovered-error') {
|
|
133
|
+
if (typeof params.code === 'string' && RELAY_FAILURE_CODE.test(params.code))
|
|
134
|
+
request.onRecoveredError?.(params.code);
|
|
135
|
+
}
|
|
136
|
+
else if (params.kind === 'retry' && params.retry && typeof params.retry === 'object') {
|
|
137
|
+
// As with a local adapter, a retry listener that throws ends the call with its error.
|
|
138
|
+
Promise.resolve().then(() => request.onRetry?.(params.retry)).catch((error) => {
|
|
139
|
+
if (!this.pending.has(entry.id))
|
|
140
|
+
return;
|
|
141
|
+
this.deps.emit('model.relay.cancel', { id: entry.id, runId: entry.runId });
|
|
142
|
+
entry.reject(error instanceof Error ? error : new Error(String(error)));
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return { ok: true };
|
|
146
|
+
}
|
|
147
|
+
result(params) {
|
|
148
|
+
const entry = this.owned(params);
|
|
149
|
+
if (!entry)
|
|
150
|
+
return { ok: false };
|
|
151
|
+
if (params.ok) {
|
|
152
|
+
if (readable(params.response))
|
|
153
|
+
entry.resolve(params.response);
|
|
154
|
+
else
|
|
155
|
+
entry.reject(new Error('Your computer sent a model reply this machine could not read.'));
|
|
156
|
+
}
|
|
157
|
+
else
|
|
158
|
+
entry.reject(failure(params.error));
|
|
159
|
+
return { ok: true };
|
|
160
|
+
}
|
|
161
|
+
/** Whether `runId` has a request no desktop has shown a sign of life for in RELAY_AWAY_MS. */
|
|
162
|
+
awaiting(runId) {
|
|
163
|
+
return [...this.pending.values()].some(entry => entry.runId === runId && entry.away);
|
|
164
|
+
}
|
|
165
|
+
/** Rejects every wait of `runId` as cancelled and tells the desktops to stop. */
|
|
166
|
+
endRun(runId) {
|
|
167
|
+
// The run is ending: its own final state follows, so its requests are not reported back to running.
|
|
168
|
+
for (const entry of [...this.pending.values()])
|
|
169
|
+
if (entry.runId === runId) {
|
|
170
|
+
entry.away = false;
|
|
171
|
+
entry.onAbort();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
close() {
|
|
175
|
+
for (const entry of [...this.pending.values()]) {
|
|
176
|
+
entry.away = false;
|
|
177
|
+
entry.reject(new Error(CANCELLED));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
lookup(id, runId) {
|
|
181
|
+
const entry = typeof id === 'string' ? this.pending.get(id) : undefined;
|
|
182
|
+
return entry && entry.runId === runId ? entry : undefined;
|
|
183
|
+
}
|
|
184
|
+
owned(params) {
|
|
185
|
+
const entry = this.lookup(params.id, params.runId);
|
|
186
|
+
return entry && entry.claimant !== undefined && entry.claimant === params.claimant ? entry : undefined;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Announces an unclaimed request now and every RELAY_REANNOUNCE_MS, holding the run's budgets meanwhile. The
|
|
190
|
+
* announce carries no payload, so repeating it costs little; the payload goes once, to the claim that holds.
|
|
191
|
+
*/
|
|
192
|
+
announce(entry) {
|
|
193
|
+
entry.resumeBudget ??= this.deps.suspendBudget(entry.runId);
|
|
194
|
+
const announced = { id: entry.id, runId: entry.runId, provider: entry.provider, model: entry.payload.model, bytes: entry.bytes };
|
|
195
|
+
const emit = () => this.deps.emit('model.relay.request', { ...announced });
|
|
196
|
+
emit();
|
|
197
|
+
entry.announceTimer = this.timers.setInterval(emit, RELAY_REANNOUNCE_MS);
|
|
198
|
+
entry.announceTimer.unref?.();
|
|
199
|
+
}
|
|
200
|
+
/** (Re)starts the claimant's silence clock; when it runs out the claim is released and the request announced again. */
|
|
201
|
+
listen(entry) {
|
|
202
|
+
if (entry.silenceTimer !== undefined)
|
|
203
|
+
this.timers.clearTimeout(entry.silenceTimer);
|
|
204
|
+
entry.silenceTimer = this.timers.setTimeout(() => {
|
|
205
|
+
entry.silenceTimer = undefined;
|
|
206
|
+
if (!this.pending.has(entry.id))
|
|
207
|
+
return;
|
|
208
|
+
entry.claimant = undefined;
|
|
209
|
+
this.announce(entry);
|
|
210
|
+
}, RELAY_CLAIM_SILENCE_MS);
|
|
211
|
+
entry.silenceTimer.unref?.();
|
|
212
|
+
}
|
|
213
|
+
/** A sign of life: restarts the away clock, and a returning desktop brings the run back to running. */
|
|
214
|
+
touch(entry) {
|
|
215
|
+
if (entry.awayTimer !== undefined)
|
|
216
|
+
this.timers.clearTimeout(entry.awayTimer);
|
|
217
|
+
if (entry.away && entry.claimant !== undefined) {
|
|
218
|
+
entry.away = false;
|
|
219
|
+
this.reportBack(entry.runId);
|
|
220
|
+
}
|
|
221
|
+
entry.awayTimer = this.timers.setTimeout(() => {
|
|
222
|
+
entry.awayTimer = undefined;
|
|
223
|
+
if (!this.pending.has(entry.id) || entry.away)
|
|
224
|
+
return;
|
|
225
|
+
const shown = [...this.pending.values()].some(other => other.runId === entry.runId && other.away);
|
|
226
|
+
entry.away = true;
|
|
227
|
+
if (!shown)
|
|
228
|
+
this.deps.setRunState(entry.runId, 'awaiting-desktop');
|
|
229
|
+
}, RELAY_AWAY_MS);
|
|
230
|
+
entry.awayTimer.unref?.();
|
|
231
|
+
}
|
|
232
|
+
reportBack(runId) {
|
|
233
|
+
if (![...this.pending.values()].some(other => other.runId === runId && other.away))
|
|
234
|
+
this.deps.setRunState(runId, 'running');
|
|
235
|
+
}
|
|
236
|
+
finish(entry) {
|
|
237
|
+
if (!this.pending.delete(entry.id))
|
|
238
|
+
return;
|
|
239
|
+
entry.request.signal.removeEventListener('abort', entry.onAbort);
|
|
240
|
+
if (entry.announceTimer !== undefined)
|
|
241
|
+
this.timers.clearInterval(entry.announceTimer);
|
|
242
|
+
if (entry.silenceTimer !== undefined)
|
|
243
|
+
this.timers.clearTimeout(entry.silenceTimer);
|
|
244
|
+
if (entry.awayTimer !== undefined)
|
|
245
|
+
this.timers.clearTimeout(entry.awayTimer);
|
|
246
|
+
entry.resumeBudget?.();
|
|
247
|
+
entry.resumeBudget = undefined;
|
|
248
|
+
// A request that ends while away (its node or branch was stopped) no longer keeps the run shown as awaiting-desktop.
|
|
249
|
+
if (entry.away)
|
|
250
|
+
this.reportBack(entry.runId);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** At most this many runs are remembered per machine; recording another drops the oldest. */
|
|
2
|
+
export declare const MODEL_RELAY_RUNS_LIMIT = 500;
|
|
3
|
+
/** By account subject, then by machine: the runs this computer started or resumed there, most recent last. */
|
|
4
|
+
export type ModelRelayRuns = Record<string, Record<string, string[]>>;
|
|
5
|
+
export declare function modelRelayRunsPath(home: string): string;
|
|
6
|
+
/**
|
|
7
|
+
* The runs whose model requests this computer answers: those it started or resumed on a machine, per account, in
|
|
8
|
+
* `<home>/model-relay-runs.json`. Writes are serialized and go through a temporary file and a rename.
|
|
9
|
+
*/
|
|
10
|
+
export declare class ModelRelayRunStore {
|
|
11
|
+
private readonly home;
|
|
12
|
+
private chain;
|
|
13
|
+
private cache;
|
|
14
|
+
/** How many times the file was read; it is read once and then kept. */
|
|
15
|
+
fileReads: number;
|
|
16
|
+
constructor(home: string);
|
|
17
|
+
/** Whether `subject` started or resumed `runId` on `env` from this computer. */
|
|
18
|
+
has(subject: string | undefined, env: string, runId: string): Promise<boolean>;
|
|
19
|
+
/** Records `runId` as started or resumed on `env` from this computer, as the most recent. */
|
|
20
|
+
record(subject: string, env: string, runId: string): Promise<void>;
|
|
21
|
+
/** Forgets every run of `env`, for every account: the machine was removed. */
|
|
22
|
+
forget(env: string): Promise<void>;
|
|
23
|
+
/** Forgets `subject`'s runs on each of `envs`: they left that account's list. */
|
|
24
|
+
forgetFor(subject: string, envs: Iterable<string>): Promise<void>;
|
|
25
|
+
/** Resolves once every write begun so far has finished. */
|
|
26
|
+
settled(): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* The file's contents, read once and kept: only this process writes the file, and each write replaces the copy.
|
|
29
|
+
* A file that is missing is empty; one that cannot be read is read again next time.
|
|
30
|
+
*/
|
|
31
|
+
private read;
|
|
32
|
+
private load;
|
|
33
|
+
private change;
|
|
34
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
/** At most this many runs are remembered per machine; recording another drops the oldest. */
|
|
5
|
+
export const MODEL_RELAY_RUNS_LIMIT = 500;
|
|
6
|
+
const ENVIRONMENT_ID = /^env_[A-Za-z0-9_-]{22}$/;
|
|
7
|
+
const ACCOUNT_SUBJECT = /^[A-Za-z0-9-]{1,128}$/;
|
|
8
|
+
const MAX_RUN_ID = 128;
|
|
9
|
+
export function modelRelayRunsPath(home) {
|
|
10
|
+
return join(home, 'model-relay-runs.json');
|
|
11
|
+
}
|
|
12
|
+
function usableRun(runId) {
|
|
13
|
+
return typeof runId === 'string' && runId.length > 0 && runId.length <= MAX_RUN_ID;
|
|
14
|
+
}
|
|
15
|
+
/** The saved file, keeping only well-formed entries; a missing or unreadable file is empty. */
|
|
16
|
+
function parse(text) {
|
|
17
|
+
let value;
|
|
18
|
+
try {
|
|
19
|
+
value = JSON.parse(text);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
const runs = {};
|
|
25
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
26
|
+
return runs;
|
|
27
|
+
for (const [subject, machines] of Object.entries(value)) {
|
|
28
|
+
if (!ACCOUNT_SUBJECT.test(subject) || !machines || typeof machines !== 'object' || Array.isArray(machines))
|
|
29
|
+
continue;
|
|
30
|
+
const kept = {};
|
|
31
|
+
for (const [env, ids] of Object.entries(machines)) {
|
|
32
|
+
if (!ENVIRONMENT_ID.test(env) || !Array.isArray(ids))
|
|
33
|
+
continue;
|
|
34
|
+
kept[env] = ids.filter(usableRun).slice(-MODEL_RELAY_RUNS_LIMIT);
|
|
35
|
+
}
|
|
36
|
+
runs[subject] = kept;
|
|
37
|
+
}
|
|
38
|
+
return runs;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The runs whose model requests this computer answers: those it started or resumed on a machine, per account, in
|
|
42
|
+
* `<home>/model-relay-runs.json`. Writes are serialized and go through a temporary file and a rename.
|
|
43
|
+
*/
|
|
44
|
+
export class ModelRelayRunStore {
|
|
45
|
+
home;
|
|
46
|
+
chain = Promise.resolve();
|
|
47
|
+
cache;
|
|
48
|
+
/** How many times the file was read; it is read once and then kept. */
|
|
49
|
+
fileReads = 0;
|
|
50
|
+
constructor(home) {
|
|
51
|
+
this.home = home;
|
|
52
|
+
}
|
|
53
|
+
/** Whether `subject` started or resumed `runId` on `env` from this computer. */
|
|
54
|
+
async has(subject, env, runId) {
|
|
55
|
+
if (subject === undefined)
|
|
56
|
+
return false;
|
|
57
|
+
const runs = await this.read();
|
|
58
|
+
return Object.hasOwn(runs, subject) && Object.hasOwn(runs[subject], env) && runs[subject][env].includes(runId);
|
|
59
|
+
}
|
|
60
|
+
/** Records `runId` as started or resumed on `env` from this computer, as the most recent. */
|
|
61
|
+
record(subject, env, runId) {
|
|
62
|
+
if (!ACCOUNT_SUBJECT.test(subject) || !ENVIRONMENT_ID.test(env) || !usableRun(runId))
|
|
63
|
+
return Promise.resolve();
|
|
64
|
+
return this.change(runs => {
|
|
65
|
+
const machines = Object.hasOwn(runs, subject) ? runs[subject] : (runs[subject] = {});
|
|
66
|
+
const list = (Object.hasOwn(machines, env) ? machines[env] : []).filter(id => id !== runId);
|
|
67
|
+
list.push(runId);
|
|
68
|
+
machines[env] = list.slice(-MODEL_RELAY_RUNS_LIMIT);
|
|
69
|
+
return true;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Forgets every run of `env`, for every account: the machine was removed. */
|
|
73
|
+
forget(env) {
|
|
74
|
+
return this.change(runs => {
|
|
75
|
+
let changed = false;
|
|
76
|
+
for (const machines of Object.values(runs))
|
|
77
|
+
if (Object.hasOwn(machines, env)) {
|
|
78
|
+
delete machines[env];
|
|
79
|
+
changed = true;
|
|
80
|
+
}
|
|
81
|
+
return changed;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Forgets `subject`'s runs on each of `envs`: they left that account's list. */
|
|
85
|
+
forgetFor(subject, envs) {
|
|
86
|
+
return this.change(runs => {
|
|
87
|
+
if (!Object.hasOwn(runs, subject))
|
|
88
|
+
return false;
|
|
89
|
+
let changed = false;
|
|
90
|
+
for (const env of envs)
|
|
91
|
+
if (Object.hasOwn(runs[subject], env)) {
|
|
92
|
+
delete runs[subject][env];
|
|
93
|
+
changed = true;
|
|
94
|
+
}
|
|
95
|
+
return changed;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/** Resolves once every write begun so far has finished. */
|
|
99
|
+
async settled() {
|
|
100
|
+
await this.chain.catch(() => undefined);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The file's contents, read once and kept: only this process writes the file, and each write replaces the copy.
|
|
104
|
+
* A file that is missing is empty; one that cannot be read is read again next time.
|
|
105
|
+
*/
|
|
106
|
+
async read() {
|
|
107
|
+
await this.chain.catch(() => undefined);
|
|
108
|
+
return this.load();
|
|
109
|
+
}
|
|
110
|
+
async load() {
|
|
111
|
+
if (this.cache !== undefined)
|
|
112
|
+
return this.cache;
|
|
113
|
+
this.fileReads += 1;
|
|
114
|
+
try {
|
|
115
|
+
this.cache = parse(await readFile(modelRelayRunsPath(this.home), 'utf8'));
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
if (error.code !== 'ENOENT')
|
|
119
|
+
return {};
|
|
120
|
+
this.cache = {};
|
|
121
|
+
}
|
|
122
|
+
return this.cache;
|
|
123
|
+
}
|
|
124
|
+
change(apply) {
|
|
125
|
+
const next = this.chain.catch(() => undefined).then(async () => {
|
|
126
|
+
const path = modelRelayRunsPath(this.home);
|
|
127
|
+
// A copy: the kept contents change only once the write has landed.
|
|
128
|
+
const runs = structuredClone(await this.load());
|
|
129
|
+
if (!apply(runs))
|
|
130
|
+
return;
|
|
131
|
+
await mkdir(dirname(path), { recursive: true });
|
|
132
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
133
|
+
try {
|
|
134
|
+
await writeFile(temporary, `${JSON.stringify(runs, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
135
|
+
await rename(temporary, path);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
this.cache = runs;
|
|
142
|
+
});
|
|
143
|
+
this.chain = next;
|
|
144
|
+
return next;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connection ids a desktop engine opens for itself to answer a machine's model requests start with this. The
|
|
3
|
+
* machine's engine pool sends such a connection only `model.relay.*` events, and no replay of its runs.
|
|
4
|
+
*/
|
|
5
|
+
export declare const MODEL_RELAY_CONNECTION_PREFIX = "relay-";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connection ids a desktop engine opens for itself to answer a machine's model requests start with this. The
|
|
3
|
+
* machine's engine pool sends such a connection only `model.relay.*` events, and no replay of its runs.
|
|
4
|
+
*/
|
|
5
|
+
export const MODEL_RELAY_CONNECTION_PREFIX = 'relay-';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offline plan pass.
|
|
3
|
+
*
|
|
4
|
+
* When the account service answers a plan check it also returns a pass: the account, its plan, when
|
|
5
|
+
* the pass was issued and when it lapses, signed with a key whose private half stays in the
|
|
6
|
+
* service's key store. This module checks that signature with the public half, so a pass whose
|
|
7
|
+
* dates were edited on disk is rejected, and lets a valid pass stand in for the plan check while the
|
|
8
|
+
* service cannot be reached.
|
|
9
|
+
*
|
|
10
|
+
* The clock is not trusted. Beside the pass the file keeps the latest time this machine has seen,
|
|
11
|
+
* which only moves forward, and a system clock earlier than that is treated as tampering. A machine
|
|
12
|
+
* its owner controls can still restore both the pass and that record from a copy; this stops an
|
|
13
|
+
* edited date and a moved clock, not a restored backup.
|
|
14
|
+
*/
|
|
15
|
+
/** Public keys that sign passes, as base64 DER (SubjectPublicKeyInfo), newest first. Empty until the key exists. */
|
|
16
|
+
export declare const PLAN_PASS_KEYS: readonly string[];
|
|
17
|
+
export type PlanPassTier = 'free' | 'legacy' | 'paid';
|
|
18
|
+
export interface PlanPass {
|
|
19
|
+
subject: string;
|
|
20
|
+
tier: PlanPassTier;
|
|
21
|
+
paid: boolean;
|
|
22
|
+
issuedAt: number;
|
|
23
|
+
expiresAt: number;
|
|
24
|
+
}
|
|
25
|
+
export interface OfflinePlan extends PlanPass {
|
|
26
|
+
offline: true;
|
|
27
|
+
}
|
|
28
|
+
/** The claims of a pass one of `keys` signed, in milliseconds, or undefined for anything else. */
|
|
29
|
+
export declare function verifyPlanPass(token: unknown, keys?: readonly string[]): PlanPass | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Keeps the pass an online plan check returned. `serverTime` is the service's own clock from that
|
|
32
|
+
* answer; it replaces the latest time seen, so a machine whose clock once ran ahead recovers the
|
|
33
|
+
* next time it is online. A pass that does not verify, names another account, or disagrees with
|
|
34
|
+
* the `plan` the service just answered is not kept.
|
|
35
|
+
*
|
|
36
|
+
* When the answer brings no pass worth keeping, a pass already stored survives only if it still
|
|
37
|
+
* says what the service just said. A downgrade the service confirmed therefore ends the old pass at
|
|
38
|
+
* once, even when the service could not sign a new one.
|
|
39
|
+
*/
|
|
40
|
+
export declare function storePlanPass(token: unknown, subject: string, home: string, options?: {
|
|
41
|
+
serverTime?: number;
|
|
42
|
+
now?: number;
|
|
43
|
+
keys?: readonly string[];
|
|
44
|
+
plan?: {
|
|
45
|
+
paid: boolean;
|
|
46
|
+
tier?: string;
|
|
47
|
+
};
|
|
48
|
+
}): Promise<boolean>;
|
|
49
|
+
/**
|
|
50
|
+
* The plan a stored pass grants `subject` right now, while the service cannot be reached.
|
|
51
|
+
*
|
|
52
|
+
* Nothing is granted when the pass does not verify, names another account, has lapsed, when the
|
|
53
|
+
* record of the latest time seen is missing, or when the system clock is behind that record. Each
|
|
54
|
+
* use moves the record forward, so time spent offline is not handed back by turning the clock back.
|
|
55
|
+
*/
|
|
56
|
+
export declare function readOfflinePlan(subject: string | undefined, home: string, options?: {
|
|
57
|
+
now?: number;
|
|
58
|
+
keys?: readonly string[];
|
|
59
|
+
}): Promise<OfflinePlan | undefined>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { createPublicKey, randomBytes, verify } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* The offline plan pass.
|
|
6
|
+
*
|
|
7
|
+
* When the account service answers a plan check it also returns a pass: the account, its plan, when
|
|
8
|
+
* the pass was issued and when it lapses, signed with a key whose private half stays in the
|
|
9
|
+
* service's key store. This module checks that signature with the public half, so a pass whose
|
|
10
|
+
* dates were edited on disk is rejected, and lets a valid pass stand in for the plan check while the
|
|
11
|
+
* service cannot be reached.
|
|
12
|
+
*
|
|
13
|
+
* The clock is not trusted. Beside the pass the file keeps the latest time this machine has seen,
|
|
14
|
+
* which only moves forward, and a system clock earlier than that is treated as tampering. A machine
|
|
15
|
+
* its owner controls can still restore both the pass and that record from a copy; this stops an
|
|
16
|
+
* edited date and a moved clock, not a restored backup.
|
|
17
|
+
*/
|
|
18
|
+
/** Public keys that sign passes, as base64 DER (SubjectPublicKeyInfo), newest first. Empty until the key exists. */
|
|
19
|
+
export const PLAN_PASS_KEYS = [];
|
|
20
|
+
/** A pass never grants more than this, whatever it says: the service caps a pass at 31 days. */
|
|
21
|
+
const MAX_LIFETIME_MS = 32 * 86_400_000;
|
|
22
|
+
/** How far behind the latest time seen the system clock may be: ordinary drift and time-zone fixes. */
|
|
23
|
+
const CLOCK_SLACK_MS = 5 * 60_000;
|
|
24
|
+
const FILE = 'plan-pass.json';
|
|
25
|
+
function importKeys(keys) {
|
|
26
|
+
const imported = [];
|
|
27
|
+
for (const key of keys) {
|
|
28
|
+
try {
|
|
29
|
+
imported.push(createPublicKey({ key: Buffer.from(key, 'base64'), format: 'der', type: 'spki' }));
|
|
30
|
+
}
|
|
31
|
+
catch { /* an unusable key signs nothing */ }
|
|
32
|
+
}
|
|
33
|
+
return imported;
|
|
34
|
+
}
|
|
35
|
+
/** The claims of a pass one of `keys` signed, in milliseconds, or undefined for anything else. */
|
|
36
|
+
export function verifyPlanPass(token, keys = PLAN_PASS_KEYS) {
|
|
37
|
+
if (typeof token !== 'string' || token.length > 4096)
|
|
38
|
+
return undefined;
|
|
39
|
+
const parts = token.split('.');
|
|
40
|
+
if (parts.length !== 2 || !parts.every(part => /^[A-Za-z0-9_-]+$/.test(part)))
|
|
41
|
+
return undefined;
|
|
42
|
+
const signature = Buffer.from(parts[1], 'base64url');
|
|
43
|
+
if (!importKeys(keys).some(key => { try {
|
|
44
|
+
return verify('sha256', Buffer.from(parts[0], 'ascii'), key, signature);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
} }))
|
|
49
|
+
return undefined;
|
|
50
|
+
let claims;
|
|
51
|
+
try {
|
|
52
|
+
claims = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
if (!claims || typeof claims !== 'object' || Array.isArray(claims))
|
|
58
|
+
return undefined;
|
|
59
|
+
const { v, sub, tier, paid, iat, exp } = claims;
|
|
60
|
+
if (v !== 1 || typeof sub !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(sub))
|
|
61
|
+
return undefined;
|
|
62
|
+
if (tier !== 'free' && tier !== 'legacy' && tier !== 'paid')
|
|
63
|
+
return undefined;
|
|
64
|
+
if (paid !== (tier !== 'free'))
|
|
65
|
+
return undefined;
|
|
66
|
+
if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp) || iat <= 0 || exp <= iat)
|
|
67
|
+
return undefined;
|
|
68
|
+
const issuedAt = iat * 1000, expiresAt = exp * 1000;
|
|
69
|
+
if (expiresAt - issuedAt > MAX_LIFETIME_MS)
|
|
70
|
+
return undefined;
|
|
71
|
+
return { subject: sub, tier, paid, issuedAt, expiresAt };
|
|
72
|
+
}
|
|
73
|
+
async function readStored(home) {
|
|
74
|
+
try {
|
|
75
|
+
const value = JSON.parse(await readFile(join(home, FILE), 'utf8'));
|
|
76
|
+
if (!value || typeof value !== 'object')
|
|
77
|
+
return undefined;
|
|
78
|
+
const { pass, lastSeen } = value;
|
|
79
|
+
return typeof pass === 'string' && Number.isSafeInteger(lastSeen) && lastSeen > 0 ? { pass, lastSeen: lastSeen } : undefined;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async function writeStored(home, stored) {
|
|
86
|
+
await mkdir(home, { recursive: true });
|
|
87
|
+
// Each write stages its own file: two plan checks finishing together must not share one.
|
|
88
|
+
const path = join(home, FILE), staged = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
await writeFile(staged, JSON.stringify(stored), { mode: 0o600 });
|
|
91
|
+
await rename(staged, path);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
await unlink(staged).catch(() => { });
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** One read-and-update of a home's record at a time in this process, so none works from a stale copy. */
|
|
99
|
+
const queues = new Map();
|
|
100
|
+
function serial(home, task) {
|
|
101
|
+
const run = (queues.get(home) ?? Promise.resolve()).then(task, task);
|
|
102
|
+
const settled = run.catch(() => { });
|
|
103
|
+
queues.set(home, settled);
|
|
104
|
+
void settled.then(() => { if (queues.get(home) === settled)
|
|
105
|
+
queues.delete(home); });
|
|
106
|
+
return run;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Keeps the pass an online plan check returned. `serverTime` is the service's own clock from that
|
|
110
|
+
* answer; it replaces the latest time seen, so a machine whose clock once ran ahead recovers the
|
|
111
|
+
* next time it is online. A pass that does not verify, names another account, or disagrees with
|
|
112
|
+
* the `plan` the service just answered is not kept.
|
|
113
|
+
*
|
|
114
|
+
* When the answer brings no pass worth keeping, a pass already stored survives only if it still
|
|
115
|
+
* says what the service just said. A downgrade the service confirmed therefore ends the old pass at
|
|
116
|
+
* once, even when the service could not sign a new one.
|
|
117
|
+
*/
|
|
118
|
+
export function storePlanPass(token, subject, home, options = {}) {
|
|
119
|
+
const agrees = (pass) => pass !== undefined && pass.subject === subject
|
|
120
|
+
&& (options.plan === undefined || (pass.paid === options.plan.paid && (options.plan.tier === undefined || pass.tier === options.plan.tier)));
|
|
121
|
+
return serial(home, async () => {
|
|
122
|
+
const pass = verifyPlanPass(token, options.keys);
|
|
123
|
+
if (!agrees(pass)) {
|
|
124
|
+
const stored = await readStored(home);
|
|
125
|
+
if (stored && !agrees(verifyPlanPass(stored.pass, options.keys)))
|
|
126
|
+
await unlink(join(home, FILE)).catch(() => { });
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
const now = options.now ?? Date.now();
|
|
130
|
+
const serverTime = options.serverTime !== undefined && Number.isFinite(options.serverTime) ? options.serverTime : undefined;
|
|
131
|
+
await writeStored(home, { pass: token, lastSeen: Math.max(serverTime ?? now, pass.issuedAt) });
|
|
132
|
+
return true;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The plan a stored pass grants `subject` right now, while the service cannot be reached.
|
|
137
|
+
*
|
|
138
|
+
* Nothing is granted when the pass does not verify, names another account, has lapsed, when the
|
|
139
|
+
* record of the latest time seen is missing, or when the system clock is behind that record. Each
|
|
140
|
+
* use moves the record forward, so time spent offline is not handed back by turning the clock back.
|
|
141
|
+
*/
|
|
142
|
+
export function readOfflinePlan(subject, home, options = {}) {
|
|
143
|
+
return serial(home, () => readOfflinePlanNow(subject, home, options));
|
|
144
|
+
}
|
|
145
|
+
async function readOfflinePlanNow(subject, home, options) {
|
|
146
|
+
if (!subject)
|
|
147
|
+
return undefined;
|
|
148
|
+
const stored = await readStored(home);
|
|
149
|
+
if (!stored)
|
|
150
|
+
return undefined;
|
|
151
|
+
const pass = verifyPlanPass(stored.pass, options.keys);
|
|
152
|
+
if (!pass || pass.subject !== subject)
|
|
153
|
+
return undefined;
|
|
154
|
+
const now = options.now ?? Date.now();
|
|
155
|
+
const floor = Math.max(stored.lastSeen, pass.issuedAt);
|
|
156
|
+
if (now < floor - CLOCK_SLACK_MS)
|
|
157
|
+
return undefined;
|
|
158
|
+
const current = Math.max(now, floor);
|
|
159
|
+
// Recorded before the expiry is judged: a pass seen lapsed stays lapsed when the clock is moved back.
|
|
160
|
+
if (current > stored.lastSeen)
|
|
161
|
+
await writeStored(home, { pass: stored.pass, lastSeen: current }).catch(() => { });
|
|
162
|
+
if (current >= pass.expiresAt)
|
|
163
|
+
return undefined;
|
|
164
|
+
return { ...pass, offline: true };
|
|
165
|
+
}
|