subharness 0.0.7 → 0.0.10
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/README.md +40 -9
- package/dist/adapters/claude-events.d.ts +71 -0
- package/dist/adapters/claude-events.js +860 -0
- package/dist/adapters/claude-events.js.map +1 -0
- package/dist/adapters/claude-worker-client.d.ts +11 -0
- package/dist/adapters/claude-worker-client.js +219 -5
- package/dist/adapters/claude-worker-client.js.map +1 -1
- package/dist/adapters/claude-worker-protocol.d.ts +58 -0
- package/dist/adapters/claude-worker-protocol.js.map +1 -1
- package/dist/adapters/claude-worker.js +48 -3
- package/dist/adapters/claude-worker.js.map +1 -1
- package/dist/adapters/claude.d.ts +5 -1
- package/dist/adapters/claude.js +14 -2
- package/dist/adapters/claude.js.map +1 -1
- package/dist/adapters/codex-events.d.ts +52 -0
- package/dist/adapters/codex-events.js +672 -0
- package/dist/adapters/codex-events.js.map +1 -0
- package/dist/adapters/codex-turn-failure.d.ts +2 -0
- package/dist/adapters/codex-turn-failure.js +116 -0
- package/dist/adapters/codex-turn-failure.js.map +1 -0
- package/dist/adapters/codex.js +44 -7
- package/dist/adapters/codex.js.map +1 -1
- package/dist/adapters/copilot-events.d.ts +68 -0
- package/dist/adapters/copilot-events.js +650 -0
- package/dist/adapters/copilot-events.js.map +1 -0
- package/dist/adapters/copilot.js +24 -4
- package/dist/adapters/copilot.js.map +1 -1
- package/dist/adapters/cursor-acp-events.d.ts +36 -0
- package/dist/adapters/cursor-acp-events.js +251 -0
- package/dist/adapters/cursor-acp-events.js.map +1 -0
- package/dist/adapters/cursor-cli-session.d.ts +1 -0
- package/dist/adapters/cursor-cli-session.js +26 -5
- package/dist/adapters/cursor-cli-session.js.map +1 -1
- package/dist/adapters/cursor-cli.js +5 -0
- package/dist/adapters/cursor-cli.js.map +1 -1
- package/dist/adapters/cursor-sdk-events.d.ts +30 -0
- package/dist/adapters/cursor-sdk-events.js +233 -0
- package/dist/adapters/cursor-sdk-events.js.map +1 -0
- package/dist/adapters/cursor-session.js +56 -7
- package/dist/adapters/cursor-session.js.map +1 -1
- package/dist/adapters/cursor-startup.js +8 -2
- package/dist/adapters/cursor-startup.js.map +1 -1
- package/dist/adapters/event-normalizer.d.ts +57 -0
- package/dist/adapters/event-normalizer.js +143 -0
- package/dist/adapters/event-normalizer.js.map +1 -0
- package/dist/adapters/event-secrets.d.ts +17 -0
- package/dist/adapters/event-secrets.js +28 -0
- package/dist/adapters/event-secrets.js.map +1 -0
- package/dist/adapters/event-types.d.ts +58 -0
- package/dist/adapters/event-types.js +2 -0
- package/dist/adapters/event-types.js.map +1 -0
- package/dist/adapters/fx-events.d.ts +37 -0
- package/dist/adapters/fx-events.js +393 -0
- package/dist/adapters/fx-events.js.map +1 -0
- package/dist/adapters/fx-rpc.d.ts +2 -0
- package/dist/adapters/fx-rpc.js +11 -5
- package/dist/adapters/fx-rpc.js.map +1 -1
- package/dist/adapters/fx.js +73 -8
- package/dist/adapters/fx.js.map +1 -1
- package/dist/adapters/opencode-events.d.ts +58 -0
- package/dist/adapters/opencode-events.js +653 -0
- package/dist/adapters/opencode-events.js.map +1 -0
- package/dist/adapters/opencode-http.d.ts +1 -0
- package/dist/adapters/opencode-http.js +8 -7
- package/dist/adapters/opencode-http.js.map +1 -1
- package/dist/adapters/opencode.js +50 -9
- package/dist/adapters/opencode.js.map +1 -1
- package/dist/adapters/rpc.d.ts +2 -0
- package/dist/adapters/rpc.js +11 -5
- package/dist/adapters/rpc.js.map +1 -1
- package/dist/adapters/types.d.ts +2 -0
- package/dist/adapters/types.js.map +1 -1
- package/dist/cli/args.d.ts +6 -1
- package/dist/cli/args.js +63 -5
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/catalog-worker.js +3 -2
- package/dist/cli/catalog-worker.js.map +1 -1
- package/dist/cli/dashboard-client.d.ts +1 -0
- package/dist/cli/dashboard-client.js +13 -1
- package/dist/cli/dashboard-client.js.map +1 -1
- package/dist/cli/dashboard-controller.js +6 -7
- package/dist/cli/dashboard-controller.js.map +1 -1
- package/dist/cli/dashboard-detail-view.d.ts +14 -8
- package/dist/cli/dashboard-detail-view.js +15 -44
- package/dist/cli/dashboard-detail-view.js.map +1 -1
- package/dist/cli/dashboard-history-view.d.ts +3 -12
- package/dist/cli/dashboard-history-view.js +18 -82
- package/dist/cli/dashboard-history-view.js.map +1 -1
- package/dist/cli/dashboard-live.d.ts +32 -0
- package/dist/cli/dashboard-live.js +177 -0
- package/dist/cli/dashboard-live.js.map +1 -0
- package/dist/cli/dashboard-renderer.d.ts +21 -1
- package/dist/cli/dashboard-renderer.js +85 -21
- package/dist/cli/dashboard-renderer.js.map +1 -1
- package/dist/cli/dashboard-steps.d.ts +53 -0
- package/dist/cli/dashboard-steps.js +157 -0
- package/dist/cli/dashboard-steps.js.map +1 -0
- package/dist/cli/dashboard-task-format.d.ts +15 -0
- package/dist/cli/dashboard-task-format.js +119 -0
- package/dist/cli/dashboard-task-format.js.map +1 -0
- package/dist/cli/dashboard-task-view.d.ts +66 -0
- package/dist/cli/dashboard-task-view.js +325 -0
- package/dist/cli/dashboard-task-view.js.map +1 -0
- package/dist/cli/dashboard.d.ts +2 -0
- package/dist/cli/dashboard.js +71 -6
- package/dist/cli/dashboard.js.map +1 -1
- package/dist/cli/extensions-client.d.ts +23 -0
- package/dist/cli/extensions-client.js +147 -0
- package/dist/cli/extensions-client.js.map +1 -0
- package/dist/cli/extensions.d.ts +15 -0
- package/dist/cli/extensions.js +187 -0
- package/dist/cli/extensions.js.map +1 -0
- package/dist/cli/help.d.ts +1 -0
- package/dist/cli/help.js +34 -6
- package/dist/cli/help.js.map +1 -1
- package/dist/cli/main.js +100 -10
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/output.js +5 -1
- package/dist/cli/output.js.map +1 -1
- package/dist/config/access.d.ts +2 -1
- package/dist/config/access.js +18 -7
- package/dist/config/access.js.map +1 -1
- package/dist/config/loader.d.ts +2 -0
- package/dist/config/loader.js +20 -6
- package/dist/config/loader.js.map +1 -1
- package/dist/config/project-context.d.ts +9 -0
- package/dist/config/project-context.js +41 -0
- package/dist/config/project-context.js.map +1 -0
- package/dist/config/resolve-access.d.ts +2 -1
- package/dist/config/resolve-access.js +5 -2
- package/dist/config/resolve-access.js.map +1 -1
- package/dist/events/content.d.ts +43 -0
- package/dist/events/content.js +249 -0
- package/dist/events/content.js.map +1 -0
- package/dist/events/queue.d.ts +59 -0
- package/dist/events/queue.js +144 -0
- package/dist/events/queue.js.map +1 -0
- package/dist/events/validate.d.ts +22 -0
- package/dist/events/validate.js +542 -0
- package/dist/events/validate.js.map +1 -0
- package/dist/extensions/catalog.d.ts +34 -0
- package/dist/extensions/catalog.js +103 -0
- package/dist/extensions/catalog.js.map +1 -0
- package/dist/extensions/child-protocol.d.ts +38 -0
- package/dist/extensions/child-protocol.js +2 -0
- package/dist/extensions/child-protocol.js.map +1 -0
- package/dist/extensions/child.d.ts +1 -0
- package/dist/extensions/child.js +125 -0
- package/dist/extensions/child.js.map +1 -0
- package/dist/extensions/consent.d.ts +13 -0
- package/dist/extensions/consent.js +204 -0
- package/dist/extensions/consent.js.map +1 -0
- package/dist/extensions/environment.d.ts +1 -0
- package/dist/extensions/environment.js +12 -0
- package/dist/extensions/environment.js.map +1 -0
- package/dist/extensions/identity.d.ts +9 -0
- package/dist/extensions/identity.js +28 -0
- package/dist/extensions/identity.js.map +1 -0
- package/dist/extensions/log.d.ts +5 -0
- package/dist/extensions/log.js +80 -0
- package/dist/extensions/log.js.map +1 -0
- package/dist/extensions/manifest.d.ts +7 -0
- package/dist/extensions/manifest.js +213 -0
- package/dist/extensions/manifest.js.map +1 -0
- package/dist/extensions/types.d.ts +24 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/extensions.d.ts +5 -0
- package/dist/extensions.js +2 -0
- package/dist/extensions.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js.map +1 -1
- package/dist/runtime/approval-registry.d.ts +6 -2
- package/dist/runtime/approval-registry.js +31 -3
- package/dist/runtime/approval-registry.js.map +1 -1
- package/dist/runtime/capture.d.ts +4 -4
- package/dist/runtime/capture.js +59 -15
- package/dist/runtime/capture.js.map +1 -1
- package/dist/runtime/catalog.d.ts +6 -1
- package/dist/runtime/catalog.js +1 -1
- package/dist/runtime/catalog.js.map +1 -1
- package/dist/runtime/coordinator.d.ts +9 -4
- package/dist/runtime/coordinator.js +130 -27
- package/dist/runtime/coordinator.js.map +1 -1
- package/dist/runtime/daemon.js +9 -1
- package/dist/runtime/daemon.js.map +1 -1
- package/dist/runtime/dashboard.d.ts +4 -0
- package/dist/runtime/dashboard.js +8 -0
- package/dist/runtime/dashboard.js.map +1 -1
- package/dist/runtime/definition.d.ts +1 -1
- package/dist/runtime/definition.js +2 -2
- package/dist/runtime/definition.js.map +1 -1
- package/dist/runtime/event-operation.d.ts +41 -0
- package/dist/runtime/event-operation.js +290 -0
- package/dist/runtime/event-operation.js.map +1 -0
- package/dist/runtime/event-owner.d.ts +94 -0
- package/dist/runtime/event-owner.js +429 -0
- package/dist/runtime/event-owner.js.map +1 -0
- package/dist/runtime/event-source.d.ts +39 -0
- package/dist/runtime/event-source.js +344 -0
- package/dist/runtime/event-source.js.map +1 -0
- package/dist/runtime/extension-instance.d.ts +61 -0
- package/dist/runtime/extension-instance.js +356 -0
- package/dist/runtime/extension-instance.js.map +1 -0
- package/dist/runtime/extension-protocol.d.ts +47 -0
- package/dist/runtime/extension-protocol.js +33 -0
- package/dist/runtime/extension-protocol.js.map +1 -0
- package/dist/runtime/extension-service.d.ts +10 -0
- package/dist/runtime/extension-service.js +35 -0
- package/dist/runtime/extension-service.js.map +1 -0
- package/dist/runtime/extension-supervisor.d.ts +33 -0
- package/dist/runtime/extension-supervisor.js +254 -0
- package/dist/runtime/extension-supervisor.js.map +1 -0
- package/dist/runtime/select-native.d.ts +3 -1
- package/dist/runtime/select-native.js +32 -5
- package/dist/runtime/select-native.js.map +1 -1
- package/dist/runtime/service.d.ts +5 -0
- package/dist/runtime/service.js +113 -15
- package/dist/runtime/service.js.map +1 -1
- package/dist/runtime/session-event-wire.d.ts +29 -0
- package/dist/runtime/session-event-wire.js +2 -0
- package/dist/runtime/session-event-wire.js.map +1 -0
- package/dist/runtime/session-events-service.d.ts +8 -0
- package/dist/runtime/session-events-service.js +124 -0
- package/dist/runtime/session-events-service.js.map +1 -0
- package/dist/runtime/session-events-transport.d.ts +8 -0
- package/dist/runtime/session-events-transport.js +142 -0
- package/dist/runtime/session-events-transport.js.map +1 -0
- package/dist/runtime/startup-lock.d.ts +2 -0
- package/dist/runtime/startup-lock.js +49 -5
- package/dist/runtime/startup-lock.js.map +1 -1
- package/dist/runtime/state.d.ts +2 -1
- package/dist/runtime/state.js +4 -0
- package/dist/runtime/state.js.map +1 -1
- package/dist/runtime/transport.d.ts +1 -0
- package/dist/runtime/transport.js +2 -0
- package/dist/runtime/transport.js.map +1 -1
- package/dist/runtime/types.d.ts +24 -0
- package/dist/runtime/types.js.map +1 -1
- package/dist/runtime/worker-client.js +42 -13
- package/dist/runtime/worker-client.js.map +1 -1
- package/dist/runtime/worker-event-channel.d.ts +30 -0
- package/dist/runtime/worker-event-channel.js +141 -0
- package/dist/runtime/worker-event-channel.js.map +1 -0
- package/dist/runtime/worker-event-protocol.d.ts +88 -0
- package/dist/runtime/worker-event-protocol.js +114 -0
- package/dist/runtime/worker-event-protocol.js.map +1 -0
- package/dist/runtime/worker-events.d.ts +73 -0
- package/dist/runtime/worker-events.js +704 -0
- package/dist/runtime/worker-events.js.map +1 -0
- package/dist/runtime/worker-server.d.ts +3 -1
- package/dist/runtime/worker-server.js +64 -9
- package/dist/runtime/worker-server.js.map +1 -1
- package/dist/sdk/connected-events.d.ts +3 -0
- package/dist/sdk/connected-events.js +259 -0
- package/dist/sdk/connected-events.js.map +1 -0
- package/dist/sdk/connected-types.d.ts +2 -0
- package/dist/sdk/connected-types.js.map +1 -1
- package/dist/sdk/connected.js +3 -0
- package/dist/sdk/connected.js.map +1 -1
- package/dist/sdk/event-types.d.ts +182 -0
- package/dist/sdk/event-types.js +2 -0
- package/dist/sdk/event-types.js.map +1 -0
- package/dist/sdk/execution-driver.js +1 -1
- package/dist/sdk/execution-driver.js.map +1 -1
- package/dist/sdk/execution-types.d.ts +2 -0
- package/dist/sdk/execution-types.js.map +1 -1
- package/dist/sdk/runner.js +2 -0
- package/dist/sdk/runner.js.map +1 -1
- package/package.json +5 -1
- package/sdk/access-config.md +9 -7
- package/sdk/adapter-contract.md +25 -3
- package/sdk/agent-skill.md +8 -5
- package/sdk/cli/dashboard-design.md +37 -9
- package/sdk/cli/dashboard-inspection.md +14 -6
- package/sdk/cli/extensions.md +44 -0
- package/sdk/cli/index.md +53 -14
- package/sdk/cli/output.md +14 -2
- package/sdk/completion-notifications.md +2 -2
- package/sdk/config.md +65 -11
- package/sdk/copilot.md +1 -1
- package/sdk/cursor.md +2 -2
- package/sdk/diagnostics.md +68 -0
- package/sdk/distribution.md +13 -3
- package/sdk/events.md +339 -0
- package/sdk/execution.md +32 -10
- package/sdk/extensions.md +189 -0
- package/sdk/fx.md +4 -2
- package/sdk/harnesses.md +1 -1
- package/sdk/index.md +4 -0
- package/sdk/message-delivery.md +2 -0
- package/sdk/opencode.md +1 -1
- package/sdk/plugins/sub-agents.md +3 -1
- package/sdk/project-root.md +97 -0
- package/sdk/project-team.md +10 -4
- package/sdk/sessions.md +4 -0
- package/sdk/v1-runtime.md +22 -8
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { AgentError } from "../errors.js";
|
|
2
|
+
// The private line allows one bounded 128 KiB event plus its fixed wire envelope.
|
|
3
|
+
export const SESSION_EVENT_WIRE_MAX_BYTES = 132 * 1024;
|
|
4
|
+
export class SessionEventsTransport {
|
|
5
|
+
transport;
|
|
6
|
+
constructor(transport) {
|
|
7
|
+
this.transport = transport;
|
|
8
|
+
}
|
|
9
|
+
records(scope, signal) {
|
|
10
|
+
return readEventRecords(this.transport, scope, signal);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function* readEventRecords(transport, scope, signal) {
|
|
14
|
+
if (transport.disconnected.aborted)
|
|
15
|
+
throw unavailable("The coordinator client is disconnected.");
|
|
16
|
+
const combined = AbortSignal.any([transport.disconnected, signal]);
|
|
17
|
+
let response;
|
|
18
|
+
try {
|
|
19
|
+
response = await fetch(transport.endpoint.url, {
|
|
20
|
+
method: "POST",
|
|
21
|
+
headers: {
|
|
22
|
+
authorization: `Bearer ${transport.endpoint.token}`,
|
|
23
|
+
"content-type": "application/json",
|
|
24
|
+
"x-subharness-instance": transport.endpoint.instanceId,
|
|
25
|
+
},
|
|
26
|
+
body: JSON.stringify({ command: "sdk.events.open", scope }),
|
|
27
|
+
signal: combined,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
if (signal.aborted)
|
|
32
|
+
throw observationClosed();
|
|
33
|
+
throw unavailable("Connection to the local coordinator failed. The task was not automatically retried.");
|
|
34
|
+
}
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
void response.body?.cancel().catch(() => { });
|
|
37
|
+
if (response.status === 401) {
|
|
38
|
+
throw new AgentError("COORDINATOR_AUTH_FAILED", "The local coordinator rejected its private authentication token.");
|
|
39
|
+
}
|
|
40
|
+
throw unavailable(`The coordinator rejected the sdk.events.open operation with HTTP status ${response.status}.`);
|
|
41
|
+
}
|
|
42
|
+
if (!response.body) {
|
|
43
|
+
throw unavailable("The coordinator returned a successful response with no body for the sdk.events.open operation.");
|
|
44
|
+
}
|
|
45
|
+
const reader = response.body.getReader();
|
|
46
|
+
const lines = new BoundedLineDecoder();
|
|
47
|
+
let complete = false;
|
|
48
|
+
try {
|
|
49
|
+
for (;;) {
|
|
50
|
+
const result = await reader.read();
|
|
51
|
+
if (result.done) {
|
|
52
|
+
complete = true;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
for (const line of lines.push(result.value))
|
|
56
|
+
yield parseLine(line);
|
|
57
|
+
}
|
|
58
|
+
lines.finish();
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error instanceof AgentError)
|
|
62
|
+
throw error;
|
|
63
|
+
if (signal.aborted)
|
|
64
|
+
throw observationClosed();
|
|
65
|
+
throw unavailable("The coordinator response stream was interrupted. The task was not automatically retried.");
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
if (!complete)
|
|
69
|
+
await reader.cancel().catch(() => { });
|
|
70
|
+
reader.releaseLock();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
class BoundedLineDecoder {
|
|
74
|
+
chunks = [];
|
|
75
|
+
bytes = 0;
|
|
76
|
+
push(chunk) {
|
|
77
|
+
const lines = [];
|
|
78
|
+
let start = 0;
|
|
79
|
+
for (;;) {
|
|
80
|
+
const newline = chunk.indexOf(10, start);
|
|
81
|
+
if (newline < 0) {
|
|
82
|
+
this.append(chunk.subarray(start));
|
|
83
|
+
return lines;
|
|
84
|
+
}
|
|
85
|
+
this.append(chunk.subarray(start, newline));
|
|
86
|
+
const line = this.decode();
|
|
87
|
+
this.chunks = [];
|
|
88
|
+
this.bytes = 0;
|
|
89
|
+
if (line.length > 0)
|
|
90
|
+
lines.push(line);
|
|
91
|
+
start = newline + 1;
|
|
92
|
+
if (start === chunk.length)
|
|
93
|
+
return lines;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
finish() {
|
|
97
|
+
if (this.bytes === 0)
|
|
98
|
+
return;
|
|
99
|
+
const remaining = this.decode();
|
|
100
|
+
if (remaining.trim()) {
|
|
101
|
+
throw unavailable("The coordinator response ended with an incomplete final record for the sdk.events.open operation. The task was not automatically retried.");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
append(chunk) {
|
|
105
|
+
if (chunk.length === 0)
|
|
106
|
+
return;
|
|
107
|
+
if (this.bytes + chunk.length > SESSION_EVENT_WIRE_MAX_BYTES) {
|
|
108
|
+
throw unavailable("The coordinator returned an oversized live event record.");
|
|
109
|
+
}
|
|
110
|
+
this.chunks.push(chunk.slice());
|
|
111
|
+
this.bytes += chunk.length;
|
|
112
|
+
}
|
|
113
|
+
decode() {
|
|
114
|
+
const value = new Uint8Array(this.bytes);
|
|
115
|
+
let offset = 0;
|
|
116
|
+
for (const chunk of this.chunks) {
|
|
117
|
+
value.set(chunk, offset);
|
|
118
|
+
offset += chunk.length;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(value);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw unavailable("The coordinator returned a malformed live event record.");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function parseLine(line) {
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(line);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
throw unavailable("The coordinator returned a malformed JSON record for the sdk.events.open operation. The task was not automatically retried.");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function observationClosed() {
|
|
137
|
+
return new AgentError("OBSERVATION_CLOSED", "The live event observation was closed.");
|
|
138
|
+
}
|
|
139
|
+
function unavailable(message) {
|
|
140
|
+
return new AgentError("COORDINATOR_UNAVAILABLE", message);
|
|
141
|
+
}
|
|
142
|
+
//# sourceMappingURL=session-events-transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-events-transport.js","sourceRoot":"","sources":["../../src/runtime/session-events-transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAI1C,kFAAkF;AAClF,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,GAAG,IAAI,CAAC;AAEvD,MAAM,OAAO,sBAAsB;IACJ,SAAS;IAAtC,YAA6B,SAA+B;yBAA/B,SAAS;IAAyB,CAAC;IAEhE,OAAO,CAAC,KAAiB,EAAE,MAAmB;QAC5C,OAAO,gBAAgB,CAAC,IAA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I,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;QAChC,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;IAC7B,CAAC;IAEO,MAAM;QACZ,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;QAAC,CAAC;QACtF,IAAI,CAAC;YAAC,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAAC,CAAC;QACvE,MAAM,CAAC;YAAC,MAAM,WAAW,CAAC,yDAAyD,CAAC,CAAC;QAAC,CAAC;IACzF,CAAC;CACF;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,IAAI,CAAC;QAAC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;IAAC,CAAC;IAC3C,MAAM,CAAC;QACL,MAAM,WAAW,CAAC,6HAA6H,CAAC,CAAC;IACnJ,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB;IACxB,OAAO,IAAI,UAAU,CAAC,oBAAoB,EAAE,wCAAwC,CAAC,CAAC;AACxF,CAAC;AAED,SAAS,WAAW,CAAC,OAAe;IAClC,OAAO,IAAI,UAAU,CAAC,yBAAyB,EAAE,OAAO,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { AgentError } from \"../errors.js\";\nimport type { EventScope } from \"../sdk/event-types.js\";\nimport type { CoordinatorTransport } from \"./transport.js\";\n\n// The private line allows one bounded 128 KiB event plus its fixed wire envelope.\nexport const SESSION_EVENT_WIRE_MAX_BYTES = 132 * 1024;\n\nexport class SessionEventsTransport {\n constructor(private readonly transport: CoordinatorTransport) {}\n\n records(scope: EventScope, signal: AbortSignal): AsyncIterable<unknown> {\n return readEventRecords(this.transport, scope, signal);\n }\n}\n\nasync function* readEventRecords(\n transport: CoordinatorTransport,\n scope: EventScope,\n signal: AbortSignal,\n): AsyncGenerator<unknown> {\n if (transport.disconnected.aborted) throw unavailable(\"The coordinator client is disconnected.\");\n const combined = AbortSignal.any([transport.disconnected, signal]);\n let response: Response;\n try {\n response = await fetch(transport.endpoint.url, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${transport.endpoint.token}`,\n \"content-type\": \"application/json\",\n \"x-subharness-instance\": transport.endpoint.instanceId,\n },\n body: JSON.stringify({ command: \"sdk.events.open\", scope }),\n signal: combined,\n });\n } catch {\n if (signal.aborted) throw observationClosed();\n throw unavailable(\"Connection to the local coordinator failed. The task was not automatically retried.\");\n }\n if (!response.ok) {\n void response.body?.cancel().catch(() => {});\n if (response.status === 401) {\n throw new AgentError(\"COORDINATOR_AUTH_FAILED\", \"The local coordinator rejected its private authentication token.\");\n }\n throw unavailable(`The coordinator rejected the sdk.events.open operation with HTTP status ${response.status}.`);\n }\n if (!response.body) {\n throw unavailable(\"The coordinator returned a successful response with no body for the sdk.events.open operation.\");\n }\n const reader = response.body.getReader();\n const lines = new BoundedLineDecoder();\n let complete = false;\n try {\n for (;;) {\n const result = await reader.read();\n if (result.done) { complete = true; break; }\n for (const line of lines.push(result.value)) yield parseLine(line);\n }\n lines.finish();\n } catch (error) {\n if (error instanceof AgentError) throw error;\n if (signal.aborted) throw observationClosed();\n throw unavailable(\"The coordinator response stream was interrupted. The task was not automatically retried.\");\n } finally {\n if (!complete) await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\nclass BoundedLineDecoder {\n private chunks: Uint8Array[] = [];\n private bytes = 0;\n\n push(chunk: Uint8Array): string[] {\n const lines: string[] = [];\n let start = 0;\n for (;;) {\n const newline = chunk.indexOf(10, start);\n if (newline < 0) {\n this.append(chunk.subarray(start));\n return lines;\n }\n this.append(chunk.subarray(start, newline));\n const line = this.decode();\n this.chunks = [];\n this.bytes = 0;\n if (line.length > 0) lines.push(line);\n start = newline + 1;\n if (start === chunk.length) return lines;\n }\n }\n\n finish(): void {\n if (this.bytes === 0) return;\n const remaining = this.decode();\n if (remaining.trim()) {\n throw unavailable(\"The coordinator response ended with an incomplete final record for the sdk.events.open operation. The task was not automatically retried.\");\n }\n }\n\n private append(chunk: Uint8Array): void {\n if (chunk.length === 0) return;\n if (this.bytes + chunk.length > SESSION_EVENT_WIRE_MAX_BYTES) {\n throw unavailable(\"The coordinator returned an oversized live event record.\");\n }\n this.chunks.push(chunk.slice());\n this.bytes += chunk.length;\n }\n\n private decode(): string {\n const value = new Uint8Array(this.bytes);\n let offset = 0;\n for (const chunk of this.chunks) { value.set(chunk, offset); offset += chunk.length; }\n try { return new TextDecoder(\"utf-8\", { fatal: true }).decode(value); }\n catch { throw unavailable(\"The coordinator returned a malformed live event record.\"); }\n }\n}\n\nfunction parseLine(line: string): unknown {\n try { return JSON.parse(line) as unknown; }\n catch {\n throw unavailable(\"The coordinator returned a malformed JSON record for the sdk.events.open operation. The task was not automatically retried.\");\n }\n}\n\nfunction observationClosed(): AgentError {\n return new AgentError(\"OBSERVATION_CLOSED\", \"The live event observation was closed.\");\n}\n\nfunction unavailable(message: string): AgentError {\n return new AgentError(\"COORDINATOR_UNAVAILABLE\", message);\n}\n"]}
|
|
@@ -3,3 +3,5 @@ export interface StartupOwnership {
|
|
|
3
3
|
release(): void;
|
|
4
4
|
}
|
|
5
5
|
export declare function acquireStartupOwnership(directory: string, timeoutMs: number): StartupOwnership;
|
|
6
|
+
export declare function acquireFileOwnership(directory: string, filename: string, timeoutMs: number): StartupOwnership;
|
|
7
|
+
export declare function isFileOwnershipContention(error: unknown): boolean;
|
|
@@ -1,22 +1,39 @@
|
|
|
1
1
|
import { chmodSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
2
3
|
import { join } from 'node:path';
|
|
3
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
4
4
|
import { AgentError } from '../errors.js';
|
|
5
|
+
const require = createRequire(import.meta.url);
|
|
6
|
+
let DatabaseSync;
|
|
7
|
+
class FileOwnershipError extends Error {
|
|
8
|
+
contended;
|
|
9
|
+
constructor(contended) {
|
|
10
|
+
super('File ownership is unavailable.');
|
|
11
|
+
this.contended = contended;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
5
14
|
export function acquireStartupOwnership(directory, timeoutMs) {
|
|
15
|
+
try {
|
|
16
|
+
return acquireFileOwnership(directory, 'startup.sqlite', timeoutMs);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new AgentError('STARTUP_FAILED', 'Another command did not finish coordinator startup.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function acquireFileOwnership(directory, filename, timeoutMs) {
|
|
6
23
|
const timeout = Number.isFinite(timeoutMs) ? Math.max(0, Math.ceil(timeoutMs)) : 0;
|
|
7
24
|
let database;
|
|
8
25
|
try {
|
|
9
|
-
const path = join(directory,
|
|
10
|
-
database = new
|
|
26
|
+
const path = join(directory, filename);
|
|
27
|
+
database = new (sqliteDatabase())(path, { timeout });
|
|
11
28
|
chmodSync(path, 0o600);
|
|
12
29
|
database.exec('BEGIN IMMEDIATE');
|
|
13
30
|
}
|
|
14
|
-
catch {
|
|
31
|
+
catch (error) {
|
|
15
32
|
try {
|
|
16
33
|
database?.close();
|
|
17
34
|
}
|
|
18
35
|
catch { /* Process exit also releases SQLite ownership. */ }
|
|
19
|
-
throw new
|
|
36
|
+
throw new FileOwnershipError(isSqliteContention(error));
|
|
20
37
|
}
|
|
21
38
|
let held = true;
|
|
22
39
|
return {
|
|
@@ -34,4 +51,31 @@ export function acquireStartupOwnership(directory, timeoutMs) {
|
|
|
34
51
|
},
|
|
35
52
|
};
|
|
36
53
|
}
|
|
54
|
+
export function isFileOwnershipContention(error) {
|
|
55
|
+
return error instanceof FileOwnershipError && error.contended;
|
|
56
|
+
}
|
|
57
|
+
function isSqliteContention(error) {
|
|
58
|
+
if (typeof error !== 'object' || error === null)
|
|
59
|
+
return false;
|
|
60
|
+
const value = error;
|
|
61
|
+
return value.code === 'ERR_SQLITE_ERROR' && (value.errcode === 5 || value.errcode === 6);
|
|
62
|
+
}
|
|
63
|
+
function sqliteDatabase() {
|
|
64
|
+
if (DatabaseSync)
|
|
65
|
+
return DatabaseSync;
|
|
66
|
+
const emitWarning = process.emitWarning;
|
|
67
|
+
process.emitWarning = ((warning, ...arguments_) => {
|
|
68
|
+
const message = typeof warning === 'string' ? warning : warning.message;
|
|
69
|
+
if (message === 'SQLite is an experimental feature and might change at any time')
|
|
70
|
+
return;
|
|
71
|
+
Reflect.apply(emitWarning, process, [warning, ...arguments_]);
|
|
72
|
+
});
|
|
73
|
+
try {
|
|
74
|
+
DatabaseSync = require('node:sqlite').DatabaseSync;
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
process.emitWarning = emitWarning;
|
|
78
|
+
}
|
|
79
|
+
return DatabaseSync;
|
|
80
|
+
}
|
|
37
81
|
//# sourceMappingURL=startup-lock.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startup-lock.js","sourceRoot":"","sources":["../../src/runtime/startup-lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"startup-lock.js","sourceRoot":"","sources":["../../src/runtime/startup-lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC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AAC,CAA+B,CAAC;IACjC,IAAI,CAAC;QAAC,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,YAAY,CAAC;IAAC,CAAC;YACnD,CAAC;QAAC,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;IAAC,CAAC;IAC9C,OAAO,YAAa,CAAC;AACvB,CAAC","sourcesContent":["import { chmodSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport type { DatabaseSync as Database } from 'node:sqlite';\nimport { AgentError } from '../errors.js';\n\nconst require = createRequire(import.meta.url);\nlet DatabaseSync: typeof import('node:sqlite').DatabaseSync | undefined;\n\nclass FileOwnershipError extends Error {\n constructor(readonly contended:boolean) { super('File ownership is unavailable.'); }\n}\n\nexport interface StartupOwnership {\n isHeld(): boolean;\n release(): void;\n}\n\nexport function acquireStartupOwnership(directory: string, timeoutMs: number): StartupOwnership {\n try { return acquireFileOwnership(directory,'startup.sqlite',timeoutMs); }\n catch { throw new AgentError('STARTUP_FAILED','Another command did not finish coordinator startup.'); }\n}\n\nexport function acquireFileOwnership(directory: string, filename: string, timeoutMs: number): StartupOwnership {\n const timeout = Number.isFinite(timeoutMs) ? Math.max(0,Math.ceil(timeoutMs)) : 0;\n let database: Database | undefined;\n try {\n const path = join(directory,filename);\n database = new (sqliteDatabase())(path,{timeout});\n chmodSync(path,0o600);\n database.exec('BEGIN IMMEDIATE');\n } catch(error) {\n try { database?.close(); } catch { /* Process exit also releases SQLite ownership. */ }\n throw new FileOwnershipError(isSqliteContention(error));\n }\n\n let held = true;\n return {\n isHeld:() => held,\n release() {\n if (!held) return;\n held = false;\n try { database.exec('ROLLBACK'); }\n finally { database.close(); }\n },\n };\n}\n\nexport function isFileOwnershipContention(error:unknown):boolean {\n return error instanceof FileOwnershipError && error.contended;\n}\n\nfunction isSqliteContention(error:unknown):boolean {\n if (typeof error !== 'object' || error === null) return false;\n const value=error as {code?:unknown;errcode?:unknown};\n return value.code === 'ERR_SQLITE_ERROR' && (value.errcode === 5 || value.errcode === 6);\n}\n\nfunction sqliteDatabase(): typeof import('node:sqlite').DatabaseSync {\n if (DatabaseSync) return DatabaseSync;\n const emitWarning = process.emitWarning;\n process.emitWarning = ((warning: string | Error, ...arguments_: unknown[]) => {\n const message = typeof warning === 'string' ? warning : warning.message;\n if (message === 'SQLite is an experimental feature and might change at any time') return;\n Reflect.apply(emitWarning, process, [warning, ...arguments_]);\n }) as typeof process.emitWarning;\n try { DatabaseSync = require('node:sqlite').DatabaseSync; }\n finally { process.emitWarning = emitWarning; }\n return DatabaseSync!;\n}\n"]}
|
package/dist/runtime/state.d.ts
CHANGED
|
@@ -3,8 +3,9 @@ export interface Endpoint {
|
|
|
3
3
|
token: string;
|
|
4
4
|
pid: number;
|
|
5
5
|
instanceId: string;
|
|
6
|
+
readonly capabilities?: readonly string[];
|
|
6
7
|
}
|
|
7
|
-
export type EndpointCapability = 'sdk-v1' | 'cli-v1';
|
|
8
|
+
export type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'cli-root-v1' | 'session-events-v1';
|
|
8
9
|
export type OwnerState = 'alive' | 'dead' | 'unknown';
|
|
9
10
|
export type EndpointProbe = {
|
|
10
11
|
readonly kind: 'absent';
|
package/dist/runtime/state.js
CHANGED
|
@@ -79,6 +79,10 @@ export async function probeEndpoint(directory, options = {}) {
|
|
|
79
79
|
|| (options.capability && !record.capabilities.includes(options.capability))) {
|
|
80
80
|
return { kind: 'incompatible', endpoint: parsed };
|
|
81
81
|
}
|
|
82
|
+
// Capabilities are live health metadata, not part of the persisted owner-private endpoint record.
|
|
83
|
+
Object.defineProperty(parsed, 'capabilities', {
|
|
84
|
+
value: Object.freeze([...record.capabilities]), enumerable: false, writable: false, configurable: false,
|
|
85
|
+
});
|
|
82
86
|
return { kind: 'reachable', endpoint: parsed };
|
|
83
87
|
}
|
|
84
88
|
export function processOwnerState(pid) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","sourceRoot":"","sources":["../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AC;AACH,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,SAAiB;IAClD,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,SAAS,EAAC,EAAC,UAAU,EAAC,QAAQ,EAAC,CAAC,CAAC;IACnE,OAAO,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AACD,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IAChE,OAAO,EAAE,IAAI,EAAC,aAAa,CAAC,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7E,QAAQ,EAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,EAAC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACjF,CAAC","sourcesContent":["import { homedir } from 'node:os';\nimport { isAbsolute, join, normalize } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { mkdir, readFile, chmod } from 'node:fs/promises';\nimport { AgentError } from '../errors.js';\n\nexport interface Endpoint { url: string; token: string; pid: number; instanceId: string }\nexport type EndpointCapability = 'sdk-v1' | 'cli-v1';\nexport type OwnerState = 'alive' | 'dead' | 'unknown';\nexport type EndpointProbe =\n | { readonly kind: 'absent' }\n | { readonly kind: 'malformed' }\n | { readonly kind: 'reachable'; readonly endpoint: Endpoint }\n | { readonly kind: 'authentication-failed' | 'incompatible' | 'instance-mismatch'; readonly endpoint: Endpoint }\n | { readonly kind: 'unresponsive'; readonly endpoint: Endpoint; readonly owner: OwnerState };\nexport interface EndpointProbeOptions {\n readonly capability?: EndpointCapability;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly checkPid?: (pid: number) => OwnerState;\n}\nexport function resolveStateDirectory(\n explicit?: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const selected = explicit ?? env.AGENT_STATE_DIR ?? join(homedir(),'.subharness','state','shared');\n if (!selected || !isAbsolute(selected)) {\n throw new AgentError('INVALID_CONFIG','Coordinator state directory must be a nonempty absolute local path.');\n }\n return normalize(selected);\n}\nexport function stateDirectory() {\n return resolveStateDirectory();\n}\nexport async function privateDirectory(directory: string) {\n await mkdir(directory,{recursive:true,mode:0o700});\n await chmod(directory,0o700);\n}\nexport async function probeEndpoint(directory: string, options: EndpointProbeOptions = {}): Promise<EndpointProbe> {\n let source: string;\n try { source = await readFile(join(directory,'coordinator.json'),'utf8'); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {kind:'absent'};\n return {kind:'malformed'};\n }\n let candidate: unknown;\n try { candidate = JSON.parse(source); }\n catch { return {kind:'malformed'}; }\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return {kind:'malformed'};\n const endpoint = candidate as Partial<Endpoint>;\n if (!/^http:\\/\\/127\\.0\\.0\\.1:\\d+\\/$/.test(String(endpoint.url))\n || typeof endpoint.token !== 'string' || !endpoint.token\n || !Number.isSafeInteger(endpoint.pid) || endpoint.pid! <= 0\n || typeof endpoint.instanceId !== 'string' || !endpoint.instanceId) return {kind:'malformed'};\n const parsed = endpoint as Endpoint;\n let response: Response;\n try {\n const timeout = AbortSignal.timeout(Math.max(1,options.timeoutMs ?? 500));\n response = await fetch(parsed.url + 'health', {\n headers:{authorization:`Bearer ${parsed.token}`},\n signal:options.signal ? AbortSignal.any([options.signal,timeout]) : timeout,\n });\n } catch {\n return {kind:'unresponsive',endpoint:parsed,owner:(options.checkPid ?? processOwnerState)(parsed.pid)};\n }\n if (response.status === 401 || response.status === 403) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'authentication-failed',endpoint:parsed};\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'incompatible',endpoint:parsed};\n }\n let health: unknown;\n try { health = await response.json(); }\n catch { return {kind:'incompatible',endpoint:parsed}; }\n if (!health || typeof health !== 'object' || Array.isArray(health)) return {kind:'incompatible',endpoint:parsed};\n const record = health as Record<string,unknown>;\n if (record.instanceId !== parsed.instanceId) return {kind:'instance-mismatch',endpoint:parsed};\n if (record.version !== 1 || record.type !== 'coordinator-health' || record.protocolVersion !== 1\n || !Array.isArray(record.capabilities) || !record.capabilities.every(item => typeof item === 'string')\n || (options.capability && !record.capabilities.includes(options.capability))) {\n return {kind:'incompatible',endpoint:parsed};\n }\n return {kind:'reachable',endpoint:parsed};\n}\n\nexport function processOwnerState(pid: number): OwnerState {\n try { process.kill(pid,0); return 'alive'; }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === 'ESRCH' ? 'dead' : 'unknown';\n }\n}\nexport async function readEndpoint(directory: string): Promise<Endpoint | undefined> {\n const probe = await probeEndpoint(directory,{capability:'cli-v1'});\n return probe.kind === 'reachable' ? probe.endpoint : undefined;\n}\nexport function localProgram(name: string) {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n return { file:fileURLToPath(new URL(`./${name}.${extension}`, import.meta.url)),\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [] };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"state.js","sourceRoot":"","sources":["../../src/runtime/state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,UAAU,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,SAAiB;IAClD,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,SAAS,EAAC,EAAC,UAAU,EAAC,QAAQ,EAAC,CAAC,CAAC;IACnE,OAAO,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AACD,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IAChE,OAAO,EAAE,IAAI,EAAC,aAAa,CAAC,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7E,QAAQ,EAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,EAAC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACjF,CAAC","sourcesContent":["import { homedir } from 'node:os';\nimport { isAbsolute, join, normalize } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { mkdir, readFile, chmod } from 'node:fs/promises';\nimport { AgentError } from '../errors.js';\n\nexport interface Endpoint {\n url: string;\n token: string;\n pid: number;\n instanceId: string;\n readonly capabilities?: readonly string[];\n}\nexport type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'cli-root-v1' | 'session-events-v1';\nexport type OwnerState = 'alive' | 'dead' | 'unknown';\nexport type EndpointProbe =\n | { readonly kind: 'absent' }\n | { readonly kind: 'malformed' }\n | { readonly kind: 'reachable'; readonly endpoint: Endpoint }\n | { readonly kind: 'authentication-failed' | 'incompatible' | 'instance-mismatch'; readonly endpoint: Endpoint }\n | { readonly kind: 'unresponsive'; readonly endpoint: Endpoint; readonly owner: OwnerState };\nexport interface EndpointProbeOptions {\n readonly capability?: EndpointCapability;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly checkPid?: (pid: number) => OwnerState;\n}\nexport function resolveStateDirectory(\n explicit?: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const selected = explicit ?? env.AGENT_STATE_DIR ?? join(homedir(),'.subharness','state','shared');\n if (!selected || !isAbsolute(selected)) {\n throw new AgentError('INVALID_CONFIG','Coordinator state directory must be a nonempty absolute local path.');\n }\n return normalize(selected);\n}\nexport function stateDirectory() {\n return resolveStateDirectory();\n}\nexport async function privateDirectory(directory: string) {\n await mkdir(directory,{recursive:true,mode:0o700});\n await chmod(directory,0o700);\n}\nexport async function probeEndpoint(directory: string, options: EndpointProbeOptions = {}): Promise<EndpointProbe> {\n let source: string;\n try { source = await readFile(join(directory,'coordinator.json'),'utf8'); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {kind:'absent'};\n return {kind:'malformed'};\n }\n let candidate: unknown;\n try { candidate = JSON.parse(source); }\n catch { return {kind:'malformed'}; }\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return {kind:'malformed'};\n const endpoint = candidate as Partial<Endpoint>;\n if (!/^http:\\/\\/127\\.0\\.0\\.1:\\d+\\/$/.test(String(endpoint.url))\n || typeof endpoint.token !== 'string' || !endpoint.token\n || !Number.isSafeInteger(endpoint.pid) || endpoint.pid! <= 0\n || typeof endpoint.instanceId !== 'string' || !endpoint.instanceId) return {kind:'malformed'};\n const parsed = endpoint as Endpoint;\n let response: Response;\n try {\n const timeout = AbortSignal.timeout(Math.max(1,options.timeoutMs ?? 500));\n response = await fetch(parsed.url + 'health', {\n headers:{authorization:`Bearer ${parsed.token}`},\n signal:options.signal ? AbortSignal.any([options.signal,timeout]) : timeout,\n });\n } catch {\n return {kind:'unresponsive',endpoint:parsed,owner:(options.checkPid ?? processOwnerState)(parsed.pid)};\n }\n if (response.status === 401 || response.status === 403) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'authentication-failed',endpoint:parsed};\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'incompatible',endpoint:parsed};\n }\n let health: unknown;\n try { health = await response.json(); }\n catch { return {kind:'incompatible',endpoint:parsed}; }\n if (!health || typeof health !== 'object' || Array.isArray(health)) return {kind:'incompatible',endpoint:parsed};\n const record = health as Record<string,unknown>;\n if (record.instanceId !== parsed.instanceId) return {kind:'instance-mismatch',endpoint:parsed};\n if (record.version !== 1 || record.type !== 'coordinator-health' || record.protocolVersion !== 1\n || !Array.isArray(record.capabilities) || !record.capabilities.every(item => typeof item === 'string')\n || (options.capability && !record.capabilities.includes(options.capability))) {\n return {kind:'incompatible',endpoint:parsed};\n }\n // Capabilities are live health metadata, not part of the persisted owner-private endpoint record.\n Object.defineProperty(parsed,'capabilities',{\n value:Object.freeze([...record.capabilities]),enumerable:false,writable:false,configurable:false,\n });\n return {kind:'reachable',endpoint:parsed};\n}\n\nexport function processOwnerState(pid: number): OwnerState {\n try { process.kill(pid,0); return 'alive'; }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === 'ESRCH' ? 'dead' : 'unknown';\n }\n}\nexport async function readEndpoint(directory: string): Promise<Endpoint | undefined> {\n const probe = await probeEndpoint(directory,{capability:'cli-v1'});\n return probe.kind === 'reachable' ? probe.endpoint : undefined;\n}\nexport function localProgram(name: string) {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n return { file:fileURLToPath(new URL(`./${name}.${extension}`, import.meta.url)),\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [] };\n}\n"]}
|
|
@@ -3,6 +3,7 @@ export declare class CoordinatorTransport {
|
|
|
3
3
|
readonly endpoint: Endpoint;
|
|
4
4
|
private readonly closed;
|
|
5
5
|
constructor(endpoint: Endpoint);
|
|
6
|
+
get disconnected(): AbortSignal;
|
|
6
7
|
disconnect(): void;
|
|
7
8
|
one<T>(body: unknown, signal?: AbortSignal): Promise<T>;
|
|
8
9
|
stream<T>(body: unknown, signal?: AbortSignal): AsyncIterable<T>;
|
|
@@ -5,6 +5,7 @@ export class CoordinatorTransport {
|
|
|
5
5
|
constructor(endpoint) {
|
|
6
6
|
this.endpoint = endpoint;
|
|
7
7
|
}
|
|
8
|
+
get disconnected() { return this.closed.signal; }
|
|
8
9
|
disconnect() { this.closed.abort(); }
|
|
9
10
|
async one(body, signal) {
|
|
10
11
|
let value;
|
|
@@ -159,6 +160,7 @@ const operations = new Set([
|
|
|
159
160
|
'sdk-session-create', 'sdk-session-get', 'sdk-session-list', 'sdk-session-prompt', 'sdk-session-close',
|
|
160
161
|
'sdk-task-get', 'sdk-task-list', 'sdk-task-snapshot', 'sdk-task-inspect', 'sdk-task-result', 'sdk-task-watch',
|
|
161
162
|
'sdk-task-responses', 'sdk-task-cancel', 'sdk-approval-respond',
|
|
163
|
+
'sdk.events.open', 'sdk.events.capabilities',
|
|
162
164
|
]);
|
|
163
165
|
function unavailable(message) {
|
|
164
166
|
return new AgentError('COORDINATOR_UNAVAILABLE', message);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/runtime/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAS1C,MAAM,OAAO,oBAAoB;IAEV,QAAQ;IADZ,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IAChD,YAAqB,QAAiB;wBAAjB,QAAQ;IAAY,CAAC;IAE1C,UAAU,KAAW,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAE3C,KAAK,CAAC,GAAG,CAAI,IAAY,EAAC,MAAmB;QAC3C,IAAI,KAAiB,CAAC;QACtB,IAAI,KAAK,GAAC,CAAC,CAAC;QACZ,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAC,MAAM,CAAC,EAAE,CAAC;YACrD,WA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C;AAED,MAAM,UAAU,GAAC,IAAI,GAAG,CAAC;IACvB,WAAW,EAAC,mBAAmB,EAAC,kBAAkB,EAAC,QAAQ,EAAC,KAAK,EAAC,MAAM,EAAC,QAAQ,EAAC,MAAM,EAAC,QAAQ,EAAC,OAAO,EAAC,QAAQ,EAAC,SAAS;IAC5H,gBAAgB,EAAC,iBAAiB;IAClC,oBAAoB,EAAC,iBAAiB,EAAC,kBAAkB,EAAC,oBAAoB,EAAC,mBAAmB;IAClG,cAAc,EAAC,eAAe,EAAC,mBAAmB,EAAC,kBAAkB,EAAC,iBAAiB,EAAC,gBAAgB;IACxG,oBAAoB,EAAC,iBAAiB,EAAC,sBAAsB;CAC9D,CAAC,CAAC;AAEH,SAAS,WAAW,CAAC,OAAc;IACjC,OAAO,IAAI,UAAU,CAAC,yBAAyB,EAAC,OAAO,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { AgentError } from '../errors.js';\nimport type { Endpoint } from './state.js';\n\ninterface ErrorRecord {\n readonly version: 1;\n readonly type: 'error';\n readonly error: {readonly code:string;readonly message:string};\n}\n\nexport class CoordinatorTransport {\n private readonly closed = new AbortController();\n constructor(readonly endpoint:Endpoint) {}\n\n disconnect(): void { this.closed.abort(); }\n\n async one<T>(body:unknown,signal?:AbortSignal):Promise<T> {\n let value:T|undefined;\n let count=0;\n for await (const record of this.records(body,signal)) {\n throwRemote(record);\n value=record as T;\n count++;\n if (count > 1) throw unavailable('The coordinator returned too many records for one operation.');\n }\n if (count !== 1) throw unavailable('The coordinator returned no record for the operation.');\n return value!;\n }\n\n stream<T>(body:unknown,signal?:AbortSignal):AsyncIterable<T> {\n const transport=this;\n return {[Symbol.asyncIterator]():AsyncIterator<T> {\n const lifetime=new AbortController();\n const observerSignal=signal ? AbortSignal.any([signal,lifetime.signal]) : lifetime.signal;\n const source=transport.records(body,observerSignal)[Symbol.asyncIterator]();\n return {\n async next() {\n const result=await source.next();\n if(result.done)return {done:true,value:undefined};\n throwRemote(result.value);\n return {done:false,value:result.value as T};\n },\n async return() {\n lifetime.abort();\n try{await source.return?.(undefined);}catch{}\n return {done:true,value:undefined};\n },\n async throw(error?:unknown) {\n lifetime.abort();\n if(source.throw)return source.throw(error) as Promise<IteratorResult<T>>;\n throw error;\n },\n };\n }};\n }\n\n async *records(body:unknown,signal?:AbortSignal,options:{allowFinalRecord?:boolean}={}):AsyncGenerator<unknown> {\n this.assertOpen();\n const operation=operationName(body);\n const combined=signal\n ? AbortSignal.any([this.closed.signal,signal])\n : this.closed.signal;\n let response:Response;\n try {\n response=await fetch(this.endpoint.url,{\n method:'POST',\n headers:{authorization:`Bearer ${this.endpoint.token}`,'content-type':'application/json',\n 'x-subharness-instance':this.endpoint.instanceId},\n body:JSON.stringify(body),\n signal:combined,\n });\n } catch {\n if (signal?.aborted) throw new AgentError('OBSERVATION_CLOSED','The observer disconnected.');\n throw unavailable('Connection to the local coordinator failed. The task was not automatically retried.');\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n if (response.status === 401)\n throw new AgentError('COORDINATOR_AUTH_FAILED','The local coordinator rejected its private authentication token.');\n throw unavailable(`The coordinator rejected ${operation ? `the ${operation} operation` : 'the request'} with HTTP status ${response.status}.`);\n }\n if (!response.body) throw unavailable(\n `The coordinator returned a successful response with no body${operation ? ` for the ${operation} operation` : ''}.`);\n let buffer='';\n const decoder=new TextDecoder();\n const reader=response.body.getReader();\n let complete=false;\n try {\n for (;;) {\n const result=await reader.read();\n if (result.done) { complete=true; break; }\n const chunk=result.value;\n buffer+=decoder.decode(chunk,{stream:true});\n let newline:number;\n while ((newline=buffer.indexOf('\\n')) >= 0) {\n const line=buffer.slice(0,newline); buffer=buffer.slice(newline+1);\n if (!line) continue;\n try { yield JSON.parse(line) as unknown; }\n catch { throw unavailable(`The coordinator returned a malformed JSON record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`); }\n }\n }\n buffer+=decoder.decode();\n if (buffer.trim()) {\n if (options.allowFinalRecord) {\n try { yield JSON.parse(buffer) as unknown; }\n catch { throw unavailable(`The coordinator returned a malformed JSON record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`); }\n } else throw unavailable(\n `The coordinator response ended with an incomplete final record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`);\n }\n } catch (error) {\n if (error instanceof AgentError) throw error;\n if (signal?.aborted) throw new AgentError('OBSERVATION_CLOSED','The observer disconnected.');\n throw unavailable('The coordinator response stream was interrupted. The task was not automatically retried.');\n } finally {\n if (!complete) await reader.cancel().catch(()=>{});\n reader.releaseLock();\n }\n }\n\n private assertOpen():void {\n if (this.closed.signal.aborted) throw unavailable('The coordinator client is disconnected.');\n }\n}\n\nfunction throwRemote(value:unknown):void {\n if (!value || typeof value !== 'object' || (value as {type?:unknown}).type !== 'error') return;\n const record=value as Partial<ErrorRecord>;\n if (!record.error || typeof record.error.code !== 'string' || typeof record.error.message !== 'string')\n throw unavailable('The coordinator returned a malformed error record.');\n throw new AgentError(record.error.code,record.error.message);\n}\n\nfunction operationName(body:unknown):string|undefined {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return;\n const command=(body as {command?:unknown}).command;\n return typeof command === 'string' && operations.has(command) ? command : undefined;\n}\n\nconst operations=new Set([\n 'dashboard','dashboard-session','dashboard-detail','parent','run','send','resume','wait','status','queue','cancel','respond',\n 'sdk-agent-list','sdk-agent-check',\n 'sdk-session-create','sdk-session-get','sdk-session-list','sdk-session-prompt','sdk-session-close',\n 'sdk-task-get','sdk-task-list','sdk-task-snapshot','sdk-task-inspect','sdk-task-result','sdk-task-watch',\n 'sdk-task-responses','sdk-task-cancel','sdk-approval-respond',\n]);\n\nfunction unavailable(message:string):AgentError {\n return new AgentError('COORDINATOR_UNAVAILABLE',message);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/runtime/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAS1C,MAAM,OAAO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AAM,WAAW,CAAC,oDAAoD,CAAC,CAAC;IAC1E,MAAM,IAAI,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,aAAa,CAAC,IAAY;IACjC,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO;IACrE,MAAM,OAAO,GAAE,IAA2B,CAAC,OAAO,CAAC;IACnD,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AACtF,CAAC;AAED,MAAM,UAAU,GAAC,IAAI,GAAG,CAAC;IACvB,WAAW,EAAC,mBAAmB,EAAC,kBAAkB,EAAC,QAAQ,EAAC,KAAK,EAAC,MAAM,EAAC,QAAQ,EAAC,MAAM,EAAC,QAAQ,EAAC,OAAO,EAAC,QAAQ,EAAC,SAAS;IAC5H,gBAAgB,EAAC,iBAAiB;IAClC,oBAAoB,EAAC,iBAAiB,EAAC,kBAAkB,EAAC,oBAAoB,EAAC,mBAAmB;IAClG,cAAc,EAAC,eAAe,EAAC,mBAAmB,EAAC,kBAAkB,EAAC,iBAAiB,EAAC,gBAAgB;IACxG,oBAAoB,EAAC,iBAAiB,EAAC,sBAAsB;IAC7D,iBAAiB,EAAC,yBAAyB;CAC5C,CAAC,CAAC;AAEH,SAAS,WAAW,CAAC,OAAc;IACjC,OAAO,IAAI,UAAU,CAAC,yBAAyB,EAAC,OAAO,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { AgentError } from '../errors.js';\nimport type { Endpoint } from './state.js';\n\ninterface ErrorRecord {\n readonly version: 1;\n readonly type: 'error';\n readonly error: {readonly code:string;readonly message:string};\n}\n\nexport class CoordinatorTransport {\n private readonly closed = new AbortController();\n constructor(readonly endpoint:Endpoint) {}\n\n get disconnected(): AbortSignal { return this.closed.signal; }\n\n disconnect(): void { this.closed.abort(); }\n\n async one<T>(body:unknown,signal?:AbortSignal):Promise<T> {\n let value:T|undefined;\n let count=0;\n for await (const record of this.records(body,signal)) {\n throwRemote(record);\n value=record as T;\n count++;\n if (count > 1) throw unavailable('The coordinator returned too many records for one operation.');\n }\n if (count !== 1) throw unavailable('The coordinator returned no record for the operation.');\n return value!;\n }\n\n stream<T>(body:unknown,signal?:AbortSignal):AsyncIterable<T> {\n const transport=this;\n return {[Symbol.asyncIterator]():AsyncIterator<T> {\n const lifetime=new AbortController();\n const observerSignal=signal ? AbortSignal.any([signal,lifetime.signal]) : lifetime.signal;\n const source=transport.records(body,observerSignal)[Symbol.asyncIterator]();\n return {\n async next() {\n const result=await source.next();\n if(result.done)return {done:true,value:undefined};\n throwRemote(result.value);\n return {done:false,value:result.value as T};\n },\n async return() {\n lifetime.abort();\n try{await source.return?.(undefined);}catch{}\n return {done:true,value:undefined};\n },\n async throw(error?:unknown) {\n lifetime.abort();\n if(source.throw)return source.throw(error) as Promise<IteratorResult<T>>;\n throw error;\n },\n };\n }};\n }\n\n async *records(body:unknown,signal?:AbortSignal,options:{allowFinalRecord?:boolean}={}):AsyncGenerator<unknown> {\n this.assertOpen();\n const operation=operationName(body);\n const combined=signal\n ? AbortSignal.any([this.closed.signal,signal])\n : this.closed.signal;\n let response:Response;\n try {\n response=await fetch(this.endpoint.url,{\n method:'POST',\n headers:{authorization:`Bearer ${this.endpoint.token}`,'content-type':'application/json',\n 'x-subharness-instance':this.endpoint.instanceId},\n body:JSON.stringify(body),\n signal:combined,\n });\n } catch {\n if (signal?.aborted) throw new AgentError('OBSERVATION_CLOSED','The observer disconnected.');\n throw unavailable('Connection to the local coordinator failed. The task was not automatically retried.');\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n if (response.status === 401)\n throw new AgentError('COORDINATOR_AUTH_FAILED','The local coordinator rejected its private authentication token.');\n throw unavailable(`The coordinator rejected ${operation ? `the ${operation} operation` : 'the request'} with HTTP status ${response.status}.`);\n }\n if (!response.body) throw unavailable(\n `The coordinator returned a successful response with no body${operation ? ` for the ${operation} operation` : ''}.`);\n let buffer='';\n const decoder=new TextDecoder();\n const reader=response.body.getReader();\n let complete=false;\n try {\n for (;;) {\n const result=await reader.read();\n if (result.done) { complete=true; break; }\n const chunk=result.value;\n buffer+=decoder.decode(chunk,{stream:true});\n let newline:number;\n while ((newline=buffer.indexOf('\\n')) >= 0) {\n const line=buffer.slice(0,newline); buffer=buffer.slice(newline+1);\n if (!line) continue;\n try { yield JSON.parse(line) as unknown; }\n catch { throw unavailable(`The coordinator returned a malformed JSON record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`); }\n }\n }\n buffer+=decoder.decode();\n if (buffer.trim()) {\n if (options.allowFinalRecord) {\n try { yield JSON.parse(buffer) as unknown; }\n catch { throw unavailable(`The coordinator returned a malformed JSON record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`); }\n } else throw unavailable(\n `The coordinator response ended with an incomplete final record${operation ? ` for the ${operation} operation` : ''}. The task was not automatically retried.`);\n }\n } catch (error) {\n if (error instanceof AgentError) throw error;\n if (signal?.aborted) throw new AgentError('OBSERVATION_CLOSED','The observer disconnected.');\n throw unavailable('The coordinator response stream was interrupted. The task was not automatically retried.');\n } finally {\n if (!complete) await reader.cancel().catch(()=>{});\n reader.releaseLock();\n }\n }\n\n private assertOpen():void {\n if (this.closed.signal.aborted) throw unavailable('The coordinator client is disconnected.');\n }\n}\n\nfunction throwRemote(value:unknown):void {\n if (!value || typeof value !== 'object' || (value as {type?:unknown}).type !== 'error') return;\n const record=value as Partial<ErrorRecord>;\n if (!record.error || typeof record.error.code !== 'string' || typeof record.error.message !== 'string')\n throw unavailable('The coordinator returned a malformed error record.');\n throw new AgentError(record.error.code,record.error.message);\n}\n\nfunction operationName(body:unknown):string|undefined {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return;\n const command=(body as {command?:unknown}).command;\n return typeof command === 'string' && operations.has(command) ? command : undefined;\n}\n\nconst operations=new Set([\n 'dashboard','dashboard-session','dashboard-detail','parent','run','send','resume','wait','status','queue','cancel','respond',\n 'sdk-agent-list','sdk-agent-check',\n 'sdk-session-create','sdk-session-get','sdk-session-list','sdk-session-prompt','sdk-session-close',\n 'sdk-task-get','sdk-task-list','sdk-task-snapshot','sdk-task-inspect','sdk-task-result','sdk-task-watch',\n 'sdk-task-responses','sdk-task-cancel','sdk-approval-respond',\n 'sdk.events.open','sdk.events.capabilities',\n]);\n\nfunction unavailable(message:string):AgentError {\n return new AgentError('COORDINATOR_UNAVAILABLE',message);\n}\n"]}
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ import type { DashboardHarness, DashboardWorkspace } from './dashboard.js';
|
|
|
5
5
|
import type { ApprovalHandler } from '../approvals/types.js';
|
|
6
6
|
import type { AgentDefinition } from '../sdk/types.js';
|
|
7
7
|
import type { ApprovalRequest, TaskState } from './task-data.js';
|
|
8
|
+
import type { AdapterEventPort } from '../adapters/event-types.js';
|
|
9
|
+
import type { SessionEvent, SessionEventCapabilities } from '../sdk/event-types.js';
|
|
10
|
+
import type { OwnerEventOperation } from './event-operation.js';
|
|
11
|
+
import type { SelectedProject } from '../config/project-context.js';
|
|
8
12
|
export type { ApprovalRequest, TaskState } from './task-data.js';
|
|
9
13
|
export type Delivery = 'queue' | 'steer' | 'interrupt';
|
|
10
14
|
export interface AgentReference {
|
|
@@ -26,18 +30,34 @@ export interface SessionInput {
|
|
|
26
30
|
env: NodeJS.ProcessEnv;
|
|
27
31
|
prompt: string;
|
|
28
32
|
parentToken?: string;
|
|
33
|
+
project?: SelectedProject;
|
|
29
34
|
}
|
|
30
35
|
export type SessionCreateInput = Omit<SessionInput, 'prompt' | 'parentToken'>;
|
|
31
36
|
export interface DriverInput extends Omit<SessionInput, 'prompt' | 'parentToken'> {
|
|
32
37
|
token: string;
|
|
33
38
|
sessionId: string;
|
|
34
39
|
onApproval?: ApprovalHandler;
|
|
40
|
+
events?: AdapterEventPort;
|
|
35
41
|
}
|
|
36
42
|
export type ManagedNativeSession = NativeSession & {
|
|
37
43
|
selectedHarness?: HarnessKind;
|
|
38
44
|
};
|
|
39
45
|
export type DriverFactory = (input: DriverInput) => Promise<ManagedNativeSession>;
|
|
46
|
+
export interface ExecutionDisplayMetadata {
|
|
47
|
+
readonly agentName: string;
|
|
48
|
+
}
|
|
49
|
+
export interface OwnerEventSink {
|
|
50
|
+
offer(event: SessionEvent): void;
|
|
51
|
+
end(): void;
|
|
52
|
+
}
|
|
53
|
+
export interface OwnerEventRegistration {
|
|
54
|
+
registerSessionSink(sessionId: string, sink: OwnerEventSink): () => void;
|
|
55
|
+
}
|
|
56
|
+
export interface AdmissionObservers {
|
|
57
|
+
attach(sessionId: string, owner: OwnerEventRegistration): void;
|
|
58
|
+
}
|
|
40
59
|
export interface PreparedExecution {
|
|
60
|
+
readonly display?: ExecutionDisplayMetadata;
|
|
41
61
|
open(input: DriverInput): Promise<ManagedNativeSession>;
|
|
42
62
|
close(): Promise<void>;
|
|
43
63
|
}
|
|
@@ -95,6 +115,7 @@ export interface Task {
|
|
|
95
115
|
revision: number;
|
|
96
116
|
ordinal: number;
|
|
97
117
|
membership: number;
|
|
118
|
+
eventOperation?: OwnerEventOperation;
|
|
98
119
|
changed: Set<() => void>;
|
|
99
120
|
watchers: Set<() => void>;
|
|
100
121
|
}
|
|
@@ -112,6 +133,9 @@ export interface Session {
|
|
|
112
133
|
controls: number;
|
|
113
134
|
nextOrdinal: number;
|
|
114
135
|
membership: number;
|
|
136
|
+
display?: ExecutionDisplayMetadata;
|
|
137
|
+
selectedModel?: string;
|
|
138
|
+
eventCapabilities?: SessionEventCapabilities;
|
|
115
139
|
harness: DashboardHarness;
|
|
116
140
|
selectedHarness?: HarnessKind;
|
|
117
141
|
workspace: Promise<DashboardWorkspace>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/runtime/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/runtime/types.ts"],"names":[],"mappings":"AAsEA,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAgB,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC","sourcesContent":["import type { ErrorInfo } from '../errors.js';\nimport type { HarnessRequest, NativeSession } from '../adapters/types.js';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { DashboardHarness, DashboardWorkspace } from './dashboard.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { AgentDefinition } from '../sdk/types.js';\nimport type { ApprovalRequest, TaskState } from './task-data.js';\nimport type { AdapterEventPort } from '../adapters/event-types.js';\nimport type { SessionEvent, SessionEventCapabilities } from '../sdk/event-types.js';\nimport type { OwnerEventOperation } from './event-operation.js';\nimport type { SelectedProject } from '../config/project-context.js';\n\nexport type { ApprovalRequest, TaskState } from './task-data.js';\n\nexport type Delivery = 'queue' | 'steer' | 'interrupt';\nexport interface AgentReference { file: string; subagents: string[] }\nexport interface HarnessReference { kind: 'harness'; harness: HarnessRequest }\nexport interface InlineReference { kind: 'inline'; definition: AgentDefinition }\nexport type ExecutionReference = AgentReference | HarnessReference | InlineReference;\nexport interface SessionInput { reference: ExecutionReference; cwd: string; env: NodeJS.ProcessEnv; prompt: string;\n parentToken?: string; project?: SelectedProject }\nexport type SessionCreateInput = Omit<SessionInput, 'prompt' | 'parentToken'>;\nexport interface DriverInput extends Omit<SessionInput, 'prompt' | 'parentToken'> { token: string; sessionId: string; onApproval?: ApprovalHandler; events?: AdapterEventPort }\nexport type ManagedNativeSession = NativeSession & { selectedHarness?: HarnessKind };\nexport type DriverFactory = (input: DriverInput) => Promise<ManagedNativeSession>;\nexport interface ExecutionDisplayMetadata { readonly agentName: string }\nexport interface OwnerEventSink {\n offer(event: SessionEvent): void;\n end(): void;\n}\nexport interface OwnerEventRegistration {\n registerSessionSink(sessionId: string, sink: OwnerEventSink): () => void;\n}\nexport interface AdmissionObservers {\n attach(sessionId: string, owner: OwnerEventRegistration): void;\n}\nexport interface PreparedExecution {\n readonly display?: ExecutionDisplayMetadata;\n open(input: DriverInput): Promise<ManagedNativeSession>;\n close(): Promise<void>;\n}\nexport interface RecordBase { version: 1; type: string; sessionId: string; taskId: string; state?: TaskState }\nexport interface Observation extends RecordBase {\n state: TaskState; responseId?: string; text?: string; error?: ErrorInfo; requests?: ApprovalRequest[];\n stopUnconfirmed?: boolean;\n}\nexport interface Receipt extends RecordBase {\n delivery?: Delivery; requestedDelivery?: Delivery; resumed?: boolean;\n paused?: true; blockedByTaskId?: string;\n}\nexport interface Response extends Observation { type: 'response'; responseId: string; text: string }\nexport interface ChildResult { taskId: string; state: TaskState; text: string }\nexport interface Task {\n id: string; sessionId: string; prompt: string; title: string; parentId?: string; state: TaskState;\n responses: Response[]; children: Set<string>; inbox: ChildResult[]; nativeActive: boolean;\n stopping: boolean; stopPromise?: Promise<void>; stopUnconfirmed?: boolean; error?: ErrorInfo;\n dispatchedAt?: number; failedAt?: number; finishedAt?: number; updatedAt: number; revision: number;\n ordinal: number; membership: number;\n eventOperation?: OwnerEventOperation;\n changed: Set<() => void>; watchers: Set<() => void>;\n}\nexport interface Session {\n id: string; token: string; input: SessionCreateInput; driver?: Promise<ManagedNativeSession>;\n prepared?: PreparedExecution; preparedClosed?: boolean;\n tasks: string[]; active?: string; paused: boolean; commands: Promise<unknown>; controls: number;\n nextOrdinal: number; membership: number;\n display?: ExecutionDisplayMetadata; selectedModel?: string; eventCapabilities?: SessionEventCapabilities;\n harness: DashboardHarness; selectedHarness?: HarnessKind; workspace: Promise<DashboardWorkspace>;\n state: 'open' | 'closing' | 'closed'; closePromise?: Promise<void>; driverClosed?: boolean;\n}\nexport const terminal = (state: TaskState) => ['completed', 'failed', 'cancelled', 'interrupted'].includes(state);\n"]}
|