@zvada/agent-server 0.3.23 → 0.3.25
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/CHANGELOG.md +64 -0
- package/README.md +14 -5
- package/dist/accounts/chatgpt.js +144 -0
- package/dist/accounts/check.js +71 -0
- package/dist/accounts/claude.js +80 -0
- package/dist/accounts/endpoint.js +104 -0
- package/dist/accounts/http.js +58 -0
- package/dist/accounts/index.js +9 -0
- package/dist/client/client.js +745 -0
- package/dist/client/connection.js +338 -0
- package/dist/client/history.js +49 -0
- package/dist/client/index.js +6 -0
- package/dist/client/listeners.js +19 -0
- package/dist/client/logins.js +92 -0
- package/dist/client/rpc.js +105 -0
- package/dist/client/streams.js +432 -0
- package/dist/client/transports.js +118 -0
- package/dist/client/turns.js +122 -0
- package/dist/core/agents/acp/acp-agent.js +425 -0
- package/dist/core/agents/acp/adapter.js +231 -0
- package/dist/core/agents/acp/client.js +222 -0
- package/dist/core/agents/acp/known-agents.js +57 -0
- package/dist/core/agents/acp/mappings.js +164 -0
- package/dist/core/agents/acp/requests.js +79 -0
- package/dist/core/agents/attachments.js +14 -0
- package/dist/core/agents/base.js +64 -0
- package/dist/core/agents/claude-code/adapter.js +474 -0
- package/dist/core/agents/claude-code/approvals.js +245 -0
- package/dist/core/agents/claude-code/claude-agent.js +319 -0
- package/dist/core/agents/claude-code/credentials.js +142 -0
- package/dist/core/agents/claude-code/events.js +11 -0
- package/dist/core/agents/claude-code/login.js +217 -0
- package/dist/core/agents/claude-code/mcp.js +181 -0
- package/dist/core/agents/claude-code/models.js +74 -0
- package/dist/core/agents/claude-code/options.js +240 -0
- package/dist/core/agents/claude-code/outcome.js +204 -0
- package/dist/core/agents/claude-code/results.js +58 -0
- package/dist/core/agents/claude-code/sdk-pair.js +59 -0
- package/dist/core/agents/claude-code/session.js +593 -0
- package/dist/core/agents/claude-code/spawn.js +125 -0
- package/dist/core/agents/claude-code/spend.js +118 -0
- package/dist/core/agents/claude-code/tools.js +131 -0
- package/dist/core/agents/claude-code/turn-usage.js +121 -0
- package/dist/core/agents/claude-code/turn.js +199 -0
- package/dist/core/agents/codex-app-server/adapter.js +463 -0
- package/dist/core/agents/codex-app-server/client.js +338 -0
- package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
- package/dist/core/agents/codex-app-server/commands.js +184 -0
- package/dist/core/agents/codex-app-server/credentials.js +92 -0
- package/dist/core/agents/codex-app-server/effort.js +13 -0
- package/dist/core/agents/codex-app-server/events.js +18 -0
- package/dist/core/agents/codex-app-server/homes.js +118 -0
- package/dist/core/agents/codex-app-server/input.js +52 -0
- package/dist/core/agents/codex-app-server/items.js +307 -0
- package/dist/core/agents/codex-app-server/login.js +183 -0
- package/dist/core/agents/codex-app-server/mcp.js +323 -0
- package/dist/core/agents/codex-app-server/models.js +160 -0
- package/dist/core/agents/codex-app-server/options.js +155 -0
- package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
- package/dist/core/agents/codex-app-server/protocol.js +38 -0
- package/dist/core/agents/codex-app-server/requests.js +250 -0
- package/dist/core/agents/codex-app-server/session.js +278 -0
- package/dist/core/agents/codex-app-server/subagents.js +260 -0
- package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
- package/dist/core/agents/codex-app-server/turn-items.js +69 -0
- package/dist/core/agents/codex-app-server/turn.js +448 -0
- package/dist/core/agents/codex-app-server/user-login.js +78 -0
- package/dist/core/agents/config-fingerprint.js +10 -0
- package/dist/core/agents/credentials.js +71 -0
- package/dist/core/agents/diffs.js +27 -0
- package/dist/core/agents/elicitation.js +42 -0
- package/dist/core/agents/inherit-config.js +5 -0
- package/dist/core/agents/login.js +56 -0
- package/dist/core/agents/mcp-config.js +109 -0
- package/dist/core/agents/plan.js +6 -0
- package/dist/core/agents/process-pool.js +307 -0
- package/dist/core/agents/registry.js +49 -0
- package/dist/core/agents/scripted/adapter.js +86 -0
- package/dist/core/agents/scripted/mcp-call.js +74 -0
- package/dist/core/agents/scripted/scripted-agent.js +331 -0
- package/dist/core/agents/scripted/scripts.js +154 -0
- package/dist/core/agents/scripted/steps.js +87 -0
- package/dist/core/agents/session-agent.js +209 -0
- package/dist/core/agents/stderr-tail.js +71 -0
- package/dist/core/agents/thinking-levels.js +9 -0
- package/dist/core/agents/types.js +1 -0
- package/dist/core/diagnostics.js +23 -0
- package/dist/core/index.js +31 -0
- package/dist/core/presets.js +114 -0
- package/dist/core/processes/identity.js +92 -0
- package/dist/core/processes/lifeline.js +218 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +164 -0
- package/dist/core/provision/cache-trust.js +121 -0
- package/dist/core/provision/cache-usage.js +61 -0
- package/dist/core/provision/checksums.js +22 -0
- package/dist/core/provision/extract.js +29 -0
- package/dist/core/provision/index.js +4 -0
- package/dist/core/provision/install-build.js +99 -0
- package/dist/core/provision/npm.js +316 -0
- package/dist/core/provision/pins.js +35 -0
- package/dist/core/provision/platform.js +65 -0
- package/dist/core/provision/provisioner.js +372 -0
- package/dist/core/provision/releases.js +68 -0
- package/dist/core/provision/tools.js +279 -0
- package/dist/core/proxy/anthropic-proxy.js +163 -0
- package/dist/core/proxy/api-key-store.js +30 -0
- package/dist/core/proxy/index.js +3 -0
- package/dist/core/proxy/loopback.js +86 -0
- package/dist/core/runtime/agent-runtime.js +437 -0
- package/dist/core/runtime/event-processor.js +379 -0
- package/dist/core/runtime/event-sink.js +65 -0
- package/dist/core/runtime/harness-clis.js +83 -0
- package/dist/core/runtime/harness-logins.js +313 -0
- package/dist/core/runtime/login-reads.js +71 -0
- package/dist/core/runtime/model-lists.js +160 -0
- package/dist/core/runtime/permission-policy.js +84 -0
- package/dist/core/runtime/request-broker.js +139 -0
- package/dist/core/runtime/steering.js +79 -0
- package/dist/core/runtime/turn-outcome.js +16 -0
- package/dist/core/runtime/turn.js +339 -0
- package/dist/core/utils/bounded.js +13 -0
- package/dist/core/utils/deadline.js +57 -0
- package/dist/core/utils/errors.js +176 -0
- package/dist/core/utils/is-record.js +4 -0
- package/dist/core/utils/loopback.js +11 -0
- package/dist/index.js +4 -0
- package/dist/operator/index.js +10 -0
- package/dist/operator/mcp.js +139 -0
- package/dist/operator/operator.js +499 -0
- package/dist/operator/render.js +408 -0
- package/dist/operator/view.js +35 -0
- package/dist/protocol/account.js +96 -0
- package/dist/protocol/async-queue.js +65 -0
- package/dist/protocol/auth.js +169 -0
- package/dist/protocol/canonical.js +18 -0
- package/dist/protocol/clis.js +63 -0
- package/dist/protocol/config.js +137 -0
- package/dist/protocol/conversation.js +231 -0
- package/dist/protocol/credentials.js +142 -0
- package/dist/protocol/errors.js +190 -0
- package/dist/protocol/execution.js +28 -0
- package/dist/protocol/factories.js +231 -0
- package/dist/protocol/guards.js +71 -0
- package/dist/protocol/harness.js +93 -0
- package/dist/protocol/history.js +201 -0
- package/dist/protocol/ids.js +37 -0
- package/dist/protocol/index.js +36 -0
- package/dist/protocol/lifecycle.js +562 -0
- package/dist/protocol/meta-keys.js +17 -0
- package/dist/protocol/meta.js +13 -0
- package/dist/protocol/model-catalog.js +223 -0
- package/dist/protocol/models.js +84 -0
- package/dist/protocol/part-input.js +94 -0
- package/dist/protocol/parts.js +166 -0
- package/dist/protocol/plan.js +31 -0
- package/dist/protocol/reduce.js +484 -0
- package/dist/protocol/selectors.js +136 -0
- package/dist/protocol/seq-cursor.js +37 -0
- package/dist/protocol/stop-reasons.js +41 -0
- package/dist/protocol/thinking.js +31 -0
- package/dist/protocol/time.js +21 -0
- package/dist/protocol/tokens.js +57 -0
- package/dist/protocol/tool-closure.js +70 -0
- package/dist/protocol/tool-state.js +153 -0
- package/dist/protocol/verify.js +467 -0
- package/dist/protocol/vocabulary.js +27 -0
- package/dist/protocol/wire-api.js +94 -0
- package/dist/protocol/wire.js +669 -0
- package/dist/server/acp/binding.js +251 -0
- package/dist/server/acp/session-records.js +53 -0
- package/dist/server/acp/translate.js +401 -0
- package/dist/server/agent-server.js +338 -0
- package/dist/server/bin.js +492 -0
- package/dist/server/feedback.js +216 -0
- package/dist/server/history.js +123 -0
- package/dist/server/index.js +8 -0
- package/dist/server/install.js +171 -0
- package/dist/server/open-parts.js +87 -0
- package/dist/server/routes.js +292 -0
- package/dist/server/secrets.js +19 -0
- package/dist/server/session-gate.js +54 -0
- package/dist/server/session-log.js +66 -0
- package/dist/server/session-store.js +243 -0
- package/dist/server/subscriptions.js +189 -0
- package/dist/server/transports.js +214 -0
- package/dist/server/wire-error.js +26 -0
- package/dist/sync/event-log.js +89 -0
- package/dist/sync/fit.js +202 -0
- package/dist/sync/history-reader.js +33 -0
- package/dist/sync/history-sqlite.js +281 -0
- package/dist/sync/history.js +163 -0
- package/dist/sync/index.js +5 -0
- package/dist/sync/journal-sqlite.js +316 -0
- package/dist/sync/journal.js +10 -0
- package/dist/sync/live-tails.js +85 -0
- package/dist/sync/node-sqlite.js +27 -0
- package/dist/sync/projection.js +32 -0
- package/dist/sync/recovery.js +117 -0
- package/dist/sync/retry.js +45 -0
- package/dist/sync/schema.js +73 -0
- package/dist/sync/sql.js +94 -0
- package/dist/sync/sqlite-file.js +31 -0
- package/dist/sync/sqlite.js +18 -0
- package/dist/sync/worker.js +212 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +28 -11
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/session.d.ts +8 -0
- package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
- package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
- package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
- package/dist/types/core/agents/process-pool.d.ts +8 -0
- package/dist/types/core/agents/process-pool.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- package/dist/types/server/routes.d.ts.map +1 -1
- package/dist/types/server/transports.d.ts +2 -1
- package/dist/types/server/transports.d.ts.map +1 -1
- package/dist/types/sync/node-sqlite.d.ts +4 -1
- package/dist/types/sync/node-sqlite.d.ts.map +1 -1
- package/docs/consuming.md +56 -7
- package/docs/deploy.md +35 -0
- package/docs/harnesses.md +30 -5
- package/package.json +43 -18
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/approvals.ts +5 -1
- package/src/core/agents/claude-code/claude-agent.ts +32 -5
- package/src/core/agents/claude-code/options.ts +28 -11
- package/src/core/agents/claude-code/session.ts +13 -0
- package/src/core/agents/codex-app-server/homes.ts +11 -2
- package/src/core/agents/codex-app-server/login.ts +30 -0
- package/src/core/agents/codex-app-server/requests.ts +7 -6
- package/src/core/agents/codex-app-server/session.ts +11 -2
- package/src/core/agents/process-pool.ts +30 -4
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/presets.ts +3 -2
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/bin.ts +25 -10
- package/src/server/routes.ts +3 -2
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { generateUUIDv7 } from "../../protocol/index.js";
|
|
2
|
+
import { onAbort } from "../utils/deadline.js";
|
|
3
|
+
/** How a cancel, a turn's end or an expiry answers each kind. */
|
|
4
|
+
const CANCELLED = {
|
|
5
|
+
permission: { outcome: "cancelled" },
|
|
6
|
+
elicitation: { action: "cancel" },
|
|
7
|
+
};
|
|
8
|
+
/** An accepted outcome with every secret question's answer masked. */
|
|
9
|
+
function redactSecrets(outcome, questions) {
|
|
10
|
+
const secret = new Set((questions ?? []).filter((q) => q.secret).map((q) => q.id));
|
|
11
|
+
if (outcome.action !== "accept" || !outcome.content || secret.size === 0)
|
|
12
|
+
return outcome;
|
|
13
|
+
return {
|
|
14
|
+
...outcome,
|
|
15
|
+
content: Object.fromEntries(Object.entries(outcome.content).map(([id, answer]) => [
|
|
16
|
+
id,
|
|
17
|
+
secret.has(id) ? ["[secret]"] : answer,
|
|
18
|
+
])),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A turn's open requests (permissions and elicitations), from asking to
|
|
23
|
+
* answer. A request is registered before its `*.requested` is written, so
|
|
24
|
+
* even a sink that answers from inside `emit` finds it. The harness gets the
|
|
25
|
+
* answer once `*.resolved` is written, so a durable sink records it before
|
|
26
|
+
* the agent acts on it, and a failed write refuses it. Its turn's end drains
|
|
27
|
+
* it: every request still open is answered as a cancel, and every
|
|
28
|
+
* `*.resolved`, whoever answered it, is written before `turn.ended`.
|
|
29
|
+
*/
|
|
30
|
+
export class RequestBroker {
|
|
31
|
+
turn;
|
|
32
|
+
pending = {
|
|
33
|
+
permission: new Map(),
|
|
34
|
+
elicitation: new Map(),
|
|
35
|
+
};
|
|
36
|
+
/** Every `*.resolved` write, whoever settled it: the drain awaits them all. */
|
|
37
|
+
writes = [];
|
|
38
|
+
closed = false;
|
|
39
|
+
constructor(turn) {
|
|
40
|
+
this.turn = turn;
|
|
41
|
+
}
|
|
42
|
+
/** Whether it takes requests: until its turn ends, or its sink fails. */
|
|
43
|
+
get open() {
|
|
44
|
+
return !this.closed;
|
|
45
|
+
}
|
|
46
|
+
/** Ask whether a tool may run; resolves with the answer, or a cancel. */
|
|
47
|
+
askPermission(toolCall, options, signal) {
|
|
48
|
+
const { sessionId, turnId } = this.turn;
|
|
49
|
+
return this.park("permission", signal, (requestId) => ({
|
|
50
|
+
type: "permission.requested",
|
|
51
|
+
sessionId,
|
|
52
|
+
turnId,
|
|
53
|
+
requestId,
|
|
54
|
+
title: toolCall.title ?? `Allow tool: ${toolCall.toolName}`,
|
|
55
|
+
toolCall,
|
|
56
|
+
options,
|
|
57
|
+
timestamp: Date.now(),
|
|
58
|
+
}), (requestId, outcome) => ({
|
|
59
|
+
type: "permission.resolved",
|
|
60
|
+
sessionId,
|
|
61
|
+
turnId,
|
|
62
|
+
requestId,
|
|
63
|
+
outcome,
|
|
64
|
+
timestamp: Date.now(),
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
/** Ask the user what the agent asks; resolves with the answer, or a cancel. */
|
|
68
|
+
askElicitation(request, signal) {
|
|
69
|
+
const { sessionId, turnId } = this.turn;
|
|
70
|
+
return this.park("elicitation", signal, (requestId) => ({
|
|
71
|
+
type: "elicitation.requested",
|
|
72
|
+
sessionId,
|
|
73
|
+
turnId,
|
|
74
|
+
requestId,
|
|
75
|
+
...request,
|
|
76
|
+
timestamp: Date.now(),
|
|
77
|
+
}), (requestId, outcome) => ({
|
|
78
|
+
type: "elicitation.resolved",
|
|
79
|
+
sessionId,
|
|
80
|
+
turnId,
|
|
81
|
+
requestId,
|
|
82
|
+
// The harness gets the answer; the stream (and so the journal, replay,
|
|
83
|
+
// history and checkpoints) never carries a secret one.
|
|
84
|
+
outcome: redactSecrets(outcome, request.questions),
|
|
85
|
+
timestamp: Date.now(),
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
/** Answer an open request of this kind; false when it is not open here. */
|
|
89
|
+
respond(kind, requestId, answer) {
|
|
90
|
+
const pending = this.pending[kind].get(requestId);
|
|
91
|
+
if (!pending)
|
|
92
|
+
return false;
|
|
93
|
+
void pending.settle(answer);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
/** Answer every open request as a cancel does; resolves once their `*.resolved` are written. */
|
|
97
|
+
async cancelAll() {
|
|
98
|
+
const open = [...this.pending.permission.values(), ...this.pending.elicitation.values()];
|
|
99
|
+
await Promise.all(open.map((pending) => pending.cancel()));
|
|
100
|
+
}
|
|
101
|
+
/** Take no more requests: a later one is answered as a cancel, with no event. */
|
|
102
|
+
close() {
|
|
103
|
+
this.closed = true;
|
|
104
|
+
}
|
|
105
|
+
/** Its turn is ending: close, cancel what is open, and wait for every `*.resolved`. */
|
|
106
|
+
async drain() {
|
|
107
|
+
this.close();
|
|
108
|
+
await this.cancelAll();
|
|
109
|
+
await Promise.all(this.writes);
|
|
110
|
+
}
|
|
111
|
+
async park(kind, signal, requested, resolved) {
|
|
112
|
+
if (this.closed || signal?.aborted)
|
|
113
|
+
return CANCELLED[kind];
|
|
114
|
+
const requestId = generateUUIDv7();
|
|
115
|
+
const requests = this.pending[kind];
|
|
116
|
+
const answer = new Promise((resolve) => {
|
|
117
|
+
let expiry;
|
|
118
|
+
let detach = () => { };
|
|
119
|
+
const settle = (value) => {
|
|
120
|
+
if (!requests.delete(requestId))
|
|
121
|
+
return undefined;
|
|
122
|
+
clearTimeout(expiry);
|
|
123
|
+
detach();
|
|
124
|
+
const write = this.turn.emit(resolved(requestId, value)).then(() => resolve(value), () => resolve(CANCELLED[kind]));
|
|
125
|
+
this.writes.push(write);
|
|
126
|
+
return write;
|
|
127
|
+
};
|
|
128
|
+
requests.set(requestId, { settle, cancel: () => settle(CANCELLED[kind]) });
|
|
129
|
+
detach = onAbort(signal, () => void settle(CANCELLED[kind]));
|
|
130
|
+
// Unanswered in time, it goes as a cancel would.
|
|
131
|
+
if (this.turn.timeoutMs !== undefined) {
|
|
132
|
+
expiry = setTimeout(() => void settle(CANCELLED[kind]), this.turn.timeoutMs);
|
|
133
|
+
expiry.unref?.();
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
await this.turn.emit(requested(requestId));
|
|
137
|
+
return await answer;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — the runtime half
|
|
2
|
+
/**
|
|
3
|
+
* One turn's steers, one entry each, from `turn/steer` to where the agent
|
|
4
|
+
* read it. The turn takes steers from admission until its harness stops
|
|
5
|
+
* executing (`close`). Once `turn.ended` is going out (`end`), a steer it
|
|
6
|
+
* lists undelivered is answered `steered` whatever the harness says after,
|
|
7
|
+
* so a client never sees both signals to send it again.
|
|
8
|
+
*/
|
|
9
|
+
export class TurnSteers {
|
|
10
|
+
steers = new Map();
|
|
11
|
+
taking = true;
|
|
12
|
+
ended = false;
|
|
13
|
+
/** Whether it takes new steers. */
|
|
14
|
+
get open() {
|
|
15
|
+
return this.taking;
|
|
16
|
+
}
|
|
17
|
+
/** What it answered this steer id, if it took it. */
|
|
18
|
+
find(steerId) {
|
|
19
|
+
return this.steers.get(steerId);
|
|
20
|
+
}
|
|
21
|
+
/** Take a steer, and hand it to the harness with `deliver`. */
|
|
22
|
+
accept(steerId, inputKey, input, deliver) {
|
|
23
|
+
let answered;
|
|
24
|
+
const steer = {
|
|
25
|
+
inputKey,
|
|
26
|
+
input,
|
|
27
|
+
state: "held",
|
|
28
|
+
result: new Promise((resolve) => {
|
|
29
|
+
answered = resolve;
|
|
30
|
+
}),
|
|
31
|
+
};
|
|
32
|
+
// Held before the harness hears of it: the agent may read it at once.
|
|
33
|
+
this.steers.set(steerId, steer);
|
|
34
|
+
answered(this.answer(steerId, steer, deliver));
|
|
35
|
+
return steer.result;
|
|
36
|
+
}
|
|
37
|
+
async answer(steerId, steer, deliver) {
|
|
38
|
+
const steered = { outcome: "steered", steerId };
|
|
39
|
+
try {
|
|
40
|
+
if ((await deliver()) === "steered")
|
|
41
|
+
return steered;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
// Too late to take back: `turn.ended` listed it undelivered.
|
|
45
|
+
if (this.ended)
|
|
46
|
+
return steered;
|
|
47
|
+
this.steers.delete(steerId);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (this.ended)
|
|
51
|
+
return steered;
|
|
52
|
+
steer.state = "refused";
|
|
53
|
+
return { outcome: "no_active_turn" };
|
|
54
|
+
}
|
|
55
|
+
/** The agent read a steer: its input, once, for its echo. */
|
|
56
|
+
read(steerId) {
|
|
57
|
+
const steer = this.steers.get(steerId);
|
|
58
|
+
if (steer?.state !== "held")
|
|
59
|
+
return undefined;
|
|
60
|
+
steer.state = "read";
|
|
61
|
+
return steer.input;
|
|
62
|
+
}
|
|
63
|
+
/** The steers it took that the agent has not read (all of them, once the turn is over). */
|
|
64
|
+
undelivered() {
|
|
65
|
+
return [...this.steers].flatMap(([steerId, steer]) => steer.state === "held" ? [steerId] : []);
|
|
66
|
+
}
|
|
67
|
+
/** Its harness stopped executing: it takes no more steers. */
|
|
68
|
+
close() {
|
|
69
|
+
this.taking = false;
|
|
70
|
+
}
|
|
71
|
+
/** `turn.ended` is going out, listing the steers still held. */
|
|
72
|
+
end() {
|
|
73
|
+
this.ended = true;
|
|
74
|
+
}
|
|
75
|
+
/** What it answered each steer, without their input, which can carry images. */
|
|
76
|
+
answers() {
|
|
77
|
+
return new Map([...this.steers].map(([steerId, { inputKey, result }]) => [steerId, { inputKey, result }]));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { errorInfo } from "../../protocol/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* How a turn ended. What its execution threw decides first. Otherwise its
|
|
4
|
+
* harness says: a turn it stopped is cancelled, unless it failed first; one
|
|
5
|
+
* it failed is an error, categorized by its typed code before its text; any
|
|
6
|
+
* other ended as the harness reported, `end_turn` when it did not say.
|
|
7
|
+
*/
|
|
8
|
+
export function turnOutcome(result, threw) {
|
|
9
|
+
if (threw === "cancelled" || (threw === undefined && result.cancelled))
|
|
10
|
+
return { stopReason: "cancelled" };
|
|
11
|
+
if (threw)
|
|
12
|
+
return { stopReason: "error", error: threw };
|
|
13
|
+
if (result.error)
|
|
14
|
+
return { stopReason: "error", error: errorInfo(result.error, result.errorCategory) };
|
|
15
|
+
return { stopReason: result.stopReason ?? "end_turn" };
|
|
16
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { DEFAULT_TOKEN_USAGE, errorInfo } from "../../protocol/index.js";
|
|
2
|
+
import { emitDiagnostic } from "../diagnostics.js";
|
|
3
|
+
import { EventProcessor } from "./event-processor.js";
|
|
4
|
+
import { EventSinkError } from "./event-sink.js";
|
|
5
|
+
import { decisionFor, optionsFor, permissionAsk } from "./permission-policy.js";
|
|
6
|
+
import { RequestBroker } from "./request-broker.js";
|
|
7
|
+
import { TurnSteers } from "./steering.js";
|
|
8
|
+
import { turnOutcome } from "./turn-outcome.js";
|
|
9
|
+
const CANCEL = { decision: "cancel" };
|
|
10
|
+
/**
|
|
11
|
+
* Whether a turn sets a field: a value, but a boolean only when `true`, a
|
|
12
|
+
* string only when it is not empty, and an array or a record only when it
|
|
13
|
+
* holds something; the others mean the same as unset.
|
|
14
|
+
*/
|
|
15
|
+
function setsField(config, field) {
|
|
16
|
+
const value = config[field];
|
|
17
|
+
if (value === undefined || value === false || value === "")
|
|
18
|
+
return false;
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return value.length > 0;
|
|
21
|
+
if (typeof value === "object" && value !== null)
|
|
22
|
+
return Object.keys(value).length > 0;
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
/** The settings a turn set that its harness never applies. */
|
|
26
|
+
export function ignoredSettingsOf(config, ignored = []) {
|
|
27
|
+
return ignored.filter((field) => setsField(config, field));
|
|
28
|
+
}
|
|
29
|
+
// @ref LLP 0013#f12-a-lone-surrogate-hung-codex — no agent is given text it cannot read
|
|
30
|
+
/**
|
|
31
|
+
* Input as an agent is given it: every string of it well-formed, a lone
|
|
32
|
+
* UTF-16 surrogate (a string cut in the middle of an emoji) made U+FFFD.
|
|
33
|
+
* Codex cannot read a line that carries one and never answers it. The user
|
|
34
|
+
* echo is made of the caller's own input, not this (LLP 0002, The user echo
|
|
35
|
+
* comes first). A text element's byte range still holds: UTF-8 writes a lone
|
|
36
|
+
* surrogate as U+FFFD, three bytes.
|
|
37
|
+
*/
|
|
38
|
+
export function wellFormedInput(input) {
|
|
39
|
+
if (typeof input === "string")
|
|
40
|
+
return input.toWellFormed();
|
|
41
|
+
return input.map((part) => Object.fromEntries(Object.entries(part).map(([key, value]) => [
|
|
42
|
+
key,
|
|
43
|
+
typeof value === "string" ? value.toWellFormed() : value,
|
|
44
|
+
])));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* One admitted turn, from admission until it settles. It executes the request
|
|
48
|
+
* on its harness, streams what the harness does through the processor to its
|
|
49
|
+
* sink, brokers the harness's requests and the client's steers, and reports
|
|
50
|
+
* a `RunSummary`.
|
|
51
|
+
*/
|
|
52
|
+
export class Turn {
|
|
53
|
+
request;
|
|
54
|
+
inputKey;
|
|
55
|
+
sink;
|
|
56
|
+
host;
|
|
57
|
+
sessionId;
|
|
58
|
+
turnId;
|
|
59
|
+
harness;
|
|
60
|
+
steers = new TurnSteers();
|
|
61
|
+
requests;
|
|
62
|
+
/**
|
|
63
|
+
* The turn's run, deferred one microtask so the runtime registers the turn
|
|
64
|
+
* before it emits anything: a synchronous sink that reenters `run()` from
|
|
65
|
+
* `turn.started` must converge, not run it twice.
|
|
66
|
+
*/
|
|
67
|
+
running;
|
|
68
|
+
execution;
|
|
69
|
+
processor;
|
|
70
|
+
/** Its durable sink failed: the turn stops, and every later write fails with it. */
|
|
71
|
+
sinkFailure;
|
|
72
|
+
/**
|
|
73
|
+
* Aborted when `cancel` or `closeSession` asks the turn to stop: part of
|
|
74
|
+
* the signal its harness is given, so a cancel that comes before the
|
|
75
|
+
* harness has the turn is not lost.
|
|
76
|
+
*/
|
|
77
|
+
cancelled = new AbortController();
|
|
78
|
+
/** The caller's signal, the runtime's shutdown and the turn's own cancel, together. */
|
|
79
|
+
signal;
|
|
80
|
+
nativeSessionId;
|
|
81
|
+
/** When the turn requested a resume: whether the harness honored it. */
|
|
82
|
+
resumed;
|
|
83
|
+
/** `session.created` was decided on: a harness's later report is ignored. */
|
|
84
|
+
announced = false;
|
|
85
|
+
constructor(request,
|
|
86
|
+
/** The identity of its input: a retry with the same converges on it. */
|
|
87
|
+
inputKey, sink,
|
|
88
|
+
/** The caller's signal and the runtime's shutdown, together. */
|
|
89
|
+
signal, host) {
|
|
90
|
+
this.request = request;
|
|
91
|
+
this.inputKey = inputKey;
|
|
92
|
+
this.sink = sink;
|
|
93
|
+
this.host = host;
|
|
94
|
+
const { sessionId, turnId, config } = request;
|
|
95
|
+
this.signal = AbortSignal.any([signal, this.cancelled.signal]);
|
|
96
|
+
this.sessionId = sessionId;
|
|
97
|
+
this.turnId = turnId;
|
|
98
|
+
this.harness = config.harness;
|
|
99
|
+
this.execution = {
|
|
100
|
+
harness: config.harness,
|
|
101
|
+
...(config.model !== undefined && { model: config.model }),
|
|
102
|
+
...(config.thinkingLevel !== undefined && { thinkingLevel: config.thinkingLevel }),
|
|
103
|
+
...(config.permissionMode !== undefined && { permissionMode: config.permissionMode }),
|
|
104
|
+
};
|
|
105
|
+
this.processor = new EventProcessor(sessionId, turnId, this.execution, this.steers);
|
|
106
|
+
this.requests = new RequestBroker({
|
|
107
|
+
sessionId,
|
|
108
|
+
turnId,
|
|
109
|
+
emit: (event) => this.emit(event),
|
|
110
|
+
timeoutMs: config.requestTimeoutMs,
|
|
111
|
+
});
|
|
112
|
+
this.running = Promise.resolve().then(() => this.execute());
|
|
113
|
+
}
|
|
114
|
+
// @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel before the harness has the turn
|
|
115
|
+
/**
|
|
116
|
+
* A cancel was asked for: the turn's signal is aborted, so a harness that
|
|
117
|
+
* has not begun the turn yet begins it stopped; its open requests are
|
|
118
|
+
* answered as cancelled; and what the harness throws from now on is it
|
|
119
|
+
* stopping. Resolves once their `*.resolved` are written.
|
|
120
|
+
*/
|
|
121
|
+
requestCancel() {
|
|
122
|
+
// Taken before the abort, which settles each request bound to the turn's
|
|
123
|
+
// signal and takes it out of the broker: the cancel would not wait for it.
|
|
124
|
+
const answered = this.requests.cancelAll();
|
|
125
|
+
this.cancelled.abort();
|
|
126
|
+
return answered;
|
|
127
|
+
}
|
|
128
|
+
async execute() {
|
|
129
|
+
const { sessionId, turnId, input, config } = this.request;
|
|
130
|
+
// Looked up as the turn executes: a harness the registry lacks rejects
|
|
131
|
+
// the run, which is not remembered, so a retry may run.
|
|
132
|
+
const agent = this.host.registry.getAgent(config.harness);
|
|
133
|
+
const adapter = this.host.registry.getAdapter(config.harness)({ sessionId });
|
|
134
|
+
const modelThinking = config.model === undefined
|
|
135
|
+
? undefined
|
|
136
|
+
: this.host.modelLists.thinkingFor({
|
|
137
|
+
harness: config.harness,
|
|
138
|
+
cwd: config.cwd,
|
|
139
|
+
sessionId,
|
|
140
|
+
env: config.env,
|
|
141
|
+
apiKey: config.apiKey,
|
|
142
|
+
}, config.model);
|
|
143
|
+
// @ref LLP 0001#d22--a-turn-says-what-it-did-not-apply — up front, then as the harness finds out
|
|
144
|
+
const notApplied = ignoredSettingsOf(config, agent.capabilities.ignoredSettings);
|
|
145
|
+
this.processor.markNotApplied(notApplied);
|
|
146
|
+
await this.emit({
|
|
147
|
+
type: "turn.started",
|
|
148
|
+
turnId,
|
|
149
|
+
sessionId,
|
|
150
|
+
execution: { ...this.execution, ...(notApplied.length && { notApplied }) },
|
|
151
|
+
timestamp: Date.now(),
|
|
152
|
+
});
|
|
153
|
+
// @ref LLP 0002#the-user-echo-comes-first — before any harness output
|
|
154
|
+
// The user echo: the submitted input goes back onto the stream as a
|
|
155
|
+
// complete user message (outputIndex 0) before any harness output, so
|
|
156
|
+
// the stream is a complete transcript and multi-client attach works. It is
|
|
157
|
+
// the caller's input as sent, which the caller can predict; the agent is
|
|
158
|
+
// given it well-formed (`wellFormedInput`).
|
|
159
|
+
for (const event of this.processor.echoUserMessage(input))
|
|
160
|
+
await this.emit(event);
|
|
161
|
+
let threw;
|
|
162
|
+
try {
|
|
163
|
+
const given = wellFormedInput(input);
|
|
164
|
+
for await (const raw of agent.execute(given, this.agentOptions(modelThinking))) {
|
|
165
|
+
await this.announceNativeSession();
|
|
166
|
+
if (config.includeRaw) {
|
|
167
|
+
await this.emit({
|
|
168
|
+
type: "raw",
|
|
169
|
+
sessionId,
|
|
170
|
+
turnId,
|
|
171
|
+
harness: config.harness,
|
|
172
|
+
data: raw,
|
|
173
|
+
timestamp: Date.now(),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
for (const event of adapter.process(raw)) {
|
|
177
|
+
for (const lifecycle of this.processor.handle(event))
|
|
178
|
+
await this.emit(lifecycle);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
await this.announceNativeSession();
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
// Its sink stopped the turn: nothing more is written.
|
|
185
|
+
if (this.sinkFailure)
|
|
186
|
+
throw this.sinkFailure;
|
|
187
|
+
// A harness asked to stop throws as it stops, whatever its words say;
|
|
188
|
+
// one that was not is failing.
|
|
189
|
+
threw = this.signal.aborted ? "cancelled" : errorInfo(error);
|
|
190
|
+
if (threw !== "cancelled") {
|
|
191
|
+
await this.emit({
|
|
192
|
+
type: "error",
|
|
193
|
+
turnId,
|
|
194
|
+
sessionId,
|
|
195
|
+
...threw,
|
|
196
|
+
// This error ends the turn; `recoverable` promises the turn goes on.
|
|
197
|
+
recoverable: false,
|
|
198
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
199
|
+
timestamp: Date.now(),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
finally {
|
|
204
|
+
// Its harness stopped executing: it takes no more input.
|
|
205
|
+
this.steers.close();
|
|
206
|
+
await this.requests.drain();
|
|
207
|
+
}
|
|
208
|
+
const result = adapter.finish();
|
|
209
|
+
// From here a steer the harness refuses was listed undelivered: it stays `steered`.
|
|
210
|
+
this.steers.end();
|
|
211
|
+
const { events, ended } = this.processor.finish(result, turnOutcome(result, threw));
|
|
212
|
+
for (const event of events)
|
|
213
|
+
await this.emit(event);
|
|
214
|
+
return {
|
|
215
|
+
sessionId,
|
|
216
|
+
turnId,
|
|
217
|
+
harness: config.harness,
|
|
218
|
+
nativeSessionId: this.nativeSessionId,
|
|
219
|
+
...(this.resumed !== undefined && { resumed: this.resumed }),
|
|
220
|
+
usage: result.usage ?? DEFAULT_TOKEN_USAGE,
|
|
221
|
+
execution: ended.execution,
|
|
222
|
+
stopReason: ended.stopReason,
|
|
223
|
+
finishReason: ended.finishReason,
|
|
224
|
+
cost: ended.cost,
|
|
225
|
+
error: ended.error,
|
|
226
|
+
cancelled: ended.stopReason === "cancelled",
|
|
227
|
+
...(ended.undeliveredSteers && { undeliveredSteers: ended.undeliveredSteers }),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Everything the harness gets: the config the engine does not handle itself, and the engine's callbacks. */
|
|
231
|
+
agentOptions(modelThinking) {
|
|
232
|
+
const { harness: _harness, elicitation, requestTimeoutMs: _requestTimeoutMs, includeRaw: _includeRaw, ...config } = this.request.config;
|
|
233
|
+
return {
|
|
234
|
+
...config,
|
|
235
|
+
sessionId: this.sessionId,
|
|
236
|
+
turnId: this.turnId,
|
|
237
|
+
...(modelThinking && { modelThinking }),
|
|
238
|
+
signal: this.signal,
|
|
239
|
+
onNativeSession: (id, info) => {
|
|
240
|
+
// Agents report once the native conversation is confirmed; guard against a
|
|
241
|
+
// misbehaving harness re-reporting after emission. Agents always pass
|
|
242
|
+
// their honest `resumed` judgment — the runtime surfaces it only when
|
|
243
|
+
// this turn actually REQUESTED a resume.
|
|
244
|
+
if (this.announced)
|
|
245
|
+
return;
|
|
246
|
+
this.nativeSessionId = id;
|
|
247
|
+
if (config.resumeSessionId && info?.resumed !== undefined)
|
|
248
|
+
this.resumed = info.resumed;
|
|
249
|
+
},
|
|
250
|
+
onPermissionRequest: this.requestPermission,
|
|
251
|
+
// @ref LLP 0001#d12--what-the-agent-asks-the-user-is-first-class-protocol-opted-into-per-turn — opted into per turn
|
|
252
|
+
// Only a client that answers them gets asked; otherwise the harness
|
|
253
|
+
// declines on the user's behalf.
|
|
254
|
+
...(elicitation && { onElicitationRequest: this.requestElicitation }),
|
|
255
|
+
onExecution: (update) => this.processor.applyExecution(update),
|
|
256
|
+
onWarning: (warning) => this.emit({
|
|
257
|
+
type: "error",
|
|
258
|
+
sessionId: this.sessionId,
|
|
259
|
+
turnId: this.turnId,
|
|
260
|
+
...warning,
|
|
261
|
+
recoverable: true,
|
|
262
|
+
timestamp: Date.now(),
|
|
263
|
+
}),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
requestPermission = async (toolCall, opts) => {
|
|
267
|
+
// A turn that takes no more requests answers none, not even from a rule.
|
|
268
|
+
if (!this.requests.open || opts?.signal?.aborted)
|
|
269
|
+
return CANCEL;
|
|
270
|
+
const ask = permissionAsk(opts);
|
|
271
|
+
const standing = ask.kind === "engine_always"
|
|
272
|
+
? this.host.memory(this.sessionId).standingRules.answer(toolCall.toolName)
|
|
273
|
+
: undefined;
|
|
274
|
+
if (standing)
|
|
275
|
+
return standing;
|
|
276
|
+
const options = optionsFor(ask);
|
|
277
|
+
const outcome = await this.requests.askPermission(toolCall, options, opts?.signal);
|
|
278
|
+
if (outcome.outcome === "cancelled")
|
|
279
|
+
return CANCEL;
|
|
280
|
+
const { decision, selected } = decisionFor(outcome, options);
|
|
281
|
+
if (ask.kind === "engine_always")
|
|
282
|
+
this.host.memory(this.sessionId).standingRules.learn(toolCall.toolName, selected);
|
|
283
|
+
return decision;
|
|
284
|
+
};
|
|
285
|
+
requestElicitation = (request, opts) => this.requests.askElicitation(request, opts?.signal);
|
|
286
|
+
async announceNativeSession() {
|
|
287
|
+
if (!this.nativeSessionId || this.announced)
|
|
288
|
+
return;
|
|
289
|
+
this.announced = true;
|
|
290
|
+
// @ref LLP 0002#the-session-is-announced-when-it-changes — not on every warm turn
|
|
291
|
+
// Announced when it says something: the session's first native id, a
|
|
292
|
+
// new one (Claude can mint one on resume), or a resume that did not
|
|
293
|
+
// continue. A warm turn on the same native session says nothing new.
|
|
294
|
+
const memory = this.host.memory(this.sessionId);
|
|
295
|
+
if (memory.announcedNative === this.nativeSessionId && this.resumed !== false)
|
|
296
|
+
return;
|
|
297
|
+
memory.announcedNative = this.nativeSessionId;
|
|
298
|
+
await this.emit({
|
|
299
|
+
type: "session.created",
|
|
300
|
+
sessionId: this.sessionId,
|
|
301
|
+
nativeSessionId: this.nativeSessionId,
|
|
302
|
+
harness: this.harness,
|
|
303
|
+
model: this.request.config.model,
|
|
304
|
+
...(this.resumed !== undefined && { resumed: this.resumed }),
|
|
305
|
+
timestamp: Date.now(),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Write to the sink, isolating its failures: a misbehaving transport must
|
|
310
|
+
* never break the turn's bracketing (`turn.started` … `turn.ended`). Except
|
|
311
|
+
* an `EventSinkError`: its writes are a durability boundary, so the turn
|
|
312
|
+
* stops rather than run on unrecorded, and every later write fails with it.
|
|
313
|
+
*/
|
|
314
|
+
async emit(event) {
|
|
315
|
+
if (this.sinkFailure)
|
|
316
|
+
throw this.sinkFailure;
|
|
317
|
+
try {
|
|
318
|
+
await this.sink.emit(event);
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
if (error instanceof EventSinkError) {
|
|
322
|
+
this.sinkFailure = error;
|
|
323
|
+
this.requests.close();
|
|
324
|
+
// Refuses pending permissions and interrupts the harness. Whether
|
|
325
|
+
// the native execution stopped stays unconfirmed.
|
|
326
|
+
void this.host.cancel(this.harness, this.sessionId).catch(() => { });
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
// The turn must not fail on a misbehaving sink — but the host gets
|
|
330
|
+
// to know its sink dropped an event.
|
|
331
|
+
emitDiagnostic(this.host.onDiagnostic, {
|
|
332
|
+
type: "sinkError",
|
|
333
|
+
sessionId: this.sessionId,
|
|
334
|
+
message: `sink emit failed for ${event.type}: ${error instanceof Error ? error.message : String(error)}`,
|
|
335
|
+
detail: error,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Set `key` as `map`'s newest entry, dropping the oldest while it holds more
|
|
3
|
+
* than `max`: a bounded cache whose insertion order is its age.
|
|
4
|
+
*/
|
|
5
|
+
export function setBounded(map, key, value, max) {
|
|
6
|
+
map.delete(key);
|
|
7
|
+
map.set(key, value);
|
|
8
|
+
for (const oldest of map.keys()) {
|
|
9
|
+
if (map.size <= max)
|
|
10
|
+
return;
|
|
11
|
+
map.delete(oldest);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wait for `promise` at most `ms`: `{ value }` once it resolves in time,
|
|
3
|
+
* `undefined` once the time is up. A rejection in time rejects. The timer
|
|
4
|
+
* never holds the process open, and is cleared either way.
|
|
5
|
+
*/
|
|
6
|
+
export async function withTimeout(promise, ms) {
|
|
7
|
+
let timer;
|
|
8
|
+
try {
|
|
9
|
+
return await Promise.race([
|
|
10
|
+
promise.then((value) => ({ value })),
|
|
11
|
+
new Promise((resolve) => {
|
|
12
|
+
timer = setTimeout(() => resolve(undefined), ms);
|
|
13
|
+
timer.unref?.();
|
|
14
|
+
}),
|
|
15
|
+
]);
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
clearTimeout(timer);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Wait for `promise` until `signal` aborts: its value, or the signal's reason
|
|
23
|
+
* thrown once the signal aborts first. Only the wait ends: the work goes on
|
|
24
|
+
* for whoever else waits for it. Without a signal it waits for the work.
|
|
25
|
+
*/
|
|
26
|
+
export async function untilAborted(promise, signal) {
|
|
27
|
+
if (!signal)
|
|
28
|
+
return await promise;
|
|
29
|
+
let off = () => { };
|
|
30
|
+
try {
|
|
31
|
+
return await Promise.race([
|
|
32
|
+
promise,
|
|
33
|
+
new Promise((_, reject) => {
|
|
34
|
+
off = onAbort(signal, () => reject(signal.reason));
|
|
35
|
+
}),
|
|
36
|
+
]);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
off();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Run `fn` once `signal` aborts, or at once if it already has. Returns what
|
|
44
|
+
* removes it again. Without a signal it never runs.
|
|
45
|
+
*/
|
|
46
|
+
export function onAbort(signal, fn) {
|
|
47
|
+
if (!signal)
|
|
48
|
+
return () => { };
|
|
49
|
+
if (signal.aborted) {
|
|
50
|
+
fn();
|
|
51
|
+
return () => { };
|
|
52
|
+
}
|
|
53
|
+
// Its own listener: the same `fn` added twice is removed once each.
|
|
54
|
+
const listener = () => fn();
|
|
55
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
56
|
+
return () => signal.removeEventListener("abort", listener);
|
|
57
|
+
}
|