@operad-io/harness-process 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/access-user.schema.json +52 -0
- package/package.json +22 -4
- package/src/acp.ts +370 -0
- package/src/always-allow.ts +203 -0
- package/src/ask-call.ts +251 -0
- package/src/ask-note.ts +47 -0
- package/src/event-note.ts +23 -0
- package/src/fold-lines.ts +238 -0
- package/src/grants.ts +53 -0
- package/src/images.ts +43 -0
- package/src/inbox.ts +45 -0
- package/src/index.ts +23 -0
- package/src/jsonl-log.ts +71 -0
- package/src/limit.ts +89 -0
- package/src/lines.ts +138 -0
- package/src/operad-tools.ts +57 -0
- package/src/process.ts +568 -0
- package/src/step.ts +293 -0
- package/src/usage.ts +62 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yinghai Zhao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://operad.io/schemas/access-user.schema.json",
|
|
4
|
+
"title": "operad access user layer",
|
|
5
|
+
"description": "The always-allowed calls in $OPERAD_HOME/access-user.json: each binds an exact command and working directory, or a tool, path and working directory. A person adds them by answering allow_always, and can remove one by deleting its line.",
|
|
6
|
+
"type": "array",
|
|
7
|
+
"items": {
|
|
8
|
+
"oneOf": [
|
|
9
|
+
{
|
|
10
|
+
"type": "object",
|
|
11
|
+
"properties": {
|
|
12
|
+
"kind": { "const": "command" },
|
|
13
|
+
"value": {
|
|
14
|
+
"type": "string",
|
|
15
|
+
"minLength": 1,
|
|
16
|
+
"description": "The command text, exactly as the person allowed it; for an MCP tool, `mcp <server>.<tool>`."
|
|
17
|
+
},
|
|
18
|
+
"cwd": {
|
|
19
|
+
"type": "string",
|
|
20
|
+
"minLength": 1,
|
|
21
|
+
"description": "The working directory the command was allowed in."
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"required": ["kind", "value", "cwd"],
|
|
25
|
+
"additionalProperties": false
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"type": "object",
|
|
29
|
+
"properties": {
|
|
30
|
+
"kind": { "const": "path" },
|
|
31
|
+
"value": {
|
|
32
|
+
"type": "string",
|
|
33
|
+
"minLength": 1,
|
|
34
|
+
"description": "The path, as the call wrote it."
|
|
35
|
+
},
|
|
36
|
+
"cwd": {
|
|
37
|
+
"type": "string",
|
|
38
|
+
"minLength": 1,
|
|
39
|
+
"description": "The working directory the path was allowed in."
|
|
40
|
+
},
|
|
41
|
+
"tool": {
|
|
42
|
+
"type": "string",
|
|
43
|
+
"minLength": 1,
|
|
44
|
+
"description": "The tool the person allowed on that path, such as write or edit."
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"required": ["kind", "value", "cwd", "tool"],
|
|
48
|
+
"additionalProperties": false
|
|
49
|
+
}
|
|
50
|
+
]
|
|
51
|
+
}
|
|
52
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/harness-process",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/engine": "0.0.1",
|
|
10
|
+
"@operad-io/mcp": "0.0.1"
|
|
11
|
+
},
|
|
12
|
+
"description": "operad: the shared process and log helpers of the harness plugins (in development)",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/operad-io/operad.git",
|
|
16
|
+
"directory": "packages/harness/process"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"access-user.schema.json",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
]
|
|
24
|
+
}
|
package/src/acp.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An ACP (Agent Client Protocol) client for the harnesses that talk to their
|
|
3
|
+
* agent over it: JSON-RPC 2.0, one message per line, on the agent's stdio.
|
|
4
|
+
*
|
|
5
|
+
* The client is a state machine, not a process owner. `runAgent` starts the
|
|
6
|
+
* agent in interactive mode and hands each stdout line to `handleLine`; the
|
|
7
|
+
* client answers through the `reply` function `runAgent` gives it. The first
|
|
8
|
+
* line to send (`initialize`) is `first`, which the caller passes as the
|
|
9
|
+
* run's stdin.
|
|
10
|
+
*
|
|
11
|
+
* The run is: `initialize`, then `session/new` (or `session/load` when a
|
|
12
|
+
* session is resumed), then one `session/set_config_option` per setting, then
|
|
13
|
+
* `session/prompt`. The `session/update` stream is handed to `onUpdate` while
|
|
14
|
+
* the prompt runs; what `session/load` replays of an earlier conversation is
|
|
15
|
+
* dropped. `session/request_permission` goes to `onPermission`. `cancel` sends
|
|
16
|
+
* `session/cancel`. `ended` settles once with how the prompt ended.
|
|
17
|
+
*
|
|
18
|
+
* The client keeps no timers: how long a silent agent may be silent is the
|
|
19
|
+
* caller's `stallMs` and `wallMs` of `runAgent`.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { isRecord } from "@operad-io/engine";
|
|
23
|
+
|
|
24
|
+
/** The ACP protocol version this client speaks. */
|
|
25
|
+
export const ACP_PROTOCOL_VERSION = 1;
|
|
26
|
+
|
|
27
|
+
/** The token counts of one prompt, as the agent reports them. */
|
|
28
|
+
export interface AcpUsage {
|
|
29
|
+
readonly totalTokens?: number;
|
|
30
|
+
readonly inputTokens?: number;
|
|
31
|
+
readonly outputTokens?: number;
|
|
32
|
+
readonly cachedReadTokens?: number | null;
|
|
33
|
+
readonly cachedWriteTokens?: number | null;
|
|
34
|
+
readonly thoughtTokens?: number | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** An error response of the agent. */
|
|
38
|
+
export interface AcpError {
|
|
39
|
+
readonly code: number;
|
|
40
|
+
readonly message: string;
|
|
41
|
+
readonly data?: unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The stage of the run an error came from. */
|
|
45
|
+
export type AcpStage = "initialize" | "session" | "config" | "prompt";
|
|
46
|
+
|
|
47
|
+
export type AcpEnd =
|
|
48
|
+
| {
|
|
49
|
+
readonly kind: "stopped";
|
|
50
|
+
/** `end_turn`, `max_tokens`, `max_turn_requests`, `refusal` or `cancelled`. */
|
|
51
|
+
readonly stopReason: string;
|
|
52
|
+
readonly usage: AcpUsage | null;
|
|
53
|
+
/** The `_meta` of the prompt response, as the agent wrote it. */
|
|
54
|
+
readonly meta: Readonly<Record<string, unknown>> | null;
|
|
55
|
+
readonly sessionId: string;
|
|
56
|
+
}
|
|
57
|
+
| {
|
|
58
|
+
readonly kind: "error";
|
|
59
|
+
readonly stage: AcpStage;
|
|
60
|
+
/** The setting a `config` stage error is about. */
|
|
61
|
+
readonly configId?: string;
|
|
62
|
+
readonly error: AcpError;
|
|
63
|
+
readonly sessionId: string | null;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** One permission option the agent offers. */
|
|
67
|
+
export interface AcpPermissionOption {
|
|
68
|
+
readonly optionId: string;
|
|
69
|
+
readonly name: string;
|
|
70
|
+
readonly kind: "allow_once" | "allow_always" | "reject_once" | "reject_always";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A `session/request_permission` request. */
|
|
74
|
+
export interface AcpPermissionRequest {
|
|
75
|
+
readonly sessionId: string;
|
|
76
|
+
/** The tool call as the agent describes it: `toolCallId`, `title`, `kind`, `rawInput`, `locations`. */
|
|
77
|
+
readonly toolCall: Readonly<Record<string, unknown>>;
|
|
78
|
+
readonly options: readonly AcpPermissionOption[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface AcpClientOptions {
|
|
82
|
+
readonly cwd: string;
|
|
83
|
+
/** The prompt as ACP content blocks. */
|
|
84
|
+
readonly prompt: readonly Readonly<Record<string, unknown>>[];
|
|
85
|
+
/** Continue this session; the agent must offer `loadSession`. */
|
|
86
|
+
readonly resumeSession?: string | undefined;
|
|
87
|
+
/** Session settings to apply before the prompt, in order. */
|
|
88
|
+
readonly config?: readonly { readonly configId: string; readonly value: string }[] | undefined;
|
|
89
|
+
/** MCP servers the agent starts, as ACP stdio servers: `{ name, command, args, env }`. */
|
|
90
|
+
readonly mcpServers?: readonly Readonly<Record<string, unknown>>[] | undefined;
|
|
91
|
+
readonly clientName: string;
|
|
92
|
+
readonly clientVersion?: string | undefined;
|
|
93
|
+
/** Each `session/update` of the running prompt, in order. */
|
|
94
|
+
readonly onUpdate: (update: Readonly<Record<string, unknown>>) => void | Promise<void>;
|
|
95
|
+
/** True lets the call run once; false refuses it. */
|
|
96
|
+
readonly onPermission: (request: AcpPermissionRequest) => Promise<boolean>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The option an answer picks, or undefined when the agent offered no option for it. */
|
|
100
|
+
export function permissionOptionFor(
|
|
101
|
+
options: readonly AcpPermissionOption[],
|
|
102
|
+
allow: boolean,
|
|
103
|
+
): AcpPermissionOption | undefined {
|
|
104
|
+
// A call is never allowed for good: only the once-option lets it through.
|
|
105
|
+
const kinds = allow ? ["allow_once"] : ["reject_once", "reject_always"];
|
|
106
|
+
for (const kind of kinds) {
|
|
107
|
+
const found = options.find((option) => option.kind === kind);
|
|
108
|
+
if (found !== undefined) return found;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function permissionOptions(value: unknown): readonly AcpPermissionOption[] {
|
|
114
|
+
if (!Array.isArray(value)) return [];
|
|
115
|
+
const found: AcpPermissionOption[] = [];
|
|
116
|
+
for (const item of value) {
|
|
117
|
+
if (!isRecord(item)) continue;
|
|
118
|
+
const { optionId, name, kind } = item;
|
|
119
|
+
if (
|
|
120
|
+
typeof optionId === "string" &&
|
|
121
|
+
(kind === "allow_once" || kind === "allow_always" || kind === "reject_once" || kind === "reject_always")
|
|
122
|
+
) {
|
|
123
|
+
found.push({ optionId, name: typeof name === "string" ? name : optionId, kind });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return found;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function errorOf(value: unknown): AcpError {
|
|
130
|
+
if (!isRecord(value)) return { code: -32603, message: "the agent sent an error without a body" };
|
|
131
|
+
return {
|
|
132
|
+
code: typeof value.code === "number" ? value.code : -32603,
|
|
133
|
+
message: typeof value.message === "string" ? value.message : "the agent sent an error without a message",
|
|
134
|
+
...(value.data === undefined ? {} : { data: value.data }),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
type Phase = "initialize" | "session" | "config" | "prompt" | "done";
|
|
139
|
+
|
|
140
|
+
export class AcpClient {
|
|
141
|
+
/** The first line the caller sends: the `initialize` request. */
|
|
142
|
+
readonly first: string;
|
|
143
|
+
/** Settles once, when the prompt ended or a stage failed. */
|
|
144
|
+
readonly ended: Promise<AcpEnd>;
|
|
145
|
+
|
|
146
|
+
private readonly options: AcpClientOptions;
|
|
147
|
+
private reply: ((text: string) => void) | undefined;
|
|
148
|
+
private nextId = 1;
|
|
149
|
+
private phase: Phase = "initialize";
|
|
150
|
+
private session: string | null = null;
|
|
151
|
+
private configAt = 0;
|
|
152
|
+
private settle: (end: AcpEnd) => void = () => undefined;
|
|
153
|
+
/** What each request in flight waits for, by id. */
|
|
154
|
+
private readonly pending = new Map<number, AcpStage>();
|
|
155
|
+
private cancelling = false;
|
|
156
|
+
private promptSent = false;
|
|
157
|
+
|
|
158
|
+
constructor(options: AcpClientOptions) {
|
|
159
|
+
this.options = options;
|
|
160
|
+
this.ended = new Promise<AcpEnd>((resolve) => {
|
|
161
|
+
this.settle = resolve;
|
|
162
|
+
});
|
|
163
|
+
this.first = this.request("initialize", {
|
|
164
|
+
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
165
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
166
|
+
clientInfo: {
|
|
167
|
+
name: options.clientName,
|
|
168
|
+
...(options.clientVersion === undefined ? {} : { version: options.clientVersion }),
|
|
169
|
+
},
|
|
170
|
+
}, "initialize");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The session the run uses; null before the agent opened one. */
|
|
174
|
+
get sessionId(): string | null {
|
|
175
|
+
return this.session;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** True while the prompt is in flight, so a cancel reaches the agent. */
|
|
179
|
+
get prompting(): boolean {
|
|
180
|
+
return this.phase === "prompt" && this.promptSent;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Whether the run ended (the prompt answered, or a stage failed). */
|
|
184
|
+
get finished(): boolean {
|
|
185
|
+
return this.phase === "done";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private request(method: string, params: Record<string, unknown>, stage: AcpStage): string {
|
|
189
|
+
const id = this.nextId;
|
|
190
|
+
this.nextId += 1;
|
|
191
|
+
this.pending.set(id, stage);
|
|
192
|
+
return JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private send(line: string): void {
|
|
196
|
+
this.reply?.(line);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private end(end: AcpEnd): void {
|
|
200
|
+
if (this.phase === "done") return;
|
|
201
|
+
this.phase = "done";
|
|
202
|
+
this.settle(end);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private fail(stage: AcpStage, error: AcpError): void {
|
|
206
|
+
const configId = stage === "config" ? this.options.config?.[this.configAt - 1]?.configId : undefined;
|
|
207
|
+
this.end({
|
|
208
|
+
kind: "error",
|
|
209
|
+
stage,
|
|
210
|
+
...(configId === undefined ? {} : { configId }),
|
|
211
|
+
error,
|
|
212
|
+
sessionId: this.session,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Sends `session/cancel` for the running prompt. The agent answers the
|
|
218
|
+
* prompt with the stop reason `cancelled`, which `ended` reports. False when
|
|
219
|
+
* no prompt is in flight, so there is nothing to cancel.
|
|
220
|
+
*/
|
|
221
|
+
cancel(): boolean {
|
|
222
|
+
if (!this.prompting || this.session === null || this.cancelling) return false;
|
|
223
|
+
this.cancelling = true;
|
|
224
|
+
this.send(JSON.stringify({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.session } }));
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Takes one line of the agent's stdout. */
|
|
229
|
+
handleLine(line: string, reply: (text: string) => void): void {
|
|
230
|
+
this.reply = reply;
|
|
231
|
+
let message: unknown;
|
|
232
|
+
try {
|
|
233
|
+
message = JSON.parse(line);
|
|
234
|
+
} catch {
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (!isRecord(message)) return;
|
|
238
|
+
const { id, method } = message;
|
|
239
|
+
if (typeof method === "string") {
|
|
240
|
+
if (typeof id === "number" || typeof id === "string") this.handleRequest(id, method, message.params);
|
|
241
|
+
else this.handleNotification(method, message.params);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (typeof id === "number") this.handleResponse(id, message);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private handleNotification(method: string, params: unknown): void {
|
|
248
|
+
if (method !== "session/update" || !isRecord(params)) return;
|
|
249
|
+
// Until the prompt is sent, an update is what `session/load` replays.
|
|
250
|
+
if (this.phase !== "prompt" || !this.promptSent) return;
|
|
251
|
+
const update = params.update;
|
|
252
|
+
if (isRecord(update)) void this.options.onUpdate(update);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private handleRequest(id: number | string, method: string, params: unknown): void {
|
|
256
|
+
const answer = (body: Record<string, unknown>): void => {
|
|
257
|
+
this.send(JSON.stringify({ jsonrpc: "2.0", id, ...body }));
|
|
258
|
+
};
|
|
259
|
+
if (method !== "session/request_permission" || !isRecord(params) || !isRecord(params.toolCall)) {
|
|
260
|
+
answer({ error: { code: -32601, message: `method not supported: ${method}` } });
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const request: AcpPermissionRequest = {
|
|
264
|
+
sessionId: typeof params.sessionId === "string" ? params.sessionId : (this.session ?? ""),
|
|
265
|
+
toolCall: params.toolCall,
|
|
266
|
+
options: permissionOptions(params.options),
|
|
267
|
+
};
|
|
268
|
+
// The reader does not wait: a person may take long to answer, and the
|
|
269
|
+
// agent's other lines (the answer to a cancel) must still be read.
|
|
270
|
+
void (async () => {
|
|
271
|
+
let allow = false;
|
|
272
|
+
if (!this.cancelling) {
|
|
273
|
+
try {
|
|
274
|
+
allow = await this.options.onPermission(request);
|
|
275
|
+
} catch {
|
|
276
|
+
allow = false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const option = permissionOptionFor(request.options, allow);
|
|
280
|
+
answer({
|
|
281
|
+
result: {
|
|
282
|
+
outcome: option === undefined ? { outcome: "cancelled" } : { outcome: "selected", optionId: option.optionId },
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
})();
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private handleResponse(id: number, message: Record<string, unknown>): void {
|
|
289
|
+
const stage = this.pending.get(id);
|
|
290
|
+
if (stage === undefined) return;
|
|
291
|
+
this.pending.delete(id);
|
|
292
|
+
if (isRecord(message.error)) {
|
|
293
|
+
this.fail(stage, errorOf(message.error));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const result = isRecord(message.result) ? message.result : {};
|
|
297
|
+
switch (stage) {
|
|
298
|
+
case "initialize": {
|
|
299
|
+
const capabilities = isRecord(result.agentCapabilities) ? result.agentCapabilities : {};
|
|
300
|
+
const resume = this.options.resumeSession;
|
|
301
|
+
if (resume !== undefined) {
|
|
302
|
+
if (capabilities.loadSession !== true) {
|
|
303
|
+
this.fail("session", {
|
|
304
|
+
code: -32601,
|
|
305
|
+
message: "the agent cannot resume a session (it does not offer session/load)",
|
|
306
|
+
});
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
this.phase = "session";
|
|
310
|
+
this.send(
|
|
311
|
+
this.request("session/load", { sessionId: resume, cwd: this.options.cwd, mcpServers: this.options.mcpServers ?? [] }, "session"),
|
|
312
|
+
);
|
|
313
|
+
this.session = resume;
|
|
314
|
+
} else {
|
|
315
|
+
this.phase = "session";
|
|
316
|
+
this.send(this.request("session/new", { cwd: this.options.cwd, mcpServers: this.options.mcpServers ?? [] }, "session"));
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
case "session": {
|
|
321
|
+
if (this.options.resumeSession === undefined) {
|
|
322
|
+
const sessionId = result.sessionId;
|
|
323
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
324
|
+
this.fail("session", { code: -32603, message: "the agent opened a session without an id" });
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
this.session = sessionId;
|
|
328
|
+
}
|
|
329
|
+
this.phase = "config";
|
|
330
|
+
this.nextStage();
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
case "config":
|
|
334
|
+
this.nextStage();
|
|
335
|
+
return;
|
|
336
|
+
case "prompt": {
|
|
337
|
+
const stopReason = typeof result.stopReason === "string" ? result.stopReason : "end_turn";
|
|
338
|
+
this.end({
|
|
339
|
+
kind: "stopped",
|
|
340
|
+
stopReason,
|
|
341
|
+
usage: isRecord(result.usage) ? (result.usage as AcpUsage) : null,
|
|
342
|
+
meta: isRecord(result._meta) ? result._meta : null,
|
|
343
|
+
sessionId: this.session ?? "",
|
|
344
|
+
});
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Sends the next setting, or the prompt when the settings are all applied. */
|
|
351
|
+
private nextStage(): void {
|
|
352
|
+
const session = this.session;
|
|
353
|
+
if (session === null) return;
|
|
354
|
+
const setting = this.options.config?.[this.configAt];
|
|
355
|
+
if (setting !== undefined) {
|
|
356
|
+
this.configAt += 1;
|
|
357
|
+
this.send(
|
|
358
|
+
this.request(
|
|
359
|
+
"session/set_config_option",
|
|
360
|
+
{ sessionId: session, configId: setting.configId, value: setting.value },
|
|
361
|
+
"config",
|
|
362
|
+
),
|
|
363
|
+
);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
this.phase = "prompt";
|
|
367
|
+
this.promptSent = true;
|
|
368
|
+
this.send(this.request("session/prompt", { sessionId: session, prompt: this.options.prompt }, "prompt"));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The access profile's user layer: the calls a person answered `allow_always`
|
|
3
|
+
* for, in `$OPERAD_HOME/access-user.json` (`operad-sandbox.md` decisions 4, 5,
|
|
4
|
+
* 8 and 11). A missing file is an empty list. A file that cannot be read is
|
|
5
|
+
* reported by the step that reads it and treated as empty. Writes take the
|
|
6
|
+
* platform file lock and replace the file atomically.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { isRecord } from "@operad-io/engine";
|
|
13
|
+
import { withLockFile } from "@operad-io/engine/platform";
|
|
14
|
+
|
|
15
|
+
/** The file name of the user layer under the operad home. */
|
|
16
|
+
export const ACCESS_USER_FILE = "access-user.json";
|
|
17
|
+
|
|
18
|
+
/** One call a person allowed always: its kind, exact value and working directory. */
|
|
19
|
+
export interface AlwaysAllowEntry {
|
|
20
|
+
readonly kind: "command" | "path";
|
|
21
|
+
/** The exact command text, or the path as the call wrote it. */
|
|
22
|
+
readonly value: string;
|
|
23
|
+
/** The working directory the person allowed it in. */
|
|
24
|
+
readonly cwd: string;
|
|
25
|
+
/** The tool a path entry names; absent for a command entry. */
|
|
26
|
+
readonly tool?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What one asked call carries into an `alwaysAllow` entry. */
|
|
30
|
+
export interface AskedCall {
|
|
31
|
+
readonly kind: "command" | "path";
|
|
32
|
+
readonly value: string;
|
|
33
|
+
readonly tool?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The file of the user layer in an operad home. */
|
|
37
|
+
export function accessUserPath(home: string): string {
|
|
38
|
+
return join(home, ACCESS_USER_FILE);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The entry an answered call writes; its working directory is the step's `cwd`. */
|
|
42
|
+
export function alwaysAllowEntry(call: AskedCall, cwd: string): AlwaysAllowEntry {
|
|
43
|
+
return {
|
|
44
|
+
kind: call.kind,
|
|
45
|
+
value: call.value,
|
|
46
|
+
cwd,
|
|
47
|
+
...(call.kind === "path" && call.tool !== undefined ? { tool: call.tool } : {}),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function messageOf(error: unknown): string {
|
|
52
|
+
return error instanceof Error ? error.message : String(error);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isMissing(error: unknown): boolean {
|
|
56
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function entryOf(value: unknown): AlwaysAllowEntry | undefined {
|
|
60
|
+
if (!isRecord(value)) return undefined;
|
|
61
|
+
const kind = value["kind"];
|
|
62
|
+
const text = value["value"];
|
|
63
|
+
const cwd = value["cwd"];
|
|
64
|
+
const tool = value["tool"];
|
|
65
|
+
if ((kind !== "command" && kind !== "path") || typeof text !== "string" || text.length === 0) return undefined;
|
|
66
|
+
if (typeof cwd !== "string" || cwd.length === 0) return undefined;
|
|
67
|
+
if (kind === "path") {
|
|
68
|
+
if (typeof tool !== "string" || tool.length === 0) return undefined;
|
|
69
|
+
return { kind, value: text, cwd, tool };
|
|
70
|
+
}
|
|
71
|
+
if (tool !== undefined) return undefined;
|
|
72
|
+
return { kind, value: text, cwd };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function entriesOf(value: unknown): AlwaysAllowEntry[] {
|
|
76
|
+
if (!Array.isArray(value)) return [];
|
|
77
|
+
return value.map(entryOf).filter((entry): entry is AlwaysAllowEntry => entry !== undefined);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function sameEntry(left: AlwaysAllowEntry, right: AlwaysAllowEntry): boolean {
|
|
81
|
+
return left.kind === right.kind && left.value === right.value && left.cwd === right.cwd && left.tool === right.tool;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The user layer's entries, and a readable problem when the file had to be treated as empty. */
|
|
85
|
+
export interface AlwaysAllowRead {
|
|
86
|
+
readonly entries: readonly AlwaysAllowEntry[];
|
|
87
|
+
readonly problem?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function invalid(path: string, detail: string): AlwaysAllowRead {
|
|
91
|
+
return { entries: [], problem: `the user access file "${path}" ${detail}; it is treated as empty` };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Reads the user layer; a missing file is an empty list and an invalid one is empty with a problem. */
|
|
95
|
+
export async function readAlwaysAllow(home: string): Promise<AlwaysAllowRead> {
|
|
96
|
+
const path = accessUserPath(home);
|
|
97
|
+
let text: string;
|
|
98
|
+
try {
|
|
99
|
+
text = await readFile(path, "utf8");
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (isMissing(error)) return { entries: [] };
|
|
102
|
+
return invalid(path, `cannot be read: ${messageOf(error)}`);
|
|
103
|
+
}
|
|
104
|
+
let raw: unknown;
|
|
105
|
+
try {
|
|
106
|
+
raw = JSON.parse(text);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return invalid(path, `is not valid JSON: ${messageOf(error)}`);
|
|
109
|
+
}
|
|
110
|
+
if (!Array.isArray(raw)) return invalid(path, "must be a JSON array of always-allowed entries");
|
|
111
|
+
const entries: AlwaysAllowEntry[] = [];
|
|
112
|
+
for (let index = 0; index < raw.length; index += 1) {
|
|
113
|
+
const entry = entryOf(raw[index]);
|
|
114
|
+
if (entry === undefined) return invalid(path, `entry ${index} is not a command or path entry with a value and a working directory`);
|
|
115
|
+
entries.push(entry);
|
|
116
|
+
}
|
|
117
|
+
return { entries };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Appends one entry, under the file lock and with an atomic replace. */
|
|
121
|
+
export async function appendAlwaysAllow(home: string, entry: AlwaysAllowEntry): Promise<void> {
|
|
122
|
+
const path = accessUserPath(home);
|
|
123
|
+
await withLockFile(`${path}.lock`, async () => {
|
|
124
|
+
const found = await readAlwaysAllow(home);
|
|
125
|
+
const entries = [...found.entries.filter((existing) => !sameEntry(existing, entry)), entry];
|
|
126
|
+
await mkdir(home, { recursive: true });
|
|
127
|
+
const temporary = join(home, `.${ACCESS_USER_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
128
|
+
try {
|
|
129
|
+
await writeFile(temporary, `${JSON.stringify(entries, null, 2)}\n`, { mode: 0o600 });
|
|
130
|
+
await rename(temporary, path);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
try {
|
|
133
|
+
await unlink(temporary);
|
|
134
|
+
} catch {
|
|
135
|
+
// The temporary file was never made, or is already gone.
|
|
136
|
+
}
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
}, { label: "access user layer" });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A late `allow_always` carries the call in the one-time grant the kernel hands
|
|
144
|
+
* back, since `askAnswer` itself names only the prompt and the choice.
|
|
145
|
+
*/
|
|
146
|
+
export function alwaysAllowFromGrant(access: unknown, cwd: string): AlwaysAllowEntry | undefined {
|
|
147
|
+
if (!isRecord(access) || !Array.isArray(access["grants"])) return undefined;
|
|
148
|
+
const grant = access["grants"].find(isRecord);
|
|
149
|
+
if (grant === undefined) return undefined;
|
|
150
|
+
const kind = grant["kind"];
|
|
151
|
+
const value = grant["value"];
|
|
152
|
+
const tool = grant["tool"];
|
|
153
|
+
if ((kind !== "command" && kind !== "path") || typeof value !== "string" || value.length === 0) return undefined;
|
|
154
|
+
if (kind === "path" && (typeof tool !== "string" || tool.length === 0)) return undefined;
|
|
155
|
+
return alwaysAllowEntry(
|
|
156
|
+
{
|
|
157
|
+
kind,
|
|
158
|
+
value,
|
|
159
|
+
...(typeof tool === "string" ? { tool } : {}),
|
|
160
|
+
},
|
|
161
|
+
cwd,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The profile a step passes on: its own entries plus the user layer, or no
|
|
167
|
+
* entries at all in a run no person's message started (`operad-sandbox.md`
|
|
168
|
+
* decision 8).
|
|
169
|
+
*/
|
|
170
|
+
export function accessWithAlwaysAllow(
|
|
171
|
+
access: unknown,
|
|
172
|
+
entries: readonly AlwaysAllowEntry[],
|
|
173
|
+
enabled: boolean,
|
|
174
|
+
): Record<string, unknown> | undefined {
|
|
175
|
+
const base = isRecord(access) ? access : undefined;
|
|
176
|
+
if (!enabled) {
|
|
177
|
+
if (base === undefined || base["alwaysAllow"] === undefined) return base;
|
|
178
|
+
return { ...base, alwaysAllow: [] };
|
|
179
|
+
}
|
|
180
|
+
const combined = [...entriesOf(base?.["alwaysAllow"]), ...entries];
|
|
181
|
+
if (combined.length === 0) return base;
|
|
182
|
+
return { ...(base ?? {}), alwaysAllow: combined };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The sources `chat:send` uses for a message a person wrote in a chat. */
|
|
186
|
+
const MESSAGE_SOURCES = new Set(["ios", "telegram", "cli", "tui", "other"]);
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether a run may see `allow_always`: no trigger is a person's command, and
|
|
190
|
+
* a message event from one of the chat's own client sources is a person's
|
|
191
|
+
* message in that conversation. Every other event (a schedule, a webhook, an
|
|
192
|
+
* incoming message from another source, a run's own event) is a background run
|
|
193
|
+
* (`operad-sandbox.md` decision 8).
|
|
194
|
+
*/
|
|
195
|
+
export function personStarted(trigger: unknown): boolean {
|
|
196
|
+
if (trigger === undefined || trigger === null) return true;
|
|
197
|
+
return (
|
|
198
|
+
isRecord(trigger) &&
|
|
199
|
+
trigger["type"] === "message" &&
|
|
200
|
+
typeof trigger["source"] === "string" &&
|
|
201
|
+
MESSAGE_SOURCES.has(trigger["source"])
|
|
202
|
+
);
|
|
203
|
+
}
|