@nones/agentflow-core 0.0.0-stage → 0.1.0
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/package.json +38 -4
- package/src/artifacts.ts +220 -0
- package/src/client.ts +316 -0
- package/src/engine.ts +2839 -0
- package/src/errors.ts +45 -0
- package/src/ids.ts +14 -0
- package/src/index.ts +90 -0
- package/src/json.ts +91 -0
- package/src/jsonl-socket.ts +70 -0
- package/src/modules.ts +434 -0
- package/src/protocol.ts +76 -0
- package/src/quota.ts +140 -0
- package/src/schema.ts +282 -0
- package/src/server.ts +759 -0
- package/src/store.ts +1126 -0
- package/src/types.ts +467 -0
- package/src/validation.ts +311 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nones/agentflow-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AgentFlow contracts, durable store, scheduler, quotas and local JSON RPC",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"module": "./src/index.ts",
|
|
8
|
+
"types": "./src/index.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./src/index.ts",
|
|
12
|
+
"import": "./src/index.ts",
|
|
13
|
+
"default": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"./types": {
|
|
16
|
+
"types": "./src/types.ts",
|
|
17
|
+
"import": "./src/types.ts",
|
|
18
|
+
"default": "./src/types.ts"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"bun": ">=1.4.5"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public",
|
|
29
|
+
"registry": "https://registry.npmjs.org/"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/nones-tools/agentflow.git",
|
|
34
|
+
"directory": "apps/core"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "bun build ./src/index.ts --target=bun --outdir=.tmp/build --packages external",
|
|
38
|
+
"test": "bun test"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/artifacts.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { AgentFlowError } from "./errors";
|
|
4
|
+
import { fromJson, toJson } from "./json";
|
|
5
|
+
import { validateJsonSchema } from "./schema";
|
|
6
|
+
import type {
|
|
7
|
+
ArtifactDeclaration,
|
|
8
|
+
ArtifactOutput,
|
|
9
|
+
ArtifactState,
|
|
10
|
+
} from "./types";
|
|
11
|
+
import type { Store } from "./store";
|
|
12
|
+
|
|
13
|
+
export interface PreparedArtifact {
|
|
14
|
+
state: Extract<ArtifactState, "staged" | "invalid">;
|
|
15
|
+
value?: unknown;
|
|
16
|
+
path?: string;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validates one produced artifact against its declaration.
|
|
22
|
+
*
|
|
23
|
+
* File paths are resolved relative to the producing agent's cwd. Both lexical
|
|
24
|
+
* traversal and symlink escape are rejected by comparing the real path against
|
|
25
|
+
* the real cwd.
|
|
26
|
+
*/
|
|
27
|
+
export function prepareArtifact(
|
|
28
|
+
declaration: ArtifactDeclaration,
|
|
29
|
+
raw: unknown,
|
|
30
|
+
cwd: string,
|
|
31
|
+
): PreparedArtifact {
|
|
32
|
+
if (declaration.type === "file") {
|
|
33
|
+
return prepareFileArtifact(declaration, raw, cwd);
|
|
34
|
+
}
|
|
35
|
+
if (declaration.type === "json") {
|
|
36
|
+
let value = raw;
|
|
37
|
+
if (typeof raw === "string") {
|
|
38
|
+
try {
|
|
39
|
+
value = JSON.parse(raw);
|
|
40
|
+
} catch {
|
|
41
|
+
return { state: "invalid", error: "artifact is not valid JSON" };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (declaration.schema !== undefined) {
|
|
45
|
+
const errors = validateJsonSchema(value, declaration.schema);
|
|
46
|
+
if (errors.length > 0) {
|
|
47
|
+
return { state: "invalid", error: errors.join("; ") };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return { state: "staged", value };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (typeof raw !== "string") {
|
|
54
|
+
return { state: "invalid", error: "text artifact must be a string" };
|
|
55
|
+
}
|
|
56
|
+
if (declaration.schema !== undefined) {
|
|
57
|
+
const errors = validateJsonSchema(raw, declaration.schema);
|
|
58
|
+
if (errors.length > 0) {
|
|
59
|
+
return { state: "invalid", error: errors.join("; ") };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { state: "staged", value: raw };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function prepareFileArtifact(
|
|
66
|
+
declaration: ArtifactDeclaration,
|
|
67
|
+
raw: unknown,
|
|
68
|
+
cwd: string,
|
|
69
|
+
): PreparedArtifact {
|
|
70
|
+
let requested: string;
|
|
71
|
+
if (typeof raw === "string") {
|
|
72
|
+
requested = raw;
|
|
73
|
+
} else if (
|
|
74
|
+
raw !== null &&
|
|
75
|
+
typeof raw === "object" &&
|
|
76
|
+
typeof (raw as { path?: unknown }).path === "string"
|
|
77
|
+
) {
|
|
78
|
+
requested = (raw as { path: string }).path;
|
|
79
|
+
} else {
|
|
80
|
+
return { state: "invalid", error: "file artifact must be a path string" };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let root: string;
|
|
84
|
+
try {
|
|
85
|
+
root = realpathSync(resolve(cwd));
|
|
86
|
+
if (!statSync(root).isDirectory()) {
|
|
87
|
+
return { state: "invalid", error: "agent cwd is not a directory" };
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
return { state: "invalid", error: "agent cwd does not exist" };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const candidate = isAbsolute(requested)
|
|
94
|
+
? resolve(requested)
|
|
95
|
+
: resolve(root, requested);
|
|
96
|
+
if (!isInside(root, candidate)) {
|
|
97
|
+
return {
|
|
98
|
+
state: "invalid",
|
|
99
|
+
error: `artifact path escapes agent cwd: ${requested}`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
let real: string;
|
|
104
|
+
try {
|
|
105
|
+
real = realpathSync(candidate);
|
|
106
|
+
} catch {
|
|
107
|
+
return { state: "invalid", error: `artifact file not found: ${requested}` };
|
|
108
|
+
}
|
|
109
|
+
if (!isInside(root, real)) {
|
|
110
|
+
return {
|
|
111
|
+
state: "invalid",
|
|
112
|
+
error: `artifact path escapes agent cwd through a symlink: ${requested}`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
if (!statSync(real).isFile()) {
|
|
117
|
+
return {
|
|
118
|
+
state: "invalid",
|
|
119
|
+
error: `artifact is not a file: ${requested}`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
return { state: "invalid", error: `artifact file not found: ${requested}` };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// `schema` is meaningful for json/text payloads. File declarations carry the
|
|
127
|
+
// path plus the file itself and are intentionally not parsed by core.
|
|
128
|
+
void declaration;
|
|
129
|
+
return { state: "staged", value: { path: real }, path: real };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function isInside(root: string, candidate: string): boolean {
|
|
133
|
+
const rel = relative(root, candidate);
|
|
134
|
+
return rel === "" || (!rel.startsWith("..") && !rel.startsWith(`..${sep}`));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Re-validates and returns a staged artifact for CLI output. */
|
|
138
|
+
export function readArtifactOutput(
|
|
139
|
+
store: Store,
|
|
140
|
+
runId: string,
|
|
141
|
+
artifactId: string,
|
|
142
|
+
): ArtifactOutput {
|
|
143
|
+
const row = store.getArtifactRow(runId, artifactId);
|
|
144
|
+
if (row === undefined) {
|
|
145
|
+
throw new AgentFlowError(
|
|
146
|
+
"artifact_missing",
|
|
147
|
+
`artifact ${artifactId} is not declared for run ${runId}`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
const declaration = fromJson<ArtifactDeclaration>(row.declaration_json, {
|
|
151
|
+
id: artifactId,
|
|
152
|
+
type: "text",
|
|
153
|
+
});
|
|
154
|
+
if (row.state !== "staged") {
|
|
155
|
+
throw new AgentFlowError(
|
|
156
|
+
row.state === "invalid" ? "artifact_invalid" : "artifact_missing",
|
|
157
|
+
row.error ?? `artifact ${artifactId} is ${row.state}`,
|
|
158
|
+
{ artifactId, state: row.state },
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (declaration.type === "file") {
|
|
163
|
+
if (row.path === null) {
|
|
164
|
+
throw new AgentFlowError(
|
|
165
|
+
"artifact_invalid",
|
|
166
|
+
`artifact ${artifactId} has no resolved path`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const real = realpathSync(row.path);
|
|
171
|
+
if (real !== row.path || !statSync(real).isFile()) {
|
|
172
|
+
throw new Error("path changed");
|
|
173
|
+
}
|
|
174
|
+
} catch {
|
|
175
|
+
throw new AgentFlowError(
|
|
176
|
+
"artifact_invalid",
|
|
177
|
+
`artifact file is no longer available: ${artifactId}`,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
id: artifactId,
|
|
182
|
+
type: declaration.type,
|
|
183
|
+
required: declaration.required === true,
|
|
184
|
+
state: row.state,
|
|
185
|
+
value: { path: row.path },
|
|
186
|
+
path: row.path,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const value = fromJson<unknown>(row.value_json, null);
|
|
191
|
+
return {
|
|
192
|
+
id: artifactId,
|
|
193
|
+
type: declaration.type,
|
|
194
|
+
required: declaration.required === true,
|
|
195
|
+
state: row.state,
|
|
196
|
+
value,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function stagedValueJson(value: unknown): string {
|
|
201
|
+
return toJson(value);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Returns a human-readable reason for required-artifact failures. */
|
|
205
|
+
export function requiredArtifactFailure(
|
|
206
|
+
store: Store,
|
|
207
|
+
runId: string,
|
|
208
|
+
): string | undefined {
|
|
209
|
+
for (const row of store.getArtifactRows(runId)) {
|
|
210
|
+
const declaration = fromJson<ArtifactDeclaration>(row.declaration_json, {
|
|
211
|
+
id: row.id,
|
|
212
|
+
type: "text",
|
|
213
|
+
});
|
|
214
|
+
if (declaration.required !== true) continue;
|
|
215
|
+
if (row.state !== "staged") {
|
|
216
|
+
return `required artifact ${row.id} is ${row.state}${row.error === null ? "" : `: ${row.error}`}`;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import type { Socket } from "bun";
|
|
2
|
+
import { AgentFlowError } from "./errors";
|
|
3
|
+
import { sleep } from "./json";
|
|
4
|
+
import { JsonLines, JsonLineWriter } from "./jsonl-socket";
|
|
5
|
+
import type { RpcResponse } from "./protocol";
|
|
6
|
+
import type {
|
|
7
|
+
AppendRequest,
|
|
8
|
+
ArtifactOutput,
|
|
9
|
+
Client,
|
|
10
|
+
ClientEventsOptions,
|
|
11
|
+
ClientOptions,
|
|
12
|
+
EngineEvent,
|
|
13
|
+
LimitsSnapshot,
|
|
14
|
+
MessageSnapshot,
|
|
15
|
+
ResumeOptions,
|
|
16
|
+
RunRequest,
|
|
17
|
+
RunSnapshot,
|
|
18
|
+
SendOptions,
|
|
19
|
+
} from "./types";
|
|
20
|
+
|
|
21
|
+
interface PendingCall {
|
|
22
|
+
resolve(value: unknown): void;
|
|
23
|
+
reject(error: unknown): void;
|
|
24
|
+
timer: ReturnType<typeof setTimeout>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface ClientConnection {
|
|
28
|
+
lines: JsonLines;
|
|
29
|
+
writer: JsonLineWriter<ClientConnection>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Local JSON-lines RPC client. Event waits are ordinary cursor polls with an
|
|
34
|
+
* optional abort signal, so a closed caller never changes daemon state.
|
|
35
|
+
*/
|
|
36
|
+
export function createClient(options: ClientOptions): Client {
|
|
37
|
+
return new ClientImpl(options);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
class ClientImpl implements Client {
|
|
41
|
+
private readonly socketPath: string;
|
|
42
|
+
private readonly timeoutMs: number;
|
|
43
|
+
private socket: Socket<ClientConnection> | undefined;
|
|
44
|
+
private connecting: Promise<Socket<ClientConnection>> | undefined;
|
|
45
|
+
private nextId = 1;
|
|
46
|
+
private closed = false;
|
|
47
|
+
private readonly pending = new Map<number, PendingCall>();
|
|
48
|
+
|
|
49
|
+
constructor(options: ClientOptions) {
|
|
50
|
+
if (
|
|
51
|
+
options === null ||
|
|
52
|
+
typeof options !== "object" ||
|
|
53
|
+
typeof options.socketPath !== "string" ||
|
|
54
|
+
options.socketPath === ""
|
|
55
|
+
) {
|
|
56
|
+
throw new AgentFlowError(
|
|
57
|
+
"validation",
|
|
58
|
+
"createClient requires socketPath",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
this.socketPath = options.socketPath;
|
|
62
|
+
this.timeoutMs =
|
|
63
|
+
typeof options.timeoutMs === "number" && options.timeoutMs > 0
|
|
64
|
+
? options.timeoutMs
|
|
65
|
+
: 30_000;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async start(request: RunRequest): Promise<RunSnapshot> {
|
|
69
|
+
return this.call<RunSnapshot>("start", request);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async runs(): Promise<RunSnapshot[]> {
|
|
73
|
+
return this.call<RunSnapshot[]>("runs", {});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async status(id: string): Promise<RunSnapshot> {
|
|
77
|
+
return this.call<RunSnapshot>("status", { id });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async events(
|
|
81
|
+
id: string,
|
|
82
|
+
options: ClientEventsOptions = {},
|
|
83
|
+
): Promise<EngineEvent[]> {
|
|
84
|
+
const waitMs = Math.max(0, options.waitMs ?? 0);
|
|
85
|
+
const pollInterval = Math.max(10, options.pollIntervalMs ?? 50);
|
|
86
|
+
const deadline = Date.now() + waitMs;
|
|
87
|
+
while (true) {
|
|
88
|
+
if (this.closed) throw new AgentFlowError("closed", "client is closed");
|
|
89
|
+
if (options.signal?.aborted) return [];
|
|
90
|
+
const events = await this.call<EngineEvent[]>("events", {
|
|
91
|
+
id,
|
|
92
|
+
...(options.after === undefined ? {} : { after: options.after }),
|
|
93
|
+
...(options.agentId === undefined ? {} : { agentId: options.agentId }),
|
|
94
|
+
});
|
|
95
|
+
if (events.length > 0) return events;
|
|
96
|
+
if (Date.now() >= deadline) return [];
|
|
97
|
+
try {
|
|
98
|
+
await sleep(
|
|
99
|
+
Math.min(pollInterval, Math.max(0, deadline - Date.now())),
|
|
100
|
+
options.signal,
|
|
101
|
+
);
|
|
102
|
+
} catch {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async append(id: string, request: AppendRequest): Promise<RunSnapshot> {
|
|
109
|
+
return this.call<RunSnapshot>("append", {
|
|
110
|
+
id,
|
|
111
|
+
waves: request.waves,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async send(
|
|
116
|
+
id: string,
|
|
117
|
+
agentId: string,
|
|
118
|
+
options: SendOptions,
|
|
119
|
+
): Promise<MessageSnapshot> {
|
|
120
|
+
return this.call<MessageSnapshot>("send", {
|
|
121
|
+
id,
|
|
122
|
+
agentId,
|
|
123
|
+
prompt: options.prompt,
|
|
124
|
+
...(options.delivery === undefined ? {} : { delivery: options.delivery }),
|
|
125
|
+
...(options.fromRun === undefined ? {} : { fromRun: options.fromRun }),
|
|
126
|
+
...(options.messageId === undefined
|
|
127
|
+
? {}
|
|
128
|
+
: { messageId: options.messageId }),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async seal(id: string): Promise<RunSnapshot> {
|
|
133
|
+
return this.call<RunSnapshot>("seal", { id });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async cancel(id: string): Promise<RunSnapshot> {
|
|
137
|
+
return this.call<RunSnapshot>("cancel", { id });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async resume(
|
|
141
|
+
id: string,
|
|
142
|
+
agentId: string,
|
|
143
|
+
options: ResumeOptions = {},
|
|
144
|
+
): Promise<RunSnapshot> {
|
|
145
|
+
return this.call<RunSnapshot>("resume", {
|
|
146
|
+
id,
|
|
147
|
+
agentId,
|
|
148
|
+
...(options.prompt === undefined ? {} : { prompt: options.prompt }),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async limits(): Promise<LimitsSnapshot> {
|
|
153
|
+
return this.call<LimitsSnapshot>("limits", {});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async output(id: string, artifactId: string): Promise<ArtifactOutput> {
|
|
157
|
+
return this.call<ArtifactOutput>("output", { id, artifactId });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async close(): Promise<void> {
|
|
161
|
+
if (this.closed) return;
|
|
162
|
+
this.closed = true;
|
|
163
|
+
this.rejectAll(new AgentFlowError("closed", "client is closed"));
|
|
164
|
+
this.socket?.terminate();
|
|
165
|
+
this.socket = undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private call<T>(action: string, args: unknown): Promise<T> {
|
|
169
|
+
if (this.closed) {
|
|
170
|
+
return Promise.reject(new AgentFlowError("closed", "client is closed"));
|
|
171
|
+
}
|
|
172
|
+
return this.connect().then(
|
|
173
|
+
(socket) =>
|
|
174
|
+
new Promise<T>((resolve, reject) => {
|
|
175
|
+
if (this.closed) {
|
|
176
|
+
reject(new AgentFlowError("closed", "client is closed"));
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const id = this.nextId;
|
|
180
|
+
this.nextId += 1;
|
|
181
|
+
const timer = setTimeout(() => {
|
|
182
|
+
this.pending.delete(id);
|
|
183
|
+
reject(
|
|
184
|
+
new AgentFlowError(
|
|
185
|
+
"ipc",
|
|
186
|
+
`request ${action} timed out after ${this.timeoutMs}ms`,
|
|
187
|
+
),
|
|
188
|
+
);
|
|
189
|
+
}, this.timeoutMs);
|
|
190
|
+
this.pending.set(id, {
|
|
191
|
+
resolve: (value) => resolve(value as T),
|
|
192
|
+
reject,
|
|
193
|
+
timer,
|
|
194
|
+
});
|
|
195
|
+
try {
|
|
196
|
+
if (!socket.data.writer.send({ id, action, args })) {
|
|
197
|
+
throw new AgentFlowError(
|
|
198
|
+
"ipc",
|
|
199
|
+
"could not write request: connection is closed",
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
this.pending.delete(id);
|
|
204
|
+
clearTimeout(timer);
|
|
205
|
+
reject(error);
|
|
206
|
+
}
|
|
207
|
+
}),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private connect(): Promise<Socket<ClientConnection>> {
|
|
212
|
+
if (this.closed) {
|
|
213
|
+
return Promise.reject(new AgentFlowError("closed", "client is closed"));
|
|
214
|
+
}
|
|
215
|
+
if (this.socket !== undefined && this.socket.readyState === 1) {
|
|
216
|
+
return Promise.resolve(this.socket);
|
|
217
|
+
}
|
|
218
|
+
if (this.connecting !== undefined) return this.connecting;
|
|
219
|
+
if (this.socket !== undefined) {
|
|
220
|
+
const stale = this.socket;
|
|
221
|
+
this.disconnected(stale);
|
|
222
|
+
stale.terminate();
|
|
223
|
+
}
|
|
224
|
+
this.connecting = Bun.connect<ClientConnection>({
|
|
225
|
+
unix: this.socketPath,
|
|
226
|
+
socket: {
|
|
227
|
+
open: (socket) => {
|
|
228
|
+
socket.data = {
|
|
229
|
+
lines: new JsonLines(),
|
|
230
|
+
writer: new JsonLineWriter(socket),
|
|
231
|
+
};
|
|
232
|
+
if (this.closed) socket.terminate();
|
|
233
|
+
else this.socket = socket;
|
|
234
|
+
},
|
|
235
|
+
data: (socket, chunk) => {
|
|
236
|
+
if (this.socket !== socket) return;
|
|
237
|
+
socket.data.lines.receive(chunk, (line) => this.handleLine(line));
|
|
238
|
+
},
|
|
239
|
+
drain(socket) {
|
|
240
|
+
if (!socket.data.writer.drain()) socket.terminate();
|
|
241
|
+
},
|
|
242
|
+
connectError() {},
|
|
243
|
+
error(socket) {
|
|
244
|
+
socket.terminate();
|
|
245
|
+
},
|
|
246
|
+
close: (socket) => {
|
|
247
|
+
this.disconnected(socket);
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
})
|
|
251
|
+
.then(
|
|
252
|
+
(socket) => {
|
|
253
|
+
if (this.closed)
|
|
254
|
+
throw new AgentFlowError("closed", "client is closed");
|
|
255
|
+
if (this.socket !== socket) {
|
|
256
|
+
throw new AgentFlowError(
|
|
257
|
+
"ipc",
|
|
258
|
+
"daemon connection closed before reply",
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return socket;
|
|
262
|
+
},
|
|
263
|
+
(error: Error) => {
|
|
264
|
+
throw new AgentFlowError(
|
|
265
|
+
"ipc",
|
|
266
|
+
`could not connect to ${this.socketPath}: ${error.message}`,
|
|
267
|
+
);
|
|
268
|
+
},
|
|
269
|
+
)
|
|
270
|
+
.finally(() => {
|
|
271
|
+
this.connecting = undefined;
|
|
272
|
+
});
|
|
273
|
+
return this.connecting;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private disconnected(socket: Socket<ClientConnection>): void {
|
|
277
|
+
if (this.socket !== socket) return;
|
|
278
|
+
this.socket = undefined;
|
|
279
|
+
this.rejectAll(
|
|
280
|
+
new AgentFlowError("ipc", "daemon connection closed before reply"),
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private handleLine(line: string): void {
|
|
285
|
+
let parsed: RpcResponse;
|
|
286
|
+
try {
|
|
287
|
+
parsed = JSON.parse(line) as RpcResponse;
|
|
288
|
+
} catch {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (parsed === null || typeof parsed.id !== "number") return;
|
|
292
|
+
const call = this.pending.get(parsed.id);
|
|
293
|
+
if (call === undefined) return;
|
|
294
|
+
this.pending.delete(parsed.id);
|
|
295
|
+
clearTimeout(call.timer);
|
|
296
|
+
if (parsed.ok) {
|
|
297
|
+
call.resolve(parsed.result);
|
|
298
|
+
} else {
|
|
299
|
+
call.reject(
|
|
300
|
+
new AgentFlowError(
|
|
301
|
+
parsed.error.code as AgentFlowError["code"],
|
|
302
|
+
parsed.error.message,
|
|
303
|
+
parsed.error.data,
|
|
304
|
+
),
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private rejectAll(error: unknown): void {
|
|
310
|
+
for (const call of this.pending.values()) {
|
|
311
|
+
clearTimeout(call.timer);
|
|
312
|
+
call.reject(error);
|
|
313
|
+
}
|
|
314
|
+
this.pending.clear();
|
|
315
|
+
}
|
|
316
|
+
}
|