paseo-plugin-secure-input 0.0.0-stage → 0.2.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/OVERVIEW.md +28 -0
- package/README.md +105 -2
- package/SECURITY.md +84 -0
- package/assets/icon.png +0 -0
- package/client/card.tsx +74 -0
- package/client/codes.ts +32 -0
- package/client/diagnostics-rows.ts +139 -0
- package/client/dialog-state.ts +59 -0
- package/client/dialog.tsx +292 -0
- package/client/envelope-cache.ts +85 -0
- package/client/fields.tsx +255 -0
- package/client/file-entry.ts +142 -0
- package/client/form-state.ts +198 -0
- package/client/globals.d.ts +19 -0
- package/client/outcome.ts +96 -0
- package/client/presentation.ts +114 -0
- package/client/sealing.ts +27 -0
- package/client/self-test.ts +96 -0
- package/client/settings.tsx +160 -0
- package/client/submit.ts +92 -0
- package/client/text.ts +47 -0
- package/client/tone.ts +36 -0
- package/client/web.ts +184 -0
- package/index.client.tsx +29 -0
- package/index.server.ts +6 -0
- package/npm-shrinkwrap.json +60 -0
- package/package.json +68 -4
- package/paseo-plugin.json +6 -0
- package/server/core/continuation.ts +151 -0
- package/server/core/entries.ts +89 -0
- package/server/core/outbox.ts +555 -0
- package/server/core/registry-store.ts +185 -0
- package/server/core/registry.ts +1031 -0
- package/server/core/selftest.ts +60 -0
- package/server/core/view.ts +38 -0
- package/server/io/atomic.ts +119 -0
- package/server/io/deadline.ts +28 -0
- package/server/io/descriptor.ts +36 -0
- package/server/io/directory.ts +40 -0
- package/server/io/drop.ts +434 -0
- package/server/io/legacy-shim.ts +108 -0
- package/server/io/ownership.ts +8 -0
- package/server/io/private-file.ts +86 -0
- package/server/paseo/bounded.ts +13 -0
- package/server/paseo/handlers.ts +124 -0
- package/server/paseo/hooks.ts +106 -0
- package/server/paseo/plugin.ts +341 -0
- package/server/paseo/runtime.ts +409 -0
- package/server/paseo/tools.ts +178 -0
- package/shared/bytes.ts +100 -0
- package/shared/canonical.ts +32 -0
- package/shared/card.ts +41 -0
- package/shared/contracts.ts +128 -0
- package/shared/errors.ts +48 -0
- package/shared/limits.ts +118 -0
- package/shared/request-id.ts +9 -0
- package/shared/request.ts +66 -0
- package/shared/sanitize.ts +101 -0
- package/shared/seal.ts +292 -0
- package/shared/shown.ts +12 -0
- package/shared/text.ts +39 -0
- package/shared/view.ts +42 -0
- package/skills/secure-input/SKILL.md +150 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
|
+
import type { z } from "zod";
|
|
3
|
+
import {
|
|
4
|
+
type DiagnosticsSchema,
|
|
5
|
+
clearDrop,
|
|
6
|
+
declineRequest,
|
|
7
|
+
fulfillRequest,
|
|
8
|
+
getRequest,
|
|
9
|
+
readDiagnostics,
|
|
10
|
+
selfTestBegin,
|
|
11
|
+
selfTestFinish,
|
|
12
|
+
} from "../../shared/contracts";
|
|
13
|
+
import { SecureInputError } from "../../shared/errors";
|
|
14
|
+
import type { FulfillResult, Registry } from "../core/registry";
|
|
15
|
+
import { beginSelfTest, finishSelfTest } from "../core/selftest";
|
|
16
|
+
import { buildView } from "../core/view";
|
|
17
|
+
import type { Runtime } from "./runtime";
|
|
18
|
+
|
|
19
|
+
export interface HandlerDeps {
|
|
20
|
+
registry: Pick<Registry, "get" | "fulfill" | "decline" | "clearDrop">;
|
|
21
|
+
runtime: Pick<Runtime, "attach">;
|
|
22
|
+
diagnostics(): Promise<z.input<typeof DiagnosticsSchema>>;
|
|
23
|
+
/** Told a code (never a message or a value) when a handler's answer did not fit its contract. */
|
|
24
|
+
report(code: string): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What the form is told when the plugin cannot give a sound answer to a submission: the registry failed in a way
|
|
29
|
+
* that is none of its refusals, or answered with something the contract cannot carry. What became of the submission
|
|
30
|
+
* is not known here, and the request is not closed by this answer, so the answer does not say that it is: it is
|
|
31
|
+
* `retryable`, which the form takes to mean that the request is open. The form keeps what was typed and the sealed
|
|
32
|
+
* envelope and sends the same envelope again, which the registry answers the same way however often it gets it (a
|
|
33
|
+
* submission it has already taken is answered as taken).
|
|
34
|
+
*/
|
|
35
|
+
const UNAVAILABLE = { ok: false as const, code: "service_unavailable" as const, retryable: true };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* An answer through the schema it will be checked against by the daemon, so that a mismatch is seen here, with a
|
|
39
|
+
* code in the log, and not as an opaque rejection of the call at run time. The answer is typed as the schema's
|
|
40
|
+
* input, so the compiler checks the object each handler builds; the run-time check is for what the types cannot see
|
|
41
|
+
* (a value outside a bound, an answer of a registry that is not what its type says).
|
|
42
|
+
*/
|
|
43
|
+
function checked<Schema extends z.ZodType>(schema: Schema, answer: z.input<Schema>, code: string, report: (code: string) => void): z.output<Schema> | null {
|
|
44
|
+
const result = schema.safeParse(answer);
|
|
45
|
+
if (result.success) return result.data;
|
|
46
|
+
report(code);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function cannotShow(what: string): SecureInputError {
|
|
51
|
+
return new SecureInputError("service_unavailable", `the ${what} cannot be shown`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The app's side. Any owner session can call these, including an agent with the daemon credential, so none of them
|
|
56
|
+
* is treated as proof that a human acted, and none returns a typed value. Each one parses its own answer through its
|
|
57
|
+
* contract's schema before returning it: a fulfilment that cannot be described gets a fixed refusal, and the
|
|
58
|
+
* contracts that have no refusal reject with a fixed text.
|
|
59
|
+
*/
|
|
60
|
+
export function registerHandlers(host: Pick<PluginServerContext, "handle">, { registry, runtime, diagnostics, report }: HandlerDeps): void {
|
|
61
|
+
host.handle(selfTestBegin, (_input, { paseo }) => {
|
|
62
|
+
runtime.attach(paseo);
|
|
63
|
+
const answer = checked(selfTestBegin.output, beginSelfTest(), "selftest_invalid", report);
|
|
64
|
+
if (answer === null) throw cannotShow("self-test");
|
|
65
|
+
return answer;
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
host.handle(selfTestFinish, ({ probeId, envelope, digest }, { paseo }) => {
|
|
69
|
+
runtime.attach(paseo);
|
|
70
|
+
const answer = checked(selfTestFinish.output, finishSelfTest(probeId, envelope, digest), "selftest_invalid", report);
|
|
71
|
+
if (answer === null) throw cannotShow("self-test");
|
|
72
|
+
return answer;
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
host.handle(getRequest, async ({ requestId }, { paseo }) => {
|
|
76
|
+
runtime.attach(paseo);
|
|
77
|
+
const view = checked(getRequest.output, buildView(registry, requestId), "view_invalid", report);
|
|
78
|
+
if (view === null) throw cannotShow("request");
|
|
79
|
+
return view;
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
host.handle(fulfillRequest, async ({ requestId, envelope }, { paseo }) => {
|
|
83
|
+
runtime.attach(paseo);
|
|
84
|
+
let result: FulfillResult;
|
|
85
|
+
try {
|
|
86
|
+
result = await registry.fulfill(requestId, envelope);
|
|
87
|
+
} catch {
|
|
88
|
+
// Not one of the registry's refusals, which are data: nothing of it is repeated.
|
|
89
|
+
report("fulfill_failed");
|
|
90
|
+
return UNAVAILABLE;
|
|
91
|
+
}
|
|
92
|
+
const answer = result.ok
|
|
93
|
+
? { ok: true as const, state: result.state }
|
|
94
|
+
: result.detail === undefined
|
|
95
|
+
? { ok: false as const, code: result.code, retryable: result.retryable }
|
|
96
|
+
: { ok: false as const, code: result.code, retryable: result.retryable, detail: result.detail };
|
|
97
|
+
return checked(fulfillRequest.output, answer, "fulfill_invalid", report) ?? UNAVAILABLE;
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
host.handle(declineRequest, async ({ requestId }, { paseo }) => {
|
|
101
|
+
runtime.attach(paseo);
|
|
102
|
+
const answer = checked(declineRequest.output, { state: (await registry.decline(requestId)).state }, "decline_invalid", report);
|
|
103
|
+
if (answer === null) throw cannotShow("decision");
|
|
104
|
+
return answer;
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// The human's word to delete every file. Like the rest, anyone with the owner's session can call it, an agent included,
|
|
108
|
+
// and it is no proof that a human did: it deletes what the plugin deletes by itself within 15 minutes, and returns counts.
|
|
109
|
+
// A registry that refuses it (the plugin is stopping, the drop cannot be swept) is an error of the call, so that the
|
|
110
|
+
// screen does not take a deletion that did not happen for one that did.
|
|
111
|
+
host.handle(clearDrop, async (_input, { paseo }) => {
|
|
112
|
+
runtime.attach(paseo);
|
|
113
|
+
const answer = checked(clearDrop.output, await registry.clearDrop(), "clear_invalid", report);
|
|
114
|
+
if (answer === null) throw cannotShow("deletion");
|
|
115
|
+
return answer;
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
host.handle(readDiagnostics, async (_input, { paseo }) => {
|
|
119
|
+
runtime.attach(paseo);
|
|
120
|
+
const answer = checked(readDiagnostics.output, await diagnostics(), "diagnostics_invalid", report);
|
|
121
|
+
if (answer === null) throw cannotShow("diagnostics");
|
|
122
|
+
return answer;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { AgentToolDefinition, PluginBeforeRequests, PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
|
+
import { SecureInputError } from "../../shared/errors";
|
|
3
|
+
import type { Registry } from "../core/registry";
|
|
4
|
+
import { within } from "./bounded";
|
|
5
|
+
import type { Runtime } from "./runtime";
|
|
6
|
+
import { TOOL_NAMES } from "./tools";
|
|
7
|
+
|
|
8
|
+
export type SessionOpenRequest = PluginBeforeRequests["agent.session_open"];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How long the handler of a turn's end waits at most for the sets that turn releases (`Registry.turnEnded`). Removing a
|
|
12
|
+
* set is a few system calls; the bound is for a disk that stalls, and it ends the wait, not the removal, which goes on
|
|
13
|
+
* in the registry's queue. Five seconds keeps an event handler that the daemon waits for from being held for longer.
|
|
14
|
+
*/
|
|
15
|
+
export const RELEASE_WAIT_MS = 5_000;
|
|
16
|
+
|
|
17
|
+
/** The plugin's own tool names, for a lookup by a name that comes with the request. */
|
|
18
|
+
const OWN_TOOLS: ReadonlySet<string> = new Set(TOOL_NAMES);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The request as it came, with the plugin's tools added to `tools`. A tool already there under one of the plugin's own
|
|
22
|
+
* names is an older one of its own and is replaced; any other stays. In Paseo 0.14 the list a hook is handed holds only
|
|
23
|
+
* what this plugin's own earlier hooks put there: each plugin gets an empty one, and the daemon merges what the plugins
|
|
24
|
+
* return afterwards (server `plugins/runtime.ts`). So the filter is defensive: no name leaves this hook twice.
|
|
25
|
+
*/
|
|
26
|
+
export function withTools(request: SessionOpenRequest, tools: readonly AgentToolDefinition[]): SessionOpenRequest {
|
|
27
|
+
return { ...request, tools: [...request.tools.filter((tool) => !OWN_TOOLS.has(tool.name)), ...tools] };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface HookDeps {
|
|
31
|
+
runtime: Pick<Runtime, "attach" | "turnEnded" | "agentArchived">;
|
|
32
|
+
/** What a turn's start and end do to the sets of the agent's delivered requests: they arm the deletion, and fire it. */
|
|
33
|
+
turns: Pick<Registry, "turnStarted" | "turnEnded">;
|
|
34
|
+
/** The plugin's tools, built for the session that opens. One that cannot be built is a failure of the hook. */
|
|
35
|
+
tools(): AgentToolDefinition[];
|
|
36
|
+
/** Remembers, for the diagnostics, that a hook or an event handler failed. A code, never a message. */
|
|
37
|
+
failed(hook: string, code: string): void;
|
|
38
|
+
/** `RELEASE_WAIT_MS` unless a test wants less. */
|
|
39
|
+
releaseWaitMs?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The code a failure is remembered under: ours when it is ours, `unexpected` for anything else. */
|
|
43
|
+
export function failureCode(error: unknown): string {
|
|
44
|
+
return error instanceof SecureInputError ? error.code : "unexpected";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The daemon runs the `before` hooks inside the opening of an agent's session: a throw from one fails that opening (0.14
|
|
49
|
+
* passes it on as "Plugin … before agent.session_open failed"), and it gives a hook 30 seconds. So nothing here can
|
|
50
|
+
* reject, and the session-open hook waits for nothing: it builds the tools and hands them over, and a call waits for the
|
|
51
|
+
* start-up itself (`agentTools`). Any failure of the hook (tools that cannot be built, a payload that is not what the SDK
|
|
52
|
+
* declares) is remembered as a code, and the request goes on as it came. The handlers of events are held to the same
|
|
53
|
+
* rule, which the daemon only logs for; the one handler that waits, a turn's end for the sets it releases, waits within
|
|
54
|
+
* `RELEASE_WAIT_MS`.
|
|
55
|
+
*/
|
|
56
|
+
export function registerHooks(host: Pick<PluginServerContext, "before" | "on">, deps: HookDeps): void {
|
|
57
|
+
host.before("agent.session_open", ({ request }, { paseo }) => {
|
|
58
|
+
try {
|
|
59
|
+
deps.runtime.attach(paseo);
|
|
60
|
+
return withTools(request, deps.tools());
|
|
61
|
+
} catch (error) {
|
|
62
|
+
deps.failed("agent.session_open", failureCode(error));
|
|
63
|
+
return request;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// A turn began: a delivered request whose message was handed over before it is armed, and the end of this turn takes
|
|
68
|
+
// its set (`Registry.turnStarted`). The event is read inside the guard: a payload without an agent is a failure.
|
|
69
|
+
host.on("agent.turn_started", (event, { paseo }) => {
|
|
70
|
+
try {
|
|
71
|
+
deps.runtime.attach(paseo);
|
|
72
|
+
deps.turns.turnStarted(event.agent.id);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
deps.failed("agent.turn_started", failureCode(error));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// A turn ended, with any outcome. First the sets it releases, waited for within `RELEASE_WAIT_MS`: a wait that runs out
|
|
79
|
+
// is no failure, and the removal goes on in the registry. Then what waits for the agent is asked for, also when the
|
|
80
|
+
// releases failed: a message is never held back by them.
|
|
81
|
+
host.on("agent.turn_ended", async (event, { paseo }) => {
|
|
82
|
+
try {
|
|
83
|
+
deps.runtime.attach(paseo);
|
|
84
|
+
const agentId = event.agent.id;
|
|
85
|
+
try {
|
|
86
|
+
await within(deps.releaseWaitMs ?? RELEASE_WAIT_MS, () => deps.turns.turnEnded(agentId));
|
|
87
|
+
} catch (error) {
|
|
88
|
+
deps.failed("agent.turn_ended", failureCode(error));
|
|
89
|
+
}
|
|
90
|
+
deps.runtime.turnEnded(agentId);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
deps.failed("agent.turn_ended", failureCode(error));
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// An archived agent is gone for good, so what waits for it is dropped. `agent.closed` is deliberately not used for
|
|
97
|
+
// this: what "closed" means for an agent that can be opened again could not be established.
|
|
98
|
+
host.on("agent.archived", ({ agent }, { paseo }) => {
|
|
99
|
+
try {
|
|
100
|
+
deps.runtime.attach(paseo);
|
|
101
|
+
deps.runtime.agentArchived(agent.id);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
deps.failed("agent.archived", failureCode(error));
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
}
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
|
+
import { lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { z } from "zod";
|
|
6
|
+
import type { DiagnosticsSchema } from "../../shared/contracts";
|
|
7
|
+
import { SecureInputError, errorDetailOf, type ErrorCode } from "../../shared/errors";
|
|
8
|
+
import { messageFor } from "../core/continuation";
|
|
9
|
+
import { Outbox, type OutboxItem, type ResolvedMessage } from "../core/outbox";
|
|
10
|
+
import { DROP_SWEEP_BOUND_MS, Registry, SHUTDOWN_BOUND_MS } from "../core/registry";
|
|
11
|
+
import { clearSelfTests } from "../core/selftest";
|
|
12
|
+
import { holdDirectory } from "../io/directory";
|
|
13
|
+
import { DropStore } from "../io/drop";
|
|
14
|
+
import { replaceLegacyBridge } from "../io/legacy-shim";
|
|
15
|
+
import { TIMED_OUT, within } from "./bounded";
|
|
16
|
+
import { registerHandlers } from "./handlers";
|
|
17
|
+
import { registerHooks } from "./hooks";
|
|
18
|
+
import { Runtime, SETTLE_BOUND_MS } from "./runtime";
|
|
19
|
+
import { agentTools } from "./tools";
|
|
20
|
+
|
|
21
|
+
/** The parts of the server context the plugin uses. */
|
|
22
|
+
export type PluginHost = Pick<PluginServerContext, "handle" | "before" | "on">;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What the plugin runs in. Under plain Node the shim v1 left is pointed at `execPath`, which runs the stub in place of
|
|
26
|
+
* v1's bridge; Electron's binary runs no script as Node, so under Electron the shim is left as v1 wrote it.
|
|
27
|
+
*/
|
|
28
|
+
export interface RuntimeInfo {
|
|
29
|
+
kind: "node" | "electron";
|
|
30
|
+
execPath: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PluginOptions {
|
|
34
|
+
/** `<Paseo home>/secure-input`. Made if missing, and resolved to its real path. */
|
|
35
|
+
dataDir: string;
|
|
36
|
+
runtime: RuntimeInfo;
|
|
37
|
+
/** Where lines for the plugin's log go. Only codes and fixed phrases are ever given to it. */
|
|
38
|
+
log(line: string): void;
|
|
39
|
+
/** `DAEMON_CALL_TIMEOUT_MS` unless a test wants less. */
|
|
40
|
+
daemonCallTimeoutMs?: number;
|
|
41
|
+
/** `STARTUP_WAIT_MS` unless a test wants less. */
|
|
42
|
+
startupWaitMs?: number;
|
|
43
|
+
/** `EXPIRY_INTERVAL_MS` unless a test wants less. */
|
|
44
|
+
expiryIntervalMs?: number;
|
|
45
|
+
/** How long a delivered set stays at the most: `DROP_TTL_MS` unless a test wants less. */
|
|
46
|
+
dropTtlMs?: number;
|
|
47
|
+
/** How long a tool call's operation waits for its turn in the registry's queue at the most: `ADMISSION_WAIT_MS` unless a test wants less. */
|
|
48
|
+
admissionWaitMs?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface StartupProblem {
|
|
52
|
+
code: ErrorCode | "unexpected";
|
|
53
|
+
detail: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface Status {
|
|
57
|
+
problem: StartupProblem | null;
|
|
58
|
+
lastHookFailure: string | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface Parts {
|
|
62
|
+
/** The real path of the data directory. Everything below is derived from it. */
|
|
63
|
+
dataDir: string;
|
|
64
|
+
/** `bin` is where v1 installed its bridge and its shim, which the start-up replaces with a stub where they are; `drop` is where the sets are. */
|
|
65
|
+
files: { outbox: string; bin: string; drop: string };
|
|
66
|
+
outbox: Outbox;
|
|
67
|
+
runtime: Runtime;
|
|
68
|
+
registry: Registry;
|
|
69
|
+
status: Status;
|
|
70
|
+
diagnostics(): Promise<z.input<typeof DiagnosticsSchema>>;
|
|
71
|
+
/** Remembers that a hook or an event handler failed, as a code. */
|
|
72
|
+
failed(hook: string, code: string): void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface RunningPlugin extends Parts {
|
|
76
|
+
/** Settles when the start-up has ended, with or without a problem. Never rejects. */
|
|
77
|
+
ready: Promise<void>;
|
|
78
|
+
/** Stops the plugin. Safe to call twice, and while the start-up is still going. */
|
|
79
|
+
dispose(): Promise<void>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** How often requests past their time are expired, and waiting messages and owed cards are tried again. */
|
|
83
|
+
export const EXPIRY_INTERVAL_MS = 60_000;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* How long a tool call waits for the start-up to end before it is refused with `NOT_STARTED`, and how long `dispose`
|
|
87
|
+
* waits for it before it goes on without it. The start-up is a handful of operations on the plugin's own files, a few
|
|
88
|
+
* milliseconds; the wait is for the case that a disk is slow, and it is a bound so that a start-up that never ends
|
|
89
|
+
* can hold up neither a call of an agent nor the stopping of the plugin.
|
|
90
|
+
*/
|
|
91
|
+
export const STARTUP_WAIT_MS = 5_000;
|
|
92
|
+
|
|
93
|
+
const PROBLEM_DETAIL_MAX = 300;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* How long Paseo 0.14 lets the plugin's process stop by itself. The daemon sends the process `shutdown`, on which the
|
|
97
|
+
* process runs `dispose`; 2 seconds later it sends SIGTERM, and 2 seconds after that SIGKILL
|
|
98
|
+
* (`SOFT_SHUTDOWN_TIMEOUT_MS = 2_000`, getpaseo/paseo v0.14.0-beta.1 packages/server/src/server/plugins/runtime.ts:48
|
|
99
|
+
* and :1316-1324). The plugin's process has no handler for SIGTERM (packages/server/src/server/plugins/plugin-process.ts
|
|
100
|
+
* installs none), so Node ends it at SIGTERM: what `dispose` has not done 2 seconds after it began is not done.
|
|
101
|
+
*/
|
|
102
|
+
export const PASEO_STOP_WINDOW_MS = 2_000;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The longest `dispose` waits for anything but the plugin's own files: the registry's shutdown, in which the sets are
|
|
106
|
+
* released and its last save is made and then `drop/` is swept, and then the runtime's settling once it was stopped.
|
|
107
|
+
* 1.8 seconds, inside `PASEO_STOP_WINDOW_MS` with room for the rest of the process's stop: so `drop/` is swept before
|
|
108
|
+
* Paseo ends the process, however long a task in the registry's queue takes. A start-up that has not ended is waited
|
|
109
|
+
* for `STARTUP_WAIT_MS` before that, which is longer than the window. Such a start-up has delivered no set (every
|
|
110
|
+
* request comes from a tool call, and a tool call waits for the start-up), so what the window cuts short then is only
|
|
111
|
+
* the sweep of what an earlier run left in `drop/`, which the next start makes.
|
|
112
|
+
*/
|
|
113
|
+
export const DISPOSE_BOUND_MS = SHUTDOWN_BOUND_MS + DROP_SWEEP_BOUND_MS + SETTLE_BOUND_MS;
|
|
114
|
+
|
|
115
|
+
const UNEXPECTED_STARTUP = "an unexpected error stopped the start-up";
|
|
116
|
+
|
|
117
|
+
export function describeRuntime(versions: Readonly<Record<string, string | undefined>>, execPath: string): RuntimeInfo {
|
|
118
|
+
return { kind: versions.electron ? "electron" : "node", execPath };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function defaultOptions(env: NodeJS.ProcessEnv = process.env): PluginOptions {
|
|
122
|
+
const home = env.PASEO_HOME || join(homedir(), ".paseo");
|
|
123
|
+
return {
|
|
124
|
+
dataDir: join(home, "secure-input"),
|
|
125
|
+
runtime: describeRuntime(process.versions, process.execPath),
|
|
126
|
+
log: (line) => console.error(line),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The directory as it really is, so that every path derived from it is the real one. It is made if it is missing,
|
|
132
|
+
* and that is all that is done to it here: a link in place of the directory itself is not followed, the path is
|
|
133
|
+
* returned as it is, and the hold that starts the plugin refuses it. The hold also checks the owner and the mode.
|
|
134
|
+
*/
|
|
135
|
+
function realDirectory(path: string): string {
|
|
136
|
+
try {
|
|
137
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
138
|
+
return lstatSync(path).isSymbolicLink() ? path : realpathSync(path);
|
|
139
|
+
} catch {
|
|
140
|
+
return path;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function describeProblem(error: unknown): StartupProblem {
|
|
145
|
+
if (!(error instanceof SecureInputError)) return { code: "unexpected", detail: UNEXPECTED_STARTUP };
|
|
146
|
+
return { code: error.code, detail: errorDetailOf(error, PROBLEM_DETAIL_MAX) ?? "" };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The message an outbox item stands for, from the plugin's own record and with the paths of its set in `drop`, and the agent the record belongs to. */
|
|
150
|
+
function resolveMessage(registry: Pick<Registry, "get">, item: OutboxItem, drop: string): ResolvedMessage | null {
|
|
151
|
+
const record = registry.get(item.requestId);
|
|
152
|
+
if (record === undefined) return null;
|
|
153
|
+
const text = messageFor(record, item.kind, drop);
|
|
154
|
+
return text === null ? null : { agentId: record.agentId, text };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Builds the parts and connects them. Nothing is started: the data directory is made and resolved, and that is all. */
|
|
158
|
+
export function assemble(options: PluginOptions): Parts {
|
|
159
|
+
const dataDir = realDirectory(options.dataDir);
|
|
160
|
+
const files = {
|
|
161
|
+
outbox: join(dataDir, "outbox.json"),
|
|
162
|
+
bin: join(dataDir, "bin"),
|
|
163
|
+
drop: join(dataDir, "drop"),
|
|
164
|
+
};
|
|
165
|
+
const report = (code: string): void => options.log(`secure-input: ${code}`);
|
|
166
|
+
const status: Status = { problem: null, lastHookFailure: null };
|
|
167
|
+
|
|
168
|
+
// The resolver reads the registry, which is built below: it runs only when something is sent, and so does `onSend`.
|
|
169
|
+
// A delivery message that is handed over makes the next turn of its agent the one that takes the set.
|
|
170
|
+
const outbox: Outbox = new Outbox(files.outbox, (item) => resolveMessage(registry, item, files.drop), {
|
|
171
|
+
onSend: (item) => {
|
|
172
|
+
if (item.kind === "continuation") registry.messageSent(item.requestId);
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
const runtime: Runtime = new Runtime(outbox, { callTimeoutMs: options.daemonCallTimeoutMs, report });
|
|
176
|
+
const registry: Registry = new Registry({
|
|
177
|
+
dataDir,
|
|
178
|
+
drop: new DropStore(files.drop),
|
|
179
|
+
onChange: (record, change) => runtime.publish(record, change),
|
|
180
|
+
// The history is bounded, and so is what the runtime and the outbox keep per request.
|
|
181
|
+
onForget: (requestId) => runtime.forget(requestId),
|
|
182
|
+
// The clock the registry's stored times and expiry are in: integer milliseconds.
|
|
183
|
+
now: () => Date.now(),
|
|
184
|
+
dropTtlMs: options.dropTtlMs,
|
|
185
|
+
admissionWaitMs: options.admissionWaitMs,
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
dataDir,
|
|
190
|
+
files,
|
|
191
|
+
outbox,
|
|
192
|
+
runtime,
|
|
193
|
+
registry,
|
|
194
|
+
status,
|
|
195
|
+
failed(hook, code) {
|
|
196
|
+
status.lastHookFailure = `${hook}: ${code}`;
|
|
197
|
+
options.log(`secure-input: hook_failed ${hook} ${code}`);
|
|
198
|
+
},
|
|
199
|
+
async diagnostics() {
|
|
200
|
+
return {
|
|
201
|
+
attached: runtime.attached,
|
|
202
|
+
dataDir,
|
|
203
|
+
registry: registry.health(),
|
|
204
|
+
outbox: outbox.health(),
|
|
205
|
+
requests: registry.counts(),
|
|
206
|
+
startup: status.problem,
|
|
207
|
+
cardsOwed: runtime.cardsOwed,
|
|
208
|
+
messagesHeld: runtime.messagesHeld,
|
|
209
|
+
lastHookFailure: status.lastHookFailure,
|
|
210
|
+
};
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Starts the plugin inside the daemon: registers the RPC handlers and the hooks at once, so the daemon sees them
|
|
217
|
+
* when `contribute` returns, and starts the start-up sequence, which cannot take them away. A failure of the sequence
|
|
218
|
+
* is kept as a code and a fixed phrase for the diagnostics and the log, and what had been set up stays up: the tools
|
|
219
|
+
* are offered all the same, and refuse in fixed words that send the agent to the user.
|
|
220
|
+
*/
|
|
221
|
+
export function startPlugin(host: PluginHost, options: PluginOptions): RunningPlugin {
|
|
222
|
+
const parts = assemble(options);
|
|
223
|
+
const { dataDir, files, registry, runtime, status, failed } = parts;
|
|
224
|
+
const report = (code: string): void => options.log(`secure-input: ${code}`);
|
|
225
|
+
const startupWaitMs = options.startupWaitMs ?? STARTUP_WAIT_MS;
|
|
226
|
+
|
|
227
|
+
// The handlers and the hooks below are registered at once, and any of them may ask for a flush of the outbox before
|
|
228
|
+
// the start-up has read the requests. Until it has, the outbox could not tell a request that is not loaded yet from
|
|
229
|
+
// one that does not exist, and would drop a message that waited across the restart: so no flush runs before then.
|
|
230
|
+
// A start-up that never gets as far as the load never flushes, and what waits stays in the file for the next start.
|
|
231
|
+
runtime.holdMessages();
|
|
232
|
+
|
|
233
|
+
// In this order, and the first step to fail ends it. The directory is held (a real directory of this user, 0700)
|
|
234
|
+
// before anything is read from it, written into it or removed from it. Then `drop/` is held and everything a killed
|
|
235
|
+
// run left in it is swept, before anything else that can fail: a set with values in it must not outlive a start that
|
|
236
|
+
// ends in a failure further on (a `bin/` that is not a private directory), and the sweep needs nothing but the
|
|
237
|
+
// directory. A `drop/` that is no private directory of this user fails the start-up there. Then the stub takes the
|
|
238
|
+
// place of v1's bridge where v1 installed one. The registry loads last, so that no request is taken before the old
|
|
239
|
+
// ones have been dealt with: a tool call waits for the start-up (`started`).
|
|
240
|
+
//
|
|
241
|
+
// A dispose ends it too. Between two steps: once the plugin is being stopped no further step is begun, also not by a
|
|
242
|
+
// start-up that hung, was no longer waited for, and comes back later. And inside a step: the one that was under way
|
|
243
|
+
// goes on, and it asks again right before each thing it would do to a path the plugin shares with the one that may
|
|
244
|
+
// have been started in its place by then (`StillWanted`). The replacement of the bridge asks whether the plugin is
|
|
245
|
+
// being stopped; the sweep and the load ask the registry, which the dispose marks stopped the moment it stops waiting
|
|
246
|
+
// for the start-up (so that a sweep or a load that ends within that wait is done in full). On "no" nothing more in
|
|
247
|
+
// `drop/` is removed, the stub and the shim are not written, and the requests are not loaded.
|
|
248
|
+
let stopping = false;
|
|
249
|
+
const stillWanted = (): boolean => !stopping;
|
|
250
|
+
const steps: Array<() => Promise<void>> = [
|
|
251
|
+
() => holdDirectory(dataDir, "data"),
|
|
252
|
+
() => registry.sweep(),
|
|
253
|
+
async () => {
|
|
254
|
+
await replaceLegacyBridge(dataDir, options.runtime, stillWanted);
|
|
255
|
+
},
|
|
256
|
+
async () => {
|
|
257
|
+
// A registry that was stopped before it had read the requests has loaded none, and the messages stay held:
|
|
258
|
+
// released, the outbox would take every message that waits for a request it cannot find and drop it from the file.
|
|
259
|
+
if (await registry.load()) runtime.releaseMessages();
|
|
260
|
+
},
|
|
261
|
+
];
|
|
262
|
+
const ready: Promise<void> = (async () => {
|
|
263
|
+
try {
|
|
264
|
+
for (const step of steps) {
|
|
265
|
+
if (stopping) return;
|
|
266
|
+
await step();
|
|
267
|
+
}
|
|
268
|
+
} catch (error) {
|
|
269
|
+
status.problem = describeProblem(error);
|
|
270
|
+
// A SecureInputError's text is a fixed phrase of ours; for anything else only the phrase above is kept.
|
|
271
|
+
options.log(`secure-input failed to start: ${status.problem.code}${status.problem.detail === "" ? "" : `: ${status.problem.detail}`}`);
|
|
272
|
+
}
|
|
273
|
+
})();
|
|
274
|
+
|
|
275
|
+
/** How the start-up ended, for a tool call: waited for within the bound, and "pending" when it has not ended by then. */
|
|
276
|
+
const started = async (): Promise<StartupProblem | null | "pending"> => ((await within(startupWaitMs, () => ready)) === TIMED_OUT ? "pending" : status.problem);
|
|
277
|
+
|
|
278
|
+
// Each part of the tick is guarded on its own: a request past its time is expired, and what waits for an agent that
|
|
279
|
+
// became idle without a turn-ended event (the daemon only tells of those it sees) is tried again, as is a card the
|
|
280
|
+
// timeline does not show yet. A tick that finds the last flush still under way does not start a second one.
|
|
281
|
+
const expiry = setInterval(() => {
|
|
282
|
+
void (async () => {
|
|
283
|
+
try {
|
|
284
|
+
await registry.expire();
|
|
285
|
+
} catch {
|
|
286
|
+
report("expire_failed");
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
await runtime.flushAll();
|
|
290
|
+
} catch {
|
|
291
|
+
report("flush_failed");
|
|
292
|
+
}
|
|
293
|
+
})();
|
|
294
|
+
}, options.expiryIntervalMs ?? EXPIRY_INTERVAL_MS);
|
|
295
|
+
expiry.unref();
|
|
296
|
+
|
|
297
|
+
registerHandlers(host, { registry, runtime, diagnostics: parts.diagnostics, report });
|
|
298
|
+
// The tools are built for each session that opens, inside the hook: one that cannot be built fails that hook, which
|
|
299
|
+
// hands the session on as it came, and never the plugin. The turn events act on the registry's sets.
|
|
300
|
+
registerHooks(host, { runtime, turns: registry, tools: () => agentTools({ registry, runtime, started, drop: files.drop }), failed });
|
|
301
|
+
|
|
302
|
+
// Each step is its own, so that one that fails does not keep the rest from running.
|
|
303
|
+
//
|
|
304
|
+
// How long it takes at most: every step that waits for anything but the plugin's own files is bounded. A start-up
|
|
305
|
+
// that has not ended is waited for `STARTUP_WAIT_MS` and then left: it begins no further step, and the step it hangs
|
|
306
|
+
// in works on paths that the plugin started after this one uses too (what is in `drop/`, the stub and the shim), so
|
|
307
|
+
// that step asks before each thing it does to them and does none of it once the answer is no (see above). The
|
|
308
|
+
// registry's shutdown takes `SHUTDOWN_BOUND_MS` and then `DROP_SWEEP_BOUND_MS` at most; the runtime, once stopped,
|
|
309
|
+
// settles within `SETTLE_BOUND_MS`. So `DISPOSE_BOUND_MS`, the sum of the three, is the most a daemon that does not
|
|
310
|
+
// answer or a disk that hangs under `drop/` can add to a dispose, and it ends inside the window Paseo gives the stop
|
|
311
|
+
// (`PASEO_STOP_WINDOW_MS`). A disk that hangs under the start-up adds `STARTUP_WAIT_MS` and no more.
|
|
312
|
+
const step = async (name: string, run: () => unknown): Promise<void> => {
|
|
313
|
+
try {
|
|
314
|
+
await run();
|
|
315
|
+
} catch {
|
|
316
|
+
report(`cleanup_failed ${name}`);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
let disposing: Promise<void> | null = null;
|
|
320
|
+
const dispose = (): Promise<void> => {
|
|
321
|
+
disposing ??= (async () => {
|
|
322
|
+
stopping = true;
|
|
323
|
+
clearInterval(expiry);
|
|
324
|
+
await step("start-up", () => within(startupWaitMs, () => ready));
|
|
325
|
+
// The start-up is not waited for any longer, ended or not. From here on a sweep or a load of its own that
|
|
326
|
+
// comes back does nothing: the registry is marked now, and not a step further down, where its shutdown begins.
|
|
327
|
+
registry.stop();
|
|
328
|
+
// The registry before the runtime: it wipes its keys, releases every set, makes its last save and sweeps `drop/`
|
|
329
|
+
// while the runtime still delivers.
|
|
330
|
+
await step("registry", () => registry.shutdown());
|
|
331
|
+
// From here on the daemon is asked nothing more for a card or a message, however many are waiting: what is
|
|
332
|
+
// still owed is saved in the outbox for the next start to send, and a card that did not land is in the dialog.
|
|
333
|
+
await step("deliveries", () => runtime.stop());
|
|
334
|
+
await step("runtime", () => runtime.settled());
|
|
335
|
+
await step("self-tests", () => clearSelfTests());
|
|
336
|
+
})();
|
|
337
|
+
return disposing;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
return { ...parts, ready, dispose };
|
|
341
|
+
}
|