pi-pocket 0.29.0 → 0.30.0-beta.2
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 +58 -1
- package/SECURITY.md +1 -0
- package/docs/architecture.md +9 -4
- package/docs/desktop-app.md +54 -0
- package/docs/examples/approval-monitor.ts +82 -0
- package/docs/extensions/people-values.md +8 -0
- package/docs/extensions/policies/api-stability.md +1 -0
- package/docs/extensions/reference/api-versions.md +3 -0
- package/docs/extensions/reference/host.md +92 -1
- package/docs/extensions/tools.md +1 -0
- package/docs/features.md +4 -4
- package/docs/index.md +3 -0
- package/docs/macos.md +90 -0
- package/docs/map.md +9 -5
- package/docs/windows.md +73 -0
- package/npm-shrinkwrap.json +71 -67
- package/package.json +9 -9
- package/src/launcher/desktop.ts +45 -0
- package/src/launcher/main.ts +81 -17
- package/src/launcher/options.ts +59 -2
- package/src/server/alerts.ts +2 -2
- package/src/server/app.ts +2 -0
- package/src/server/auth.ts +40 -0
- package/src/server/background.ts +109 -241
- package/src/server/commands.ts +28 -17
- package/src/server/design/scan-fig-container.ts +3 -2
- package/src/server/design/scan-files.ts +3 -11
- package/src/server/design/system.ts +3 -4
- package/src/server/design/tokens-io.ts +2 -3
- package/src/server/docs.ts +9 -0
- package/src/server/errors.ts +12 -0
- package/src/server/extension-document-compat.ts +4 -0
- package/src/server/extensions/artifacts.ts +2 -6
- package/src/server/extensions/codemode.ts +27 -1
- package/src/server/extensions/guard.ts +9 -1
- package/src/server/extensions/pocket-relay/files.ts +10 -3
- package/src/server/extensions/pocket-relay/runtime.ts +6 -0
- package/src/server/extensions/pocket-relay.ts +31 -3
- package/src/server/extensions/schedules.ts +9 -2
- package/src/server/host.ts +25 -0
- package/src/server/http/api.ts +21 -4
- package/src/server/http/browser-routes.ts +5 -2
- package/src/server/http/conversation-routes.ts +4 -3
- package/src/server/http/events.ts +9 -4
- package/src/server/http/io.ts +5 -2
- package/src/server/http/sign-in.ts +9 -3
- package/src/server/limit-gate.ts +257 -65
- package/src/server/limits.ts +80 -4
- package/src/server/main.ts +71 -16
- package/src/server/no-follow.ts +67 -0
- package/src/server/pending-approvals.ts +174 -0
- package/src/server/processes.ts +1480 -0
- package/src/server/projection.ts +7 -6
- package/src/server/room.ts +2 -0
- package/src/server/schedules.ts +226 -4
- package/src/server/secrets.ts +6 -4
- package/src/server/socket-path.ts +167 -0
- package/src/server/themes.ts +2 -4
- package/src/server/worktrees.ts +16 -17
- package/types/pocket.d.ts +74 -0
- package/web/agent-now.js +2 -2
- package/web/notify.js +1 -5
- package/web/peeks.js +1 -1
- package/web/sessions.js +2 -3
- package/web/sheets/schedules.js +18 -0
- package/web/store.js +126 -13
- package/web/transcript.js +4 -30
package/src/server/limits.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Provider limits, read from a failed model request: is this a limit a run can wait out, and when does it clear?
|
|
3
|
-
* `classify` takes what a failed request left (its error text, and
|
|
4
|
-
*
|
|
3
|
+
* `classify` takes what a failed request left (its error text, and facts the request's `fetch` saw) and gives one
|
|
4
|
+
* verdict. Nothing here waits, stores, or sends: `limit-gate.ts` does that.
|
|
5
5
|
*
|
|
6
6
|
* What each provider sends is listed in docs/design/rate-limit-wait.md. Only the error text is certain to reach this
|
|
7
7
|
* code; headers come from the recording fetch (`recordResponses`) for the adapters that take one.
|
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
const KEPT_HEADER =
|
|
12
12
|
/^(retry-after(-ms)?|anthropic-ratelimit-.+|x-ratelimit-.+|x-codex-.+|x-should-retry)$/;
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
type ErrorHint = "request" | "restart" | "overload";
|
|
15
|
+
|
|
16
|
+
/** Status, limit headers, and a hint from an error body. The body itself is not kept. */
|
|
17
|
+
export type ResponseFacts = { status: number; headers: Record<string, string>; hint?: ErrorHint };
|
|
16
18
|
|
|
17
19
|
/** The facts of a response: its status and the limit headers. Anything else is dropped here. */
|
|
18
20
|
export function responseFacts(
|
|
@@ -44,6 +46,8 @@ export type Source = "header" | "body" | "text";
|
|
|
44
46
|
export type Classified =
|
|
45
47
|
/** Not a limit, or one that waiting does not clear (a sign-in, billing, a bad request): the error goes on as it is. */
|
|
46
48
|
| { type: "other"; why: string }
|
|
49
|
+
/** Only this request's conversation could not continue. The account and model must not wait. */
|
|
50
|
+
| { type: "request" }
|
|
47
51
|
/** A limit. `resetAt` (epoch ms) when its end is known; otherwise `backoff`: only trying again tells. */
|
|
48
52
|
| {
|
|
49
53
|
type: "limit";
|
|
@@ -101,6 +105,63 @@ const TRANSIENT =
|
|
|
101
105
|
|
|
102
106
|
const TRANSIENT_STATUS = new Set([429, 500, 502, 503, 504, 520, 524, 529]);
|
|
103
107
|
|
|
108
|
+
const STATUS_PREFIX = /^\s*(?:HTTP\s+)?([45]\d\d)(?=[:\s]|$)[:\s]*/i;
|
|
109
|
+
const CONVERSATION_CODE =
|
|
110
|
+
/^(?:(?:invalid|unknown|missing|expired)_(?:previous_response|conversation)(?:_id)?|(?:previous_response|conversation)(?:_(?:id|owner(?:_account)?))?_(?:invalid|missing|expired|not_found|unavailable))$/i;
|
|
111
|
+
const CONVERSATION_TEXT =
|
|
112
|
+
/\b(?:(?:invalid|unknown|missing|expired|no such) (?:previous response|conversation)|(?:previous response|conversation)(?: id| owner(?: account)?)? (?:is )?(?:unavailable|invalid|missing|expired|not found|does not exist))\b/i;
|
|
113
|
+
const RESTART = /\b(?:server|service) (?:is )?(?:draining|restarting)\b/i;
|
|
114
|
+
const OVERLOAD =
|
|
115
|
+
/\boverloaded(?:_error)?\b|server[ _-]busy|servers are currently busy|high demand|at capacity/i;
|
|
116
|
+
|
|
117
|
+
/** Some adapters put the HTTP status at the start of the error, but do not take a recording fetch. */
|
|
118
|
+
export function messageStatus(message: string): number | undefined {
|
|
119
|
+
const match = STATUS_PREFIX.exec(message);
|
|
120
|
+
|
|
121
|
+
return match === null ? undefined : Number(match[1]);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Read known error shapes, not arbitrary mentions of a conversation in the provider's text. */
|
|
125
|
+
export function serverErrorHint(status: number | undefined, text: string): ErrorHint | undefined {
|
|
126
|
+
const body = text.replace(STATUS_PREFIX, "").trim();
|
|
127
|
+
let message = body;
|
|
128
|
+
let codes: string[] = [];
|
|
129
|
+
|
|
130
|
+
if (body.startsWith("{")) {
|
|
131
|
+
type Detail = { code?: unknown; type?: unknown; param?: unknown; message?: unknown };
|
|
132
|
+
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(body) as Detail & { error?: Detail };
|
|
135
|
+
const error = parsed.error ?? parsed;
|
|
136
|
+
|
|
137
|
+
codes = [error.code, error.type].filter((value) => typeof value === "string");
|
|
138
|
+
message = typeof error.message === "string" ? error.message : "";
|
|
139
|
+
|
|
140
|
+
if (
|
|
141
|
+
!codes.some((code) => OVERLOAD.test(code)) &&
|
|
142
|
+
(codes.some((code) => CONVERSATION_CODE.test(code)) ||
|
|
143
|
+
(codes.includes("invalid_request_error") &&
|
|
144
|
+
(error.param === "previous_response_id" ||
|
|
145
|
+
error.param === "conversation_id")))
|
|
146
|
+
) {
|
|
147
|
+
return "request";
|
|
148
|
+
}
|
|
149
|
+
} catch {
|
|
150
|
+
// The SDK may have cut a long body short. Its ordinary error text can still say what happened.
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (status === 503 && RESTART.test(message)) {
|
|
155
|
+
return "restart";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (OVERLOAD.test(message) || codes.some((code) => OVERLOAD.test(code))) {
|
|
159
|
+
return "overload";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return CONVERSATION_TEXT.test(message) ? "request" : undefined;
|
|
163
|
+
}
|
|
164
|
+
|
|
104
165
|
/**
|
|
105
166
|
* The usage limits that providers send as a 429, or as a 403 with a reset time: only these shapes (not any "usage
|
|
106
167
|
* limit" in a text) let a 403 wait.
|
|
@@ -405,6 +466,21 @@ export function classify(input: LimitInput): Classified {
|
|
|
405
466
|
return { type: "other", why: `HTTP ${status}` };
|
|
406
467
|
}
|
|
407
468
|
|
|
469
|
+
// A gateway can send a continuation error as a 5xx. Keep it out of shared gates, even with Retry-After.
|
|
470
|
+
// A real 429 or 529 still limits other requests. An ordinary 4xx follows the no-wait rules above and below.
|
|
471
|
+
const reported = status ?? messageStatus(message);
|
|
472
|
+
|
|
473
|
+
if (
|
|
474
|
+
reported !== undefined &&
|
|
475
|
+
reported >= 500 &&
|
|
476
|
+
reported < 600 &&
|
|
477
|
+
reported !== 529 &&
|
|
478
|
+
statusWaits(reported) &&
|
|
479
|
+
(facts?.hint ?? serverErrorHint(reported, message)) === "request"
|
|
480
|
+
) {
|
|
481
|
+
return { type: "request" };
|
|
482
|
+
}
|
|
483
|
+
|
|
408
484
|
if ((SIGN_IN.test(message) && !(status === 403 && usageShape)) || status === 401) {
|
|
409
485
|
return { type: "other", why: "sign-in or permission" };
|
|
410
486
|
}
|
package/src/server/main.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Pi Pocket server. Run it through `bin/pi-pocket.js`, which restarts it when the app asks to (exit code 75).
|
|
4
4
|
*
|
|
5
|
-
* node bin/pi-pocket.js [--host 127.0.0.1] [--port 8787] [--cwd DIR] [--data DIR] [--rotate-token]
|
|
5
|
+
* node bin/pi-pocket.js [--host 127.0.0.1] [--port 8787 | --socket PATH] [--cwd DIR] [--data DIR] [--rotate-token]
|
|
6
6
|
*
|
|
7
7
|
* Under the launcher (PI_POCKET_LAUNCHER=1 with an IPC channel) the server reports `ready` instead of printing its
|
|
8
8
|
* sign-in links, and takes `access` messages that say how other devices reach it (a tunnel's public URL).
|
|
@@ -15,6 +15,13 @@ import { join, resolve } from "node:path";
|
|
|
15
15
|
import type { AccessInfo, PocketApp } from "./app.ts";
|
|
16
16
|
import { APP_ROOT, dataDir } from "./config.ts";
|
|
17
17
|
import type { createHandler } from "./http.ts";
|
|
18
|
+
import {
|
|
19
|
+
claimSocket,
|
|
20
|
+
parseSocketPath,
|
|
21
|
+
prepareSocketPath,
|
|
22
|
+
socketArgument,
|
|
23
|
+
SocketPathError,
|
|
24
|
+
} from "./socket-path.ts";
|
|
18
25
|
import { restoreMissingNpmPackage } from "./update-state.ts";
|
|
19
26
|
|
|
20
27
|
// A resident process can reach recovery even when a stopped package switch left no live folder.
|
|
@@ -32,11 +39,13 @@ function parseArgs(argv: string[]) {
|
|
|
32
39
|
const options = {
|
|
33
40
|
host: process.env.PI_POCKET_HOST ?? "127.0.0.1",
|
|
34
41
|
port: Number(process.env.PI_POCKET_PORT ?? 8787),
|
|
42
|
+
socket: process.env.PI_POCKET_SOCKET as string | undefined,
|
|
35
43
|
cwd: process.cwd(),
|
|
36
44
|
data: dataDir(),
|
|
37
45
|
rotateToken: false,
|
|
38
46
|
keepAliveSeconds: Number(process.env.PI_POCKET_KEEPALIVE_SECONDS?.trim() || 5),
|
|
39
47
|
};
|
|
48
|
+
let tcpFlag: string | undefined;
|
|
40
49
|
|
|
41
50
|
for (let index = 0; index < argv.length; index++) {
|
|
42
51
|
const arg = argv[index]!;
|
|
@@ -53,8 +62,12 @@ function parseArgs(argv: string[]) {
|
|
|
53
62
|
|
|
54
63
|
if (arg === "--host") {
|
|
55
64
|
options.host = value();
|
|
65
|
+
tcpFlag = arg;
|
|
56
66
|
} else if (arg === "--port" || arg === "-p") {
|
|
57
67
|
options.port = Number(value());
|
|
68
|
+
tcpFlag = arg;
|
|
69
|
+
} else if (arg === "--socket") {
|
|
70
|
+
options.socket = socketArgument(value());
|
|
58
71
|
} else if (arg === "--cwd") {
|
|
59
72
|
options.cwd = resolve(value());
|
|
60
73
|
} else if (arg === "--data") {
|
|
@@ -63,7 +76,7 @@ function parseArgs(argv: string[]) {
|
|
|
63
76
|
options.rotateToken = true;
|
|
64
77
|
} else if (arg === "--help" || arg === "-h") {
|
|
65
78
|
console.log(
|
|
66
|
-
"pi-pocket [--host 127.0.0.1] [--port 8787] [--cwd DIR] [--data DIR] [--rotate-token]",
|
|
79
|
+
"pi-pocket [--host 127.0.0.1] [--port 8787 | --socket PATH] [--cwd DIR] [--data DIR] [--rotate-token]",
|
|
67
80
|
);
|
|
68
81
|
process.exit(0);
|
|
69
82
|
} else {
|
|
@@ -71,10 +84,6 @@ function parseArgs(argv: string[]) {
|
|
|
71
84
|
}
|
|
72
85
|
}
|
|
73
86
|
|
|
74
|
-
if (!Number.isInteger(options.port) || options.port <= 0) {
|
|
75
|
-
throw new Error("--port must be a number");
|
|
76
|
-
}
|
|
77
|
-
|
|
78
87
|
if (
|
|
79
88
|
!Number.isInteger(options.keepAliveSeconds) ||
|
|
80
89
|
options.keepAliveSeconds < 1 ||
|
|
@@ -85,6 +94,16 @@ function parseArgs(argv: string[]) {
|
|
|
85
94
|
);
|
|
86
95
|
}
|
|
87
96
|
|
|
97
|
+
options.socket = parseSocketPath(options.socket);
|
|
98
|
+
|
|
99
|
+
if (options.socket !== undefined && tcpFlag !== undefined) {
|
|
100
|
+
throw new Error(`--socket cannot be combined with ${tcpFlag}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (options.socket === undefined && (!Number.isInteger(options.port) || options.port <= 0)) {
|
|
104
|
+
throw new Error("--port must be a number");
|
|
105
|
+
}
|
|
106
|
+
|
|
88
107
|
return options;
|
|
89
108
|
}
|
|
90
109
|
|
|
@@ -120,6 +139,7 @@ const stop = async (code: number) => {
|
|
|
120
139
|
|
|
121
140
|
stopping = true;
|
|
122
141
|
stopWatching();
|
|
142
|
+
// Closing also removes the socket file (`--socket`): Node unlinks the path it listened on.
|
|
123
143
|
server.close();
|
|
124
144
|
server.closeAllConnections();
|
|
125
145
|
|
|
@@ -179,23 +199,45 @@ server.headersTimeout = 60_000;
|
|
|
179
199
|
// The timeouts above count from a request's first byte, not from the idle time before it.
|
|
180
200
|
server.keepAliveTimeout = options.keepAliveSeconds * 1000;
|
|
181
201
|
|
|
182
|
-
// Take the port before opening the database: opening resumes interrupted work, which must not start in
|
|
183
|
-
// that then exits because it cannot serve.
|
|
202
|
+
// Take the port (or the socket) before opening the database: opening resumes interrupted work, which must not start in
|
|
203
|
+
// a process that then exits because it cannot serve.
|
|
184
204
|
try {
|
|
205
|
+
if (options.socket !== undefined) {
|
|
206
|
+
await prepareSocketPath(options.socket);
|
|
207
|
+
}
|
|
208
|
+
|
|
185
209
|
await new Promise<void>((resolve, reject) => {
|
|
186
210
|
server.once("error", reject);
|
|
187
|
-
|
|
211
|
+
|
|
212
|
+
const listening = () => {
|
|
188
213
|
server.off("error", reject);
|
|
189
214
|
resolve();
|
|
190
|
-
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
if (options.socket === undefined) {
|
|
218
|
+
server.listen(options.port, options.host, listening);
|
|
219
|
+
} else {
|
|
220
|
+
server.listen(options.socket, listening);
|
|
221
|
+
}
|
|
191
222
|
});
|
|
223
|
+
|
|
224
|
+
if (options.socket !== undefined) {
|
|
225
|
+
claimSocket(options.socket);
|
|
226
|
+
}
|
|
192
227
|
} catch (error) {
|
|
193
228
|
const code = (error as NodeJS.ErrnoException).code;
|
|
194
229
|
|
|
230
|
+
server.close();
|
|
195
231
|
console.error(
|
|
196
|
-
|
|
197
|
-
?
|
|
198
|
-
:
|
|
232
|
+
error instanceof SocketPathError
|
|
233
|
+
? error.message
|
|
234
|
+
: options.socket !== undefined
|
|
235
|
+
? code === "EADDRINUSE"
|
|
236
|
+
? `Socket ${options.socket} is already in use. Is Pi Pocket already running?`
|
|
237
|
+
: `Could not listen on ${options.socket}: ${(error as Error).message}`
|
|
238
|
+
: code === "EADDRINUSE"
|
|
239
|
+
? `Port ${options.port} is already in use on ${options.host}. Is Pi Pocket already running? Pick another with --port.`
|
|
240
|
+
: `Could not listen on ${options.host}:${options.port}: ${(error as Error).message}`,
|
|
199
241
|
);
|
|
200
242
|
process.exit(CONFIG_ERROR_CODE);
|
|
201
243
|
}
|
|
@@ -224,7 +266,10 @@ if (options.rotateToken) {
|
|
|
224
266
|
|
|
225
267
|
handle = makeHandler({
|
|
226
268
|
app: opened,
|
|
227
|
-
listen:
|
|
269
|
+
listen:
|
|
270
|
+
options.socket === undefined
|
|
271
|
+
? { host: options.host, port: options.port }
|
|
272
|
+
: { socket: options.socket },
|
|
228
273
|
restart: () => void stop(RESTART_CODE),
|
|
229
274
|
});
|
|
230
275
|
stopWatching = (() => {
|
|
@@ -256,10 +301,20 @@ await opened.updates.recover().catch((error: unknown) => {
|
|
|
256
301
|
if (launcher) {
|
|
257
302
|
process.send?.({
|
|
258
303
|
type: "ready",
|
|
259
|
-
|
|
260
|
-
|
|
304
|
+
...(options.socket === undefined
|
|
305
|
+
? { host: options.host, port: options.port }
|
|
306
|
+
: { socket: options.socket }),
|
|
261
307
|
loginPath: `/login?token=${token}`,
|
|
262
308
|
});
|
|
309
|
+
} else if (options.socket !== undefined) {
|
|
310
|
+
console.log(`\nPi Pocket is running on the Unix socket ${options.socket}.`);
|
|
311
|
+
console.log(` data: ${options.data}`);
|
|
312
|
+
console.log(` sessions: new sessions start in ${options.cwd}`);
|
|
313
|
+
console.log(
|
|
314
|
+
" Open this path once per browser at your reverse proxy's address to sign in as the owner (keep it private):",
|
|
315
|
+
);
|
|
316
|
+
console.log(` /login?token=${token}`);
|
|
317
|
+
console.log(" Other devices: open the app's menu and use “Sign in another device”.\n");
|
|
263
318
|
} else {
|
|
264
319
|
const hosts = new Set<string>([
|
|
265
320
|
options.host === "0.0.0.0" || options.host === "::" ? "127.0.0.1" : options.host,
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type BigIntStats, closeSync, constants, fstatSync, lstatSync, openSync } from "node:fs";
|
|
2
|
+
import { lstat, open, type FileHandle } from "node:fs/promises";
|
|
3
|
+
|
|
4
|
+
/** `O_RDONLY | O_NONBLOCK` where the system has it: a pipe swapped in for the file does not hold the reader. */
|
|
5
|
+
export const READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);
|
|
6
|
+
|
|
7
|
+
function linkError(path: string): NodeJS.ErrnoException {
|
|
8
|
+
return Object.assign(new Error(`ELOOP: a link is not followed, open '${path}'`), {
|
|
9
|
+
code: "ELOOP",
|
|
10
|
+
path,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** As `bigint`: a Windows file ID can be larger than a number holds exactly. */
|
|
15
|
+
function same(before: BigIntStats, after: BigIntStats): boolean {
|
|
16
|
+
return before.dev === after.dev && before.ino === after.ino;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Opens a file, never through a link as its last part, on every system. `O_NOFOLLOW` does that where it exists; it
|
|
21
|
+
* does not exist on Windows. So the path is also checked with `lstat` first, and the file opened must be the file
|
|
22
|
+
* checked (device and inode), which refuses a link that takes the file's place between the check and the open.
|
|
23
|
+
*/
|
|
24
|
+
export function openNoFollowSync(path: string, flags: number = READ_FLAGS): number {
|
|
25
|
+
const before = lstatSync(path, { bigint: true });
|
|
26
|
+
|
|
27
|
+
if (before.isSymbolicLink()) {
|
|
28
|
+
throw linkError(path);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const fd = openSync(path, flags | (constants.O_NOFOLLOW ?? 0));
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
if (!same(before, fstatSync(fd, { bigint: true }))) {
|
|
35
|
+
throw linkError(path);
|
|
36
|
+
}
|
|
37
|
+
} catch (error) {
|
|
38
|
+
closeSync(fd);
|
|
39
|
+
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return fd;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `openNoFollowSync`, as a `FileHandle`. */
|
|
47
|
+
export async function openNoFollow(path: string, flags: number = READ_FLAGS): Promise<FileHandle> {
|
|
48
|
+
const before = await lstat(path, { bigint: true });
|
|
49
|
+
|
|
50
|
+
if (before.isSymbolicLink()) {
|
|
51
|
+
throw linkError(path);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const handle = await open(path, flags | (constants.O_NOFOLLOW ?? 0));
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
if (!same(before, await handle.stat({ bigint: true }))) {
|
|
58
|
+
throw linkError(path);
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
await handle.close();
|
|
62
|
+
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return handle;
|
|
67
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/** Read-only approval observations, filtered for the person and the whole audience of a source session. */
|
|
2
|
+
import type { ConversationId } from "@earendil-works/pi-durable";
|
|
3
|
+
import type { PocketApp } from "./app.ts";
|
|
4
|
+
import { HttpError } from "./errors.ts";
|
|
5
|
+
import type { ApprovalRequest } from "./host.ts";
|
|
6
|
+
|
|
7
|
+
/** A pending approval. No arguments, free-text reasons, form fields, or answers leave this API. */
|
|
8
|
+
export interface PendingApproval {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly conversationId: ConversationId;
|
|
11
|
+
readonly session: ConversationId;
|
|
12
|
+
readonly createdAt: number;
|
|
13
|
+
readonly tool: "bash" | "write" | "edit" | "ask" | "tool";
|
|
14
|
+
readonly summary: string;
|
|
15
|
+
readonly state: "pending";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ResolvedApproval extends Omit<PendingApproval, "state"> {
|
|
19
|
+
readonly state: "resolved";
|
|
20
|
+
readonly outcome: "allowed" | "denied" | "cancelled" | "superseded";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ApprovalEvents {
|
|
24
|
+
created: PendingApproval;
|
|
25
|
+
resolved: ResolvedApproval;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface PendingApprovalsApi {
|
|
29
|
+
list(source: ConversationId): readonly PendingApproval[];
|
|
30
|
+
on<E extends keyof ApprovalEvents>(
|
|
31
|
+
source: ConversationId,
|
|
32
|
+
event: E,
|
|
33
|
+
listener: (approval: ApprovalEvents[E]) => unknown,
|
|
34
|
+
): () => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Internal transitions carry the original request, never exposed to an extension through the public facade. */
|
|
38
|
+
export type ApprovalTransition =
|
|
39
|
+
| { event: "created"; request: ApprovalRequest }
|
|
40
|
+
| { event: "resolved"; request: ApprovalRequest; outcome: ResolvedApproval["outcome"] };
|
|
41
|
+
|
|
42
|
+
const summaries = {
|
|
43
|
+
bash: "Run a command (arguments redacted)",
|
|
44
|
+
write: "Write a file (arguments redacted)",
|
|
45
|
+
edit: "Edit a file (arguments redacted)",
|
|
46
|
+
ask: "Answer a question (contents redacted)",
|
|
47
|
+
tool: "Run a tool (arguments redacted)",
|
|
48
|
+
} as const;
|
|
49
|
+
|
|
50
|
+
function describe(app: PocketApp, request: ApprovalRequest): PendingApproval {
|
|
51
|
+
// Do not try to recognize secrets in arbitrary shell commands, paths, or prose. Withhold all such text.
|
|
52
|
+
const tool =
|
|
53
|
+
request.form !== undefined
|
|
54
|
+
? "ask"
|
|
55
|
+
: request.tool === "bash" || request.tool === "write" || request.tool === "edit"
|
|
56
|
+
? request.tool
|
|
57
|
+
: "tool";
|
|
58
|
+
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
id: request.id,
|
|
61
|
+
conversationId: request.conversationId,
|
|
62
|
+
session: app.rootOf(request.conversationId),
|
|
63
|
+
createdAt: request.createdAt,
|
|
64
|
+
tool,
|
|
65
|
+
summary: summaries[tool],
|
|
66
|
+
state: "pending",
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function pendingApprovalsFor(app: PocketApp): PendingApprovalsApi {
|
|
71
|
+
function person(source: ConversationId): string {
|
|
72
|
+
const meta = app.sessionMeta(source);
|
|
73
|
+
const by = app.attribution.requesterOf(source);
|
|
74
|
+
const user = by === undefined ? undefined : app.config.userById(by);
|
|
75
|
+
|
|
76
|
+
if (meta === undefined || meta.pip !== undefined || user === undefined) {
|
|
77
|
+
throw new HttpError(
|
|
78
|
+
403,
|
|
79
|
+
"Approval observations need a session where Pi works for someone.",
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
app.requireSee(user, source);
|
|
84
|
+
|
|
85
|
+
return user.id;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function visible(source: ConversationId, by: string, request: ApprovalRequest): boolean {
|
|
89
|
+
const user = app.config.userById(by);
|
|
90
|
+
const meta = app.sessionMeta(source);
|
|
91
|
+
const target = app.sessionMeta(app.rootOf(request.conversationId));
|
|
92
|
+
|
|
93
|
+
return (
|
|
94
|
+
user !== undefined &&
|
|
95
|
+
meta !== undefined &&
|
|
96
|
+
meta.pip === undefined &&
|
|
97
|
+
target !== undefined &&
|
|
98
|
+
target.pip === undefined &&
|
|
99
|
+
app.canSee(user, source) &&
|
|
100
|
+
app.canSee(user, request.conversationId) &&
|
|
101
|
+
app.config.users
|
|
102
|
+
.filter((each) => app.canSee(each, source))
|
|
103
|
+
.every((each) => app.canSee(each, request.conversationId))
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return Object.freeze({
|
|
108
|
+
list(source: ConversationId): readonly PendingApproval[] {
|
|
109
|
+
const by = person(source);
|
|
110
|
+
|
|
111
|
+
return Object.freeze(
|
|
112
|
+
app.approvals
|
|
113
|
+
.all()
|
|
114
|
+
.filter((request) => visible(source, by, request))
|
|
115
|
+
.map((request) => describe(app, request)),
|
|
116
|
+
);
|
|
117
|
+
},
|
|
118
|
+
on<E extends keyof ApprovalEvents>(
|
|
119
|
+
source: ConversationId,
|
|
120
|
+
event: E,
|
|
121
|
+
listener: (approval: ApprovalEvents[E]) => unknown,
|
|
122
|
+
): () => void {
|
|
123
|
+
const by = person(source);
|
|
124
|
+
|
|
125
|
+
if (event !== "created" && event !== "resolved") {
|
|
126
|
+
throw new Error(`host.pendingApprovals.on: no event ${String(event)}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (typeof listener !== "function") {
|
|
130
|
+
throw new Error("host.pendingApprovals.on: give it a function");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let active = true;
|
|
134
|
+
const off = app.approvals.observe((change) => {
|
|
135
|
+
if (change.event !== event) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const pending = describe(app, change.request);
|
|
140
|
+
const value =
|
|
141
|
+
change.event === "created"
|
|
142
|
+
? pending
|
|
143
|
+
: Object.freeze({
|
|
144
|
+
...pending,
|
|
145
|
+
state: "resolved" as const,
|
|
146
|
+
outcome: change.outcome,
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// Deliver after the change, outside the approval's path. Recheck access on delivery, not enqueue.
|
|
150
|
+
queueMicrotask(() => {
|
|
151
|
+
if (!active || !visible(source, by, change.request)) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
Promise.resolve(listener(value as ApprovalEvents[E])).catch(failed);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
failed(error);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
const failed = (_error: unknown) => {
|
|
164
|
+
// A listener's exception can itself hold a secret. Do not copy it to a log.
|
|
165
|
+
app.log(`host.pendingApprovals.on(${event}): a listener failed`);
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
return () => {
|
|
169
|
+
active = false;
|
|
170
|
+
off();
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
}
|