pi-better-server 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -1
- package/scripts/measure-shared-reads.mjs +25 -5
- package/scripts/test-on-pi.sh +3 -2
- package/src/daemon-owner.ts +2 -1
- package/src/handshake.ts +1 -1
- package/src/protocol.ts +2 -0
- package/src/runtime/background.ts +12 -3
- package/src/runtime/cancellation.ts +10 -6
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +18 -1
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +9 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +5 -3
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +17 -1
- package/src/runtime/domain/coordinator/src/store.mjs +11 -1
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/query-executor.ts +58 -9
- package/src/runtime/query-worker.mjs +3 -2
- package/src/runtime/read-model.ts +111 -59
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/work-client.d.mts +1 -0
- package/src/runtime/work-client.mjs +16 -2
- package/src/server.ts +66 -5
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -58,5 +58,8 @@
|
|
|
58
58
|
},
|
|
59
59
|
"engines": {
|
|
60
60
|
"node": ">=22.0.0"
|
|
61
|
+
},
|
|
62
|
+
"dependencies": {
|
|
63
|
+
"yaml": "^2.9.1"
|
|
61
64
|
}
|
|
62
65
|
}
|
|
@@ -45,8 +45,11 @@ function distribution(values) {
|
|
|
45
45
|
}
|
|
46
46
|
const report = { platform: process.platform, arch: process.arch, node: process.version,
|
|
47
47
|
sdk: sdkVersion, scope: 'Real Pi RPC processes with standalone Subagents, control RPC at 10 Hz, seeded read-only work records; no guardian in slice #753.', scenarios: [] };
|
|
48
|
+
const output = process.env.PI_SHARED_READ_REPORT ?? join(tmpdir(), 'pi-shared-read-resources.json');
|
|
49
|
+
const phase = (step, history, clients = 0) => { report.phase = { step, history, clients }; };
|
|
48
50
|
try {
|
|
49
51
|
for (const history of [4416, 10000]) {
|
|
52
|
+
phase('seed-history', history);
|
|
50
53
|
const root = realpathSync(mkdtempSync('/tmp/p751-res-'));
|
|
51
54
|
const agent = join(root, 'agent'), transport = join(root, 's'), runs = join(root, 'pi-better-subagents/runs');
|
|
52
55
|
const durable = join(agent, 'subagents'), archives = join(durable, 'attempts');
|
|
@@ -67,22 +70,28 @@ try {
|
|
|
67
70
|
pid: work.pid, spawnPid: process.pid, startedAt: Date.now(), sessionId: id, callback: false, name: `resource-work-${i}` }));
|
|
68
71
|
}
|
|
69
72
|
const server = track(fork(new URL('./measure-shared-reads/daemon.mjs', import.meta.url), [], { env, execArgv: [], stdio: ['ignore','ignore','inherit','ipc'] }));
|
|
73
|
+
phase('start-server', history);
|
|
70
74
|
const ready = await waitMessage(server, m => m.type === 'ready');
|
|
71
75
|
const control = new WorkClient(ready.socket, agent); await control.ready;
|
|
72
76
|
const pis = [];
|
|
73
77
|
const rebuildLatencies = [];
|
|
74
78
|
const rebuildStarted = performance.now();
|
|
79
|
+
phase('initial-snapshot', history);
|
|
75
80
|
const initial = control.get({ cwd: root, active: true });
|
|
76
81
|
let indexed = await initial;
|
|
77
82
|
while (indexed.status !== 'ready') {
|
|
83
|
+
phase('rebuild-status', history);
|
|
78
84
|
assert.ok(performance.now() - rebuildStarted < 30000, `Rebuild did not recover: ${indexed.reason}`);
|
|
79
85
|
const began = performance.now(); await control.request('runtime_get_status'); rebuildLatencies.push(performance.now() - began);
|
|
80
|
-
await delay(20); indexed = await control.get({ cwd: root, active: true });
|
|
86
|
+
await delay(20); phase('rebuild-snapshot', history); indexed = await control.get({ cwd: root, active: true });
|
|
81
87
|
}
|
|
82
88
|
const rebuildMs = performance.now() - rebuildStarted;
|
|
89
|
+
assert.ok(rebuildLatencies.every(ms => ms < 250), 'status RPC must respond within 250 ms during index rebuild');
|
|
83
90
|
assert.equal(indexed.activity.active, 2);
|
|
91
|
+
phase('history-count', history);
|
|
84
92
|
assert.equal((await control.get({ cwd: root, active: false, limit: 1 })).totalMatching, history);
|
|
85
93
|
for (const count of [1, 5, 10]) {
|
|
94
|
+
phase('start-pi-clients', history, count);
|
|
86
95
|
while (pis.length < count) {
|
|
87
96
|
const pi = track(fork(sdkCli, ['--mode','rpc','--offline','--no-session','--no-extensions',
|
|
88
97
|
'--extension',join(workspace,'packages/pi-better-subagents/index.ts'),
|
|
@@ -103,9 +112,12 @@ try {
|
|
|
103
112
|
});
|
|
104
113
|
await pi.rpc(); pis.push(pi);
|
|
105
114
|
}
|
|
115
|
+
phase('warmup', history, count);
|
|
106
116
|
await delay(1200);
|
|
107
117
|
await control.get({ cwd: root, active: true });
|
|
108
118
|
const before = await control.request('runtime_get_metrics');
|
|
119
|
+
report.lastMetrics = before;
|
|
120
|
+
phase('measurement-window', history, count);
|
|
109
121
|
const subjects = [...pis, server, work];
|
|
110
122
|
const start = await Promise.all(subjects.map(sample));
|
|
111
123
|
const began = performance.now(), latencies = [];
|
|
@@ -116,8 +128,10 @@ try {
|
|
|
116
128
|
}
|
|
117
129
|
const elapsedMs = performance.now() - began;
|
|
118
130
|
const end = await Promise.all(subjects.map(sample));
|
|
131
|
+
phase('post-window-snapshot', history, count);
|
|
119
132
|
await control.get({ cwd: root, active: true });
|
|
120
133
|
const after = await control.request('runtime_get_metrics');
|
|
134
|
+
report.lastMetrics = after;
|
|
121
135
|
assert.equal(after.metadataReads, before.metadataReads, 'unchanged history must not be reread for more Pi clients');
|
|
122
136
|
assert.equal(after.projections, before.projections, 'unchanged work must not be reprojected for more Pi clients');
|
|
123
137
|
assert.ok(after.inventories - before.inventories <= Math.ceil(elapsedMs / 1000) + 2,
|
|
@@ -139,7 +153,13 @@ try {
|
|
|
139
153
|
await Promise.all(pis.map(pi => stop(pi))); control.close(); await stop(server, true); await stop(work);
|
|
140
154
|
rmSync(root, { recursive: true, force: true });
|
|
141
155
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
156
|
+
report.phase = { step: 'complete' };
|
|
157
|
+
} catch (error) {
|
|
158
|
+
report.failure = { message: String(error).slice(0, 2048) };
|
|
159
|
+
throw error;
|
|
160
|
+
} finally {
|
|
161
|
+
try {
|
|
162
|
+
writeFileSync(output, JSON.stringify(report, null, 2) + '\n');
|
|
163
|
+
console.log(`Resource report: ${output}`);
|
|
164
|
+
} finally { await Promise.all([...children].map(child => stop(child))); }
|
|
165
|
+
}
|
package/scripts/test-on-pi.sh
CHANGED
|
@@ -25,11 +25,11 @@ printf '{ "name": "pi-compat", "private": true }\n' > "$PREFIX/package.json"
|
|
|
25
25
|
cp "$ROOT_DIR/scripts/isolate-registry.mjs" "$PREFIX/scripts/"
|
|
26
26
|
cp -R "$PKG_DIR/src" "$PKG_DIR/test" "$PKG_DIR/scripts" "$PKG_DIR/package.json" "$PKG_DIR/tsconfig.json" "$PREFIX/packages/pi-better-server/"
|
|
27
27
|
[ -d "$PKG_DIR/codex-plugin" ] && cp -R "$PKG_DIR/codex-plugin" "$PREFIX/packages/pi-better-server/"
|
|
28
|
-
#
|
|
28
|
+
# Activity and permission regressions load the real sibling providers against this SDK.
|
|
29
29
|
node --input-type=module - "$ROOT_DIR" "$PREFIX" <<'NODE'
|
|
30
30
|
import { cpSync } from "node:fs";
|
|
31
31
|
import { basename, join } from "node:path";
|
|
32
|
-
for (const name of ["pi-better-subagents", "pi-better-background-tasks", "operation-coordinator"]) {
|
|
32
|
+
for (const name of ["pi-better-subagents", "pi-better-background-tasks", "pi-better-sandbox", "operation-coordinator"]) {
|
|
33
33
|
cpSync(join(process.argv[2], "packages", name), join(process.argv[3], "packages", name), {
|
|
34
34
|
recursive: true, filter: path => !["node_modules", ".work", ".pi-compat"].includes(basename(path)),
|
|
35
35
|
});
|
|
@@ -39,6 +39,7 @@ NODE
|
|
|
39
39
|
# Its host-provided peers must keep resolving to the requested Pi above.
|
|
40
40
|
(cd "$PREFIX/packages/pi-better-subagents" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
41
41
|
(cd "$PREFIX/packages/pi-better-background-tasks" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
42
|
+
(cd "$PREFIX/packages/pi-better-sandbox" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
42
43
|
|
|
43
44
|
cd "$PREFIX/packages/pi-better-server"
|
|
44
45
|
installed="$(node -p "require('$PREFIX/node_modules/@earendil-works/pi-coding-agent/package.json').version")"
|
package/src/daemon-owner.ts
CHANGED
|
@@ -42,8 +42,9 @@ export function processMatchesStart(pid: number, start: unknown): boolean {
|
|
|
42
42
|
try {
|
|
43
43
|
const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
44
44
|
encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
|
|
45
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
45
46
|
}).trim();
|
|
46
|
-
return observed.length > 0 && observed === start.trim();
|
|
47
|
+
return observed.length > 0 && observed.replace(/\s+/g, " ") === start.trim().replace(/\s+/g, " ");
|
|
47
48
|
} catch { return false; }
|
|
48
49
|
}
|
|
49
50
|
const identity = processIdentity(pid);
|
package/src/handshake.ts
CHANGED
|
@@ -12,7 +12,7 @@ export function serverHello(identity: HelloIdentity = {}): HelloData {
|
|
|
12
12
|
return { protocolVersion: PROTOCOL_VERSION, piVersion: PI_VERSION, extensionVersions: { ...SERVER_EXTENSION_VERSIONS },
|
|
13
13
|
...(identity.agentDir ? { agentDir: identity.agentDir, nodeVersion: process.versions.node } : {}),
|
|
14
14
|
...(build ? { build } : {}), ...(identity.instanceId ? { instanceId: identity.instanceId } : {}),
|
|
15
|
-
capabilities: [...(identity.runtimeLifecycle ? ["runtime-client-retention-v1"] : []),...(identity.agentDir ? ["runtime-status-v1", "runtime-state-v1", "runtime-subscriptions-v1", "runtime-background-state-v1", "runtime-cancellation-v1"] : []), "native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
|
|
15
|
+
capabilities: [...(identity.runtimeLifecycle ? ["runtime-client-retention-v1"] : []),...(identity.agentDir ? ["runtime-status-v1", "runtime-state-v1", "runtime-subscriptions-v1", "runtime-background-state-v1", "runtime-cancellation-v1", "runtime-result-supervision-v1", "runtime-catalog-v1"] : []), "native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
|
|
16
16
|
...(identity.safeUpgrade && build && identity.instanceId ? ["safe-upgrade-v1"] : [])] };
|
|
17
17
|
}
|
|
18
18
|
|
package/src/protocol.ts
CHANGED
|
@@ -124,6 +124,7 @@ export type ControlCommand =
|
|
|
124
124
|
|
|
125
125
|
export type ClientCommand = HelloCommand | DaemonCommand | ControlCommand | SessionCommand
|
|
126
126
|
| { id?: string; type: "runtime_cancellation_status" }
|
|
127
|
+
| { id?: string; type: "runtime_result_supervision" }
|
|
127
128
|
| { id?: string; type: "runtime_cancel_task" | "runtime_query_cancellation"; credential: string }
|
|
128
129
|
| ({ id?: string; type: "runtime_upgrade" } & UpgradeRequest)
|
|
129
130
|
| { id?: string; type: "runtime_upgrade_status" }
|
|
@@ -131,6 +132,7 @@ export type ClientCommand = HelloCommand | DaemonCommand | ControlCommand | Sess
|
|
|
131
132
|
|
|
132
133
|
export type DaemonResponse =
|
|
133
134
|
| { id?: string; type: "response"; command: "runtime_cancellation_status" | "runtime_cancel_task" | "runtime_query_cancellation"; success: true; data: unknown }
|
|
135
|
+
| { id?: string; type: "response"; command: "runtime_result_supervision"; success: true; data: { hostId: string; epoch: string; reason?: string } }
|
|
134
136
|
| { id?: string; type: "response"; command: "hello"; success: true; data: HelloData }
|
|
135
137
|
| { id?: string; type: "response"; command: "list_sessions"; success: true; data: { sessions: SessionSummary[] } }
|
|
136
138
|
| { id?: string; type: "response"; command: "create_session"; success: true; sessionId: string; data: SessionSummary }
|
|
@@ -39,7 +39,7 @@ export class BackgroundObservation {
|
|
|
39
39
|
catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
|
|
40
40
|
return operations.flatMap((op: any) => {
|
|
41
41
|
try {
|
|
42
|
-
const inspection = snapshot(this.
|
|
42
|
+
const inspection = snapshot(this.directoryFor(op), op.task_id);
|
|
43
43
|
const claim = inspection?.claim;
|
|
44
44
|
return claim && !inspection.terminal && inspection.token === op.launch_token && processMatchesStart(claim.pid, claim.pidStartTime)
|
|
45
45
|
? [{ kind: "runner", id: op.task_id, owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace }, operationId: op.operation_id,
|
|
@@ -50,6 +50,14 @@ export class BackgroundObservation {
|
|
|
50
50
|
});
|
|
51
51
|
}
|
|
52
52
|
readonly metrics = { runnerSnapshots: 0, activeQueries: 0, historyQueries: 0 };
|
|
53
|
+
private directoryFor(op: any): string {
|
|
54
|
+
if (!op.supervision_host_id?.startsWith("server:")) return this.directory;
|
|
55
|
+
const row = this.db.prepare("SELECT value FROM coordinator_state WHERE key = ?").get(`result-supervision-v1:${op.operation_id}`);
|
|
56
|
+
if (!row) throw new Error("Captured result-supervision directory unavailable");
|
|
57
|
+
const grant = JSON.parse(row.value);
|
|
58
|
+
if (grant.launchToken !== op.launch_token || typeof grant.directory !== "string") throw new Error("Captured runner execution identity differs");
|
|
59
|
+
return grant.directory;
|
|
60
|
+
}
|
|
53
61
|
constructor(root: string, directory = join(tmpdir(), process.env.VITEST_POOL_ID ? `pi-better-background-tasks-vitest-${process.env.VITEST_POOL_ID}` : "pi-better-background-tasks", "supervisor"), indexDb?: any, changed = () => {}) {
|
|
54
62
|
this.root = root; this.directory = directory;
|
|
55
63
|
if (indexDb) this.history = new BackgroundHistory(indexDb, directory, () => {
|
|
@@ -105,9 +113,10 @@ export class BackgroundObservation {
|
|
|
105
113
|
private project(operations: any[]) {
|
|
106
114
|
return operations.map((op: any) => {
|
|
107
115
|
this.metrics.runnerSnapshots++;
|
|
108
|
-
const
|
|
116
|
+
const directory = this.directoryFor(op);
|
|
117
|
+
const inspection = snapshot(directory, op.task_id);
|
|
109
118
|
let context: any = {};
|
|
110
|
-
try { context = JSON.parse(readFileSync(join(
|
|
119
|
+
try { context = JSON.parse(readFileSync(join(directory, "observed", `${op.task_id}.json`), "utf8")); }
|
|
111
120
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
112
121
|
const terminal = inspection?.terminal === true || op.terminal_revision > 0;
|
|
113
122
|
const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
|
-
|
|
5
|
-
import { openStore } from "./domain/coordinator/index.mjs";
|
|
4
|
+
import { acquireMutationStore } from "./mutation-store.ts";
|
|
6
5
|
// @ts-expect-error Generated canonical supervisor; only stop is invoked here.
|
|
7
6
|
import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
|
|
8
7
|
// @ts-expect-error Generated canonical durable stop records.
|
|
@@ -28,15 +27,20 @@ export function hasPendingCancellation(root: string): boolean {
|
|
|
28
27
|
/** Cancellation only: no arbitrary method, module, launch or wait dispatch. */
|
|
29
28
|
export class RuntimeCancellation {
|
|
30
29
|
private store: any;
|
|
30
|
+
private releaseStore: () => void;
|
|
31
31
|
private pending = new Map<string, Promise<unknown>>();
|
|
32
32
|
readonly epoch: number;
|
|
33
33
|
private fault?: (stage: CancellationStage) => void;
|
|
34
34
|
get busy() { return this.pending.size > 0; }
|
|
35
35
|
constructor(root: string, instanceId: string, fault?: (stage: CancellationStage) => void) {
|
|
36
36
|
this.fault = fault;
|
|
37
|
-
|
|
38
|
-
this.
|
|
39
|
-
|
|
37
|
+
const lease = acquireMutationStore(root);
|
|
38
|
+
this.store = lease.store;
|
|
39
|
+
this.releaseStore = lease.release;
|
|
40
|
+
try {
|
|
41
|
+
this.epoch = this.store.cancellationRuntimeEpoch(instanceId);
|
|
42
|
+
for (const admission of this.store.pendingTaskCancellations()) void this.execute(admission);
|
|
43
|
+
} catch (error) { this.releaseStore(); throw error; }
|
|
40
44
|
}
|
|
41
45
|
async handle(command: Record<string, unknown>) {
|
|
42
46
|
if (Object.keys(command).some(key => !["id", "type", "credential"].includes(key))) throw new Error("not_accepted: unsupported cancellation field");
|
|
@@ -91,5 +95,5 @@ export class RuntimeCancellation {
|
|
|
91
95
|
this.pending.set(key, execution);
|
|
92
96
|
return execution;
|
|
93
97
|
}
|
|
94
|
-
async close() { await Promise.all(this.pending.values()); this.
|
|
98
|
+
async close() { await Promise.all(this.pending.values()); this.releaseStore(); }
|
|
95
99
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { processMatchesStart } from "../daemon-owner.ts";
|
|
5
|
+
|
|
6
|
+
/** Private fixed-host registrations, not client-supplied trust decisions. */
|
|
7
|
+
export class CatalogAdmission {
|
|
8
|
+
private live = new Map<string, object>();
|
|
9
|
+
private revoked = new Set<string>();
|
|
10
|
+
private root: string;
|
|
11
|
+
private instanceId: string;
|
|
12
|
+
constructor(agentDir: string, instanceId: string) { this.root = join(realpathSync(agentDir), "catalog-host-admission"); this.instanceId = instanceId; }
|
|
13
|
+
read(authority: any) {
|
|
14
|
+
if (!authority || typeof authority.id !== "string" || !/^[a-f0-9-]{36}$/.test(authority.id)
|
|
15
|
+
|| typeof authority.secret !== "string" || !/^[a-f0-9]{64}$/.test(authority.secret)) throw new Error("catalog-authority-refused");
|
|
16
|
+
const root = lstatSync(this.root), path = join(this.root, `${authority.id}.json`), file = lstatSync(path);
|
|
17
|
+
if (!root.isDirectory() || root.isSymbolicLink() || (root.mode & 0o077) !== 0 || root.uid !== process.getuid?.()
|
|
18
|
+
|| !file.isFile() || file.isSymbolicLink() || (file.mode & 0o077) !== 0 || file.uid !== root.uid || file.size > 8192) throw new Error("catalog-authority-refused");
|
|
19
|
+
const record = JSON.parse(readFileSync(path, "utf8"));
|
|
20
|
+
const digest = createHash("sha256").update(authority.secret).digest("hex");
|
|
21
|
+
if (record.version !== 1 || record.serverInstance !== this.instanceId || record.id !== authority.id || record.generation !== authority.generation
|
|
22
|
+
|| typeof record.secretHash !== "string" || record.secretHash.length !== digest.length
|
|
23
|
+
|| !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
|
|
24
|
+
|| record.cwd !== authority.cwd || record.cwd !== realpathSync(record.cwd)
|
|
25
|
+
|| record.sessionId !== authority.sessionId || record.branchId !== authority.branchId
|
|
26
|
+
|| typeof record.projectTrusted !== "boolean" || !Number.isSafeInteger(record.pid) || record.pid <= 0
|
|
27
|
+
|| typeof record.sessionId !== "string" || !record.sessionId || typeof record.branchId !== "string" || !record.branchId
|
|
28
|
+
|| typeof record.overlayDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.overlayDigest)) throw new Error("catalog-authority-refused");
|
|
29
|
+
if (!processMatchesStart(record.pid, record.pidStartTime)) throw new Error("catalog-host-identity-refused");
|
|
30
|
+
return record;
|
|
31
|
+
}
|
|
32
|
+
bind(authority: unknown, socket: object) {
|
|
33
|
+
const record = this.read(authority);
|
|
34
|
+
if (this.revoked.has(record.id)) throw new Error("catalog-host-revoked");
|
|
35
|
+
if (this.live.has(record.id) && this.live.get(record.id) !== socket) throw new Error("catalog-host-already-bound");
|
|
36
|
+
this.live.set(record.id, socket);
|
|
37
|
+
}
|
|
38
|
+
verify(authority: unknown) {
|
|
39
|
+
const record = this.read(authority);
|
|
40
|
+
if (!this.live.has(record.id)) throw new Error("catalog-host-revoked");
|
|
41
|
+
return record;
|
|
42
|
+
}
|
|
43
|
+
close(socket: object) {
|
|
44
|
+
for (const [id, owner] of this.live) if (owner === socket) {
|
|
45
|
+
this.live.delete(id);
|
|
46
|
+
try { rmSync(join(this.root, `${id}.json`), { force: true }); }
|
|
47
|
+
catch { this.revoked.add(id); }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { loadCatalog, saveDefinition, resetRuntimeToBundled, resetUserDefinition, listScopedAgents } from "./domain/catalog/catalog-store.mjs";
|
|
3
|
+
import { withAgentSessionSettings, saveAgentSessionDefaults } from "./domain/catalog/agent-session-settings.mjs";
|
|
4
|
+
import { saveSkillExposure } from "./domain/catalog/catalog-skill-edits.mjs";
|
|
5
|
+
import { parseDefinition } from "./domain/catalog/catalog-schema.mjs";
|
|
6
|
+
import { CatalogAdmission } from "./catalog-admission.ts";
|
|
7
|
+
import { overlayDigest } from "./domain/catalog/catalog-overlay.mjs";
|
|
8
|
+
import { watch, type FSWatcher } from "node:fs";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
|
|
11
|
+
/** One server-owned filesystem catalog; registrations belong to the live socket. */
|
|
12
|
+
export class SharedCatalog {
|
|
13
|
+
private agentDir: string;
|
|
14
|
+
readonly admission: CatalogAdmission;
|
|
15
|
+
private observers = new Set<() => void>();
|
|
16
|
+
private timer?: ReturnType<typeof setInterval>;
|
|
17
|
+
private pending?: ReturnType<typeof setTimeout>;
|
|
18
|
+
private watchers = new Map<string, { watcher: FSWatcher; references: number }>();
|
|
19
|
+
constructor(agentDir: string, instanceId: string) { this.agentDir = agentDir; this.admission = new CatalogAdmission(agentDir, instanceId); }
|
|
20
|
+
|
|
21
|
+
observe(read: () => any, emit: (snapshot: any) => void) {
|
|
22
|
+
if (this.observers.size >= 64) throw new Error("catalog-subscription-limit");
|
|
23
|
+
let revision: string | undefined, seq = 0;
|
|
24
|
+
const watched: string[] = [];
|
|
25
|
+
const initial = read();
|
|
26
|
+
const paths = new Set<string>([this.agentDir, ...[...initial.roles, ...initial.agents].map(([, entry]: any) => dirname(entry.path))]);
|
|
27
|
+
const notify = () => { this.pending ??= setTimeout(() => { this.pending = undefined; for (const reconcile of this.observers) reconcile(); }, 50); this.pending.unref(); };
|
|
28
|
+
for (const path of paths) {
|
|
29
|
+
const existing = this.watchers.get(path);
|
|
30
|
+
if (existing) { existing.references++; watched.push(path); continue; }
|
|
31
|
+
try {
|
|
32
|
+
const watcher = watch(path, { persistent: false }, notify); watcher.on("error", notify);
|
|
33
|
+
this.watchers.set(path, { watcher, references: 1 }); watched.push(path);
|
|
34
|
+
} catch { /* Bounded reconciliation also discovers newly created paths. */ }
|
|
35
|
+
}
|
|
36
|
+
const reconcile = () => {
|
|
37
|
+
let snapshot;
|
|
38
|
+
try { snapshot = read(); } catch { snapshot = { revision: "revoked", status: "revoked", roles: [], agents: [], diagnostics: [] }; }
|
|
39
|
+
if (snapshot.revision === revision) return;
|
|
40
|
+
revision = snapshot.revision;
|
|
41
|
+
emit({ ...snapshot, seq: ++seq });
|
|
42
|
+
};
|
|
43
|
+
revision = initial.revision;
|
|
44
|
+
this.observers.add(reconcile);
|
|
45
|
+
this.timer ??= setInterval(() => { for (const reconcile of this.observers) reconcile(); }, 1000);
|
|
46
|
+
this.timer.unref();
|
|
47
|
+
return { snapshot: { ...initial, seq }, close: () => {
|
|
48
|
+
this.observers.delete(reconcile);
|
|
49
|
+
for (const path of watched) { const entry = this.watchers.get(path); if (entry && --entry.references === 0) { entry.watcher.close(); this.watchers.delete(path); } }
|
|
50
|
+
if (!this.observers.size) { clearInterval(this.timer); this.timer = undefined; clearTimeout(this.pending); this.pending = undefined; }
|
|
51
|
+
} };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
connection() {
|
|
55
|
+
let registration: { cwd: string; sessionId: string; projectAccess: boolean; authority?: unknown } | undefined;
|
|
56
|
+
const location = () => {
|
|
57
|
+
if (!registration) throw new Error("catalog-unregistered: register a workspace first");
|
|
58
|
+
if (realpathSync(registration.cwd) !== registration.cwd) throw new Error("catalog-workspace-changed");
|
|
59
|
+
if (!registration.authority) throw new Error("catalog-authority-refused: register through the Pi host adapter");
|
|
60
|
+
const grant = this.admission.verify(registration.authority);
|
|
61
|
+
if (grant && (grant.cwd !== registration.cwd || grant.sessionId !== registration.sessionId)) throw new Error("catalog-scope-refused");
|
|
62
|
+
return { cwd: registration.cwd, userRoot: this.agentDir, projectTrusted: registration.projectAccess && grant.projectTrusted === true };
|
|
63
|
+
};
|
|
64
|
+
return (command: Record<string, unknown>) => {
|
|
65
|
+
if (command.type === "runtime_register_catalog") {
|
|
66
|
+
if (typeof command.cwd !== "string" || typeof command.sessionId !== "string" || !command.sessionId) throw new Error("Invalid catalog registration");
|
|
67
|
+
registration = { cwd: realpathSync(command.cwd), sessionId: command.sessionId, projectAccess: command.projectAccess !== "deny", authority: command.authority };
|
|
68
|
+
location();
|
|
69
|
+
return { cwd: registration.cwd, sessionId: registration.sessionId, projectTrusted: location().projectTrusted };
|
|
70
|
+
}
|
|
71
|
+
const loc = location();
|
|
72
|
+
if (command.type === "runtime_get_catalog_scope") {
|
|
73
|
+
if (command.scope !== "user" && command.scope !== "project") throw new Error("Invalid catalog scope");
|
|
74
|
+
return listScopedAgents(loc, command.scope);
|
|
75
|
+
}
|
|
76
|
+
const snapshot = loadCatalog(loc);
|
|
77
|
+
if (command.type === "runtime_get_catalog") {
|
|
78
|
+
const overlay = validateOverlay(command.overlay);
|
|
79
|
+
if (registration?.authority && command.overlay !== undefined) {
|
|
80
|
+
const grant = this.admission.verify(registration.authority);
|
|
81
|
+
const digest = overlayDigest(overlay);
|
|
82
|
+
if (digest !== grant.overlayDigest) throw new Error("catalog-overlay-refused");
|
|
83
|
+
}
|
|
84
|
+
const view = withAgentSessionSettings(snapshot, overlay);
|
|
85
|
+
return { ...view, roles: [...view.roles], agents: [...view.agents] };
|
|
86
|
+
}
|
|
87
|
+
if (command.type !== "runtime_edit_catalog") throw new Error("Unknown catalog command");
|
|
88
|
+
if (!registration?.authority) throw new Error("catalog-authority-refused: edits require a live host grant");
|
|
89
|
+
// No await between comparison and atomic domain write: cooperating clients
|
|
90
|
+
// serialize here. External writers do not participate in this transaction.
|
|
91
|
+
if (typeof command.expectedRevision !== "string" || command.expectedRevision !== snapshot.revision) throw new Error("catalog-conflict: content revision changed; reload before editing");
|
|
92
|
+
const id = command.catalogId;
|
|
93
|
+
if (typeof id !== "string") throw new Error("Invalid catalog id");
|
|
94
|
+
const entry = snapshot.roles.get(id) ?? snapshot.agents.get(id);
|
|
95
|
+
if (command.action === "reset-runtime" || command.action === "reset-definition") {
|
|
96
|
+
if (!entry) throw new Error("Catalog definition not found");
|
|
97
|
+
const reset = command.action === "reset-runtime" ? resetRuntimeToBundled : resetUserDefinition;
|
|
98
|
+
return reset({ ...loc, id, expectedPath: entry.path, expectedDigest: entry.contentDigest });
|
|
99
|
+
}
|
|
100
|
+
if (command.action === "preferences") {
|
|
101
|
+
return saveAgentSessionDefaults(snapshot, id, validateOverlay({ [id]: command.preferences }), loc);
|
|
102
|
+
}
|
|
103
|
+
if (command.action === "skills") {
|
|
104
|
+
if (!entry) throw new Error("Catalog definition not found");
|
|
105
|
+
const edit = command.edit as { mode?: string; paths?: unknown } | undefined;
|
|
106
|
+
if (!edit || !["inherit", "none", "explicit"].includes(edit.mode ?? "") || edit.mode === "explicit" && (!Array.isArray(edit.paths) || !edit.paths.every(p => typeof p === "string"))) throw new Error("Invalid skill edit");
|
|
107
|
+
return saveSkillExposure({ ...loc, entry: { id, winningSource: { path: entry.path, contentDigest: entry.contentDigest } } }, edit as import("./domain/catalog/catalog-schema.mjs").SkillExposureEdit);
|
|
108
|
+
}
|
|
109
|
+
if (command.action === "definition") {
|
|
110
|
+
if (command.scope !== "user" && command.scope !== "project") throw new Error("Catalog scope must be user or project; builtins are read-only");
|
|
111
|
+
if (command.scope === "project" && !loc.projectTrusted) throw new Error("catalog-untrusted: project writes refused");
|
|
112
|
+
if (typeof command.markdown !== "string") throw new Error("Definition must be Markdown");
|
|
113
|
+
const parsed = parseDefinition(command.markdown);
|
|
114
|
+
if (!parsed.definition || parsed.diagnostics.some(d => d.blocking) || parsed.definition.id !== id) throw new Error("Invalid catalog definition: " + parsed.diagnostics.map(d => d.message).join(" "));
|
|
115
|
+
return saveDefinition({ ...loc, definition: parsed.definition, scope: command.scope, replace: command.replace === true });
|
|
116
|
+
}
|
|
117
|
+
throw new Error("Unknown catalog edit action");
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function validateOverlay(value: unknown): import("./domain/catalog/agent-session-settings.mjs").AgentSessionOverrides {
|
|
123
|
+
if (value === undefined) return {};
|
|
124
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid catalog overlay");
|
|
125
|
+
for (const [id, patch] of Object.entries(value)) {
|
|
126
|
+
if (!/^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id) || !patch || typeof patch !== "object" || Array.isArray(patch)) throw new Error("Invalid catalog overlay");
|
|
127
|
+
for (const [key, item] of Object.entries(patch)) {
|
|
128
|
+
if (key === "model" ? item !== null && (typeof item !== "string" || !/^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(item))
|
|
129
|
+
: key !== "effort" || item !== null && !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(item as string)) throw new Error("Invalid catalog preference");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return value as import("./domain/catalog/agent-session-settings.mjs").AgentSessionOverrides;
|
|
133
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createAssignmentReader(path: string): { revision(): string; read(owner: any): any; conversationRevisions(): Map<string, string> | undefined; close(): void };
|
|
1
|
+
export function createAssignmentReader(path: string): { revision(): string; beginSnapshot(): { revision: string; release(): void }; read(owner: any): any; conversationRevisions(): Map<string, string> | undefined; close(): void };
|
|
@@ -47,6 +47,7 @@ export function readAssignmentWaits(path, owner, connection) {
|
|
|
47
47
|
export function createAssignmentReader(path) {
|
|
48
48
|
let db;
|
|
49
49
|
let identity;
|
|
50
|
+
let snapshot = false;
|
|
50
51
|
const statements = new Map();
|
|
51
52
|
return {
|
|
52
53
|
revision() {
|
|
@@ -54,6 +55,7 @@ export function createAssignmentReader(path) {
|
|
|
54
55
|
const stat = statSync(path, { bigint: true });
|
|
55
56
|
const next = `${stat.dev}:${stat.ino}`;
|
|
56
57
|
if (identity !== next) {
|
|
58
|
+
if (snapshot) throw new Error("Coordinator identity changed during observation");
|
|
57
59
|
db?.close();
|
|
58
60
|
db = undefined;
|
|
59
61
|
statements.clear();
|
|
@@ -63,6 +65,21 @@ export function createAssignmentReader(path) {
|
|
|
63
65
|
db ??= new DatabaseSync(path, { readOnly: true });
|
|
64
66
|
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
65
67
|
},
|
|
68
|
+
beginSnapshot() {
|
|
69
|
+
this.revision();
|
|
70
|
+
if (snapshot) throw new Error("Coordinator snapshot already open");
|
|
71
|
+
db.exec("BEGIN");
|
|
72
|
+
snapshot = true;
|
|
73
|
+
const release = () => {
|
|
74
|
+
if (!snapshot) return;
|
|
75
|
+
try { db.exec("ROLLBACK"); } finally { snapshot = false; }
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
// Pin the WAL read view before recording its revision; other writers keep advancing.
|
|
79
|
+
db.prepare("SELECT count(*) FROM sqlite_schema").get();
|
|
80
|
+
return { revision: this.revision(), release };
|
|
81
|
+
} catch (error) { release(); throw error; }
|
|
82
|
+
},
|
|
66
83
|
read(owner) {
|
|
67
84
|
try {
|
|
68
85
|
this.revision();
|
|
@@ -98,6 +115,6 @@ export function createAssignmentReader(path) {
|
|
|
98
115
|
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
99
116
|
} catch { return undefined; }
|
|
100
117
|
},
|
|
101
|
-
close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
118
|
+
close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
102
119
|
};
|
|
103
120
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CatalogDefinition, type PortablePreferences, type ThinkingLevel } from "./catalog-schema.mjs";
|
|
2
|
+
import { type CatalogSnapshot, type LoadCatalogInput, type SaveResult } from "./catalog-store.mjs";
|
|
3
|
+
export declare const AGENT_SESSION_SETTINGS_ENTRY = "pi-better-subagents-agent-settings";
|
|
4
|
+
export type AgentSettingKey = "model" | "effort";
|
|
5
|
+
export type AgentSessionOverrides = Readonly<Record<string, Readonly<{
|
|
6
|
+
model?: string | null;
|
|
7
|
+
effort?: ThinkingLevel | null;
|
|
8
|
+
}>>>;
|
|
9
|
+
export interface AgentSessionContext {
|
|
10
|
+
sessionManager?: {
|
|
11
|
+
getBranch?(): readonly unknown[];
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface AgentSessionSettings {
|
|
15
|
+
restore(ctx: AgentSessionContext): void;
|
|
16
|
+
snapshot(): AgentSessionOverrides;
|
|
17
|
+
change(id: string, key: AgentSettingKey, value: string | null): void;
|
|
18
|
+
reset(id: string): void;
|
|
19
|
+
clear(): void;
|
|
20
|
+
}
|
|
21
|
+
/** The host must restore from the current context before constructing catalog hosts. */
|
|
22
|
+
export declare function createAgentSessionSettings(pi: {
|
|
23
|
+
appendEntry(customType: string, data: unknown): void;
|
|
24
|
+
}): AgentSessionSettings;
|
|
25
|
+
/** Copy only preferences; never repair or bypass a catalog validation failure. */
|
|
26
|
+
export declare function sessionPreferences(definition: CatalogDefinition, settings?: AgentSessionOverrides, saved?: AgentSessionOverrides): PortablePreferences;
|
|
27
|
+
/** A launch batch retains this immutable overlay, even if the UI changes later. */
|
|
28
|
+
export declare function withAgentSessionSettings(snapshot: CatalogSnapshot, settings?: AgentSessionOverrides): CatalogSnapshot;
|
|
29
|
+
/** Save selected preference edits without copying or rewriting Markdown definitions. */
|
|
30
|
+
export declare function saveAgentSessionDefaults(snapshot: CatalogSnapshot, id: string, settings: AgentSessionOverrides, location: LoadCatalogInput): SaveResult;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/agent-session-settings.ts. Do not edit directly.
|
|
2
|
+
/** Branch-local catalog preferences. Null removes a definition's own value. */
|
|
3
|
+
import { mkdirSync } from "node:fs";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { EFFORT_LEVELS } from "./catalog-schema.mjs";
|
|
6
|
+
import { contentDigest, projectCatalogPaths, userCatalogPaths } from "./catalog-store.mjs";
|
|
7
|
+
import { writeCatalogPreferences } from "./catalog-preferences.mjs";
|
|
8
|
+
export const AGENT_SESSION_SETTINGS_ENTRY = "pi-better-subagents-agent-settings";
|
|
9
|
+
function validId(id) {
|
|
10
|
+
return typeof id === "string" && /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id);
|
|
11
|
+
}
|
|
12
|
+
function valid(id, key, value) {
|
|
13
|
+
return validId(id) &&
|
|
14
|
+
(key === "model" || key === "effort") && (value === null || typeof value === "string" &&
|
|
15
|
+
(key === "model" ? /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(value)
|
|
16
|
+
: EFFORT_LEVELS.includes(value)));
|
|
17
|
+
}
|
|
18
|
+
/** The host must restore from the current context before constructing catalog hosts. */
|
|
19
|
+
export function createAgentSessionSettings(pi) {
|
|
20
|
+
let overrides = Object.freeze({});
|
|
21
|
+
const apply = (id, key, value) => {
|
|
22
|
+
overrides = Object.freeze({ ...overrides, [id]: Object.freeze({ ...overrides[id], [key]: value }) });
|
|
23
|
+
};
|
|
24
|
+
const reset = (id) => {
|
|
25
|
+
const next = { ...overrides };
|
|
26
|
+
delete next[id];
|
|
27
|
+
overrides = Object.freeze(next);
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
snapshot: () => overrides,
|
|
31
|
+
clear() { overrides = Object.freeze({}); },
|
|
32
|
+
restore(ctx) {
|
|
33
|
+
overrides = Object.freeze({});
|
|
34
|
+
const branch = ctx.sessionManager?.getBranch?.();
|
|
35
|
+
if (!Array.isArray(branch))
|
|
36
|
+
return;
|
|
37
|
+
for (const entry of branch) {
|
|
38
|
+
if (!entry || entry.type !== "custom" || entry.customType !== AGENT_SESSION_SETTINGS_ENTRY)
|
|
39
|
+
continue;
|
|
40
|
+
const data = entry.data;
|
|
41
|
+
if (data?.version !== 1)
|
|
42
|
+
continue;
|
|
43
|
+
if (data.kind === "reset") {
|
|
44
|
+
if (validId(data.id))
|
|
45
|
+
reset(data.id);
|
|
46
|
+
}
|
|
47
|
+
else if (valid(data.id, data.key, data.value)) {
|
|
48
|
+
apply(data.id, data.key, data.value);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
change(id, key, value) {
|
|
53
|
+
if (!valid(id, key, value))
|
|
54
|
+
throw new Error("Choose a catalog id and a valid model or effort. Nothing changed.");
|
|
55
|
+
// Append first: a persistence failure must not become an ephemeral edit.
|
|
56
|
+
pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, id, key, value });
|
|
57
|
+
apply(id, key, value);
|
|
58
|
+
},
|
|
59
|
+
reset(id) {
|
|
60
|
+
if (!validId(id))
|
|
61
|
+
throw new Error("Choose a valid catalog id. Nothing changed.");
|
|
62
|
+
// Append first, just like changes: failed persistence leaves the session intact.
|
|
63
|
+
pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, kind: "reset", id });
|
|
64
|
+
reset(id);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Copy only preferences; never repair or bypass a catalog validation failure. */
|
|
69
|
+
export function sessionPreferences(definition, settings = {}, saved = {}) {
|
|
70
|
+
const own = { ...(definition.kind === "role" ? definition.defaults : definition.overrides) };
|
|
71
|
+
const patch = { ...saved[definition.id], ...settings[definition.id] };
|
|
72
|
+
for (const key of ["model", "effort"]) {
|
|
73
|
+
if (!patch || !Object.hasOwn(patch, key))
|
|
74
|
+
continue;
|
|
75
|
+
if (patch[key] === null)
|
|
76
|
+
delete own[key];
|
|
77
|
+
else if (patch[key] !== undefined)
|
|
78
|
+
Object.assign(own, { [key]: patch[key] });
|
|
79
|
+
}
|
|
80
|
+
return own;
|
|
81
|
+
}
|
|
82
|
+
/** A launch batch retains this immutable overlay, even if the UI changes later. */
|
|
83
|
+
export function withAgentSessionSettings(snapshot, settings) {
|
|
84
|
+
if (!settings || Object.keys(settings).length === 0)
|
|
85
|
+
return snapshot;
|
|
86
|
+
const ordered = Object.fromEntries(Object.keys(settings).sort().map((id) => [id, Object.freeze({
|
|
87
|
+
...(Object.hasOwn(settings[id], "model") ? { model: settings[id].model } : {}),
|
|
88
|
+
...(Object.hasOwn(settings[id], "effort") ? { effort: settings[id].effort } : {}),
|
|
89
|
+
})]));
|
|
90
|
+
const digest = contentDigest(JSON.stringify([snapshot.digest, ordered]));
|
|
91
|
+
return Object.freeze({ ...snapshot, digest, revision: digest, sessionSettings: Object.freeze(ordered) });
|
|
92
|
+
}
|
|
93
|
+
/** Save selected preference edits without copying or rewriting Markdown definitions. */
|
|
94
|
+
export function saveAgentSessionDefaults(snapshot, id, settings, location) {
|
|
95
|
+
const entry = snapshot.roles.get(id) ?? snapshot.agents.get(id);
|
|
96
|
+
if (!entry?.definition || !entry.structurallyValid || entry.duplicate) {
|
|
97
|
+
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: `Cannot save ${id}: repair the catalog definition first. Session edits are unchanged.`, blocking: true, structural: false }] };
|
|
98
|
+
}
|
|
99
|
+
const scope = entry.scope === "project" || Object.values(snapshot.preferenceSources?.[id] ?? {}).some(source => source.scope === "project") ? "project" : "user";
|
|
100
|
+
if (scope === "project" && !location.projectTrusted) {
|
|
101
|
+
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: "Project catalog preferences require a trusted project. Nothing changed.", blocking: true, structural: false }] };
|
|
102
|
+
}
|
|
103
|
+
const root = scope === "project" ? projectCatalogPaths(location.cwd, location.projectConfigDirName).root : userCatalogPaths(location.userRoot).root;
|
|
104
|
+
try {
|
|
105
|
+
mkdirSync(dirname(root), { recursive: true, mode: 0o700 });
|
|
106
|
+
const saved = writeCatalogPreferences(root, id, current => ({ ...current, ...settings[id] }));
|
|
107
|
+
return { ok: true, path: saved.path, scope, diagnostics: [] };
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: error instanceof Error ? error.message : String(error), blocking: true, structural: false }] };
|
|
111
|
+
}
|
|
112
|
+
}
|