pi-better-server 0.2.4 → 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 +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- 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/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable records and public result types for the detached local supervisor.
|
|
3
|
+
*
|
|
4
|
+
* Scope: local processes and local command watches only. The supervisor is the
|
|
5
|
+
* slice-2 runtime from [ADR 0020](../../../../docs/adr/0020-observed-waits-retain-an-owner.md)
|
|
6
|
+
* and [the observed-waits design](../../../../docs/plans/observed-waits-design.md):
|
|
7
|
+
* execution and terminal evidence survive the process that launched them. It
|
|
8
|
+
* does not implement the coordinator store, dependency waits, continuation or
|
|
9
|
+
* any remote adapter, and it never widens permission: callers pass a command
|
|
10
|
+
* that was already admitted and confined.
|
|
11
|
+
*
|
|
12
|
+
* Environment values are never written to a durable record. A record may name
|
|
13
|
+
* that the launch environment is inherited, and only the runner process carries
|
|
14
|
+
* the actual values.
|
|
15
|
+
*/
|
|
16
|
+
/** Bumped when a record shape changes in a way an older reader must refuse. */
|
|
17
|
+
export const SUPERVISOR_RECORD_VERSION = 1;
|
|
18
|
+
/** Bumped with the runner's own behaviour, not the record schema. */
|
|
19
|
+
export const SUPERVISOR_RUNNER_VERSION = "2";
|
|
20
|
+
export const SUPERVISOR_TASK_ID_PREFIX = "bgs_";
|
|
21
|
+
export const SUPERVISOR_TASK_ID_PATTERN = /^bgs_[0-9a-f]{20}$/;
|
|
22
|
+
/** Mirror of the Background tasks watch defaults, so a supervised watch keeps them. */
|
|
23
|
+
export const DEFAULT_WATCH_INTERVAL_MS = 30_000;
|
|
24
|
+
export const DEFAULT_WATCH_TIMEOUT_MS = 15 * 60_000;
|
|
25
|
+
/** Per-stream log cap; mirrors the Background tasks task-log retention default. */
|
|
26
|
+
export const DEFAULT_MAX_LOG_BYTES = 4 * 1024 * 1024;
|
|
27
|
+
/** How much of the last check/output is kept in the durable terminal record. */
|
|
28
|
+
export const DEFAULT_TERMINAL_TAIL_BYTES = 8 * 1024;
|
|
29
|
+
/** How long a launch may exist before an unclaimed launch is reported lost. */
|
|
30
|
+
export const DEFAULT_CLAIM_GRACE_MS = 30_000;
|
|
31
|
+
/** How long `start` waits for the runner's durable claim before returning. */
|
|
32
|
+
export const DEFAULT_CLAIM_WAIT_MS = 2_000;
|
|
33
|
+
/** How long `stop` waits for runner-attested evidence before escalating. */
|
|
34
|
+
export const DEFAULT_STOP_WAIT_MS = 5_000;
|
|
35
|
+
/** Poll cadence for stop requests, in the runner and in the caller's wait loops. */
|
|
36
|
+
export const SUPERVISOR_POLL_MS = 50;
|
|
37
|
+
/** SIGTERM-to-SIGKILL grace for a timed-out or stopped command group. */
|
|
38
|
+
export const SUPERVISOR_TERMINATION_GRACE_MS = 2_000;
|
|
39
|
+
/** How long group cleanup may run before it must be reported as unproven. */
|
|
40
|
+
export const SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS = 7_000;
|
|
41
|
+
/** Cross-process state fence: how long a waiter holds on before erroring (never steals). */
|
|
42
|
+
export const SUPERVISOR_FENCE_WAIT_MS = 5_000;
|
|
43
|
+
/**
|
|
44
|
+
* `inspect` is an observation path: it waits only briefly for the fence and then
|
|
45
|
+
* reports `fenceBusy` rather than blocking a status loop on a wedged holder.
|
|
46
|
+
*/
|
|
47
|
+
export const SUPERVISOR_INSPECT_FENCE_WAIT_MS = 250;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Generated canonical terminal publication. Do not edit directly.
|
|
2
|
+
import { existsSync, statSync } from "node:fs";
|
|
3
|
+
function terminalOutcome(status) {
|
|
4
|
+
switch (status) {
|
|
5
|
+
case "succeeded": return "succeeded";
|
|
6
|
+
case "cancelled": return "cancelled";
|
|
7
|
+
case "lost": return "lost";
|
|
8
|
+
default: return "failed";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function evidenceFor(inspection) {
|
|
12
|
+
const paths = inspection.logs;
|
|
13
|
+
const evidence = [];
|
|
14
|
+
const result = inspection.result;
|
|
15
|
+
const lost = inspection.lost;
|
|
16
|
+
const terminalRef = result ? "result.json" : "lost.json";
|
|
17
|
+
const summary = result
|
|
18
|
+
? `status=${result.status} exit=${result.exitCode ?? "null"} timedOut=${result.timedOut ? "true" : "false"}${result.groupCleanup ? ` groupCleanup=${result.groupCleanup}` : ""}`
|
|
19
|
+
: `status=lost detailLost=true`;
|
|
20
|
+
evidence.push({
|
|
21
|
+
operationId: "",
|
|
22
|
+
terminalRevision: 0,
|
|
23
|
+
kind: "terminal-record",
|
|
24
|
+
ref: terminalRef,
|
|
25
|
+
summary,
|
|
26
|
+
detailLost: !result,
|
|
27
|
+
});
|
|
28
|
+
for (const [label, path] of [["stdout", paths.stdout], ["stderr", paths.stderr]]) {
|
|
29
|
+
try {
|
|
30
|
+
const size = existsSync(path) ? statSync(path).size : 0;
|
|
31
|
+
if (size <= 0)
|
|
32
|
+
continue;
|
|
33
|
+
evidence.push({
|
|
34
|
+
operationId: "",
|
|
35
|
+
terminalRevision: 0,
|
|
36
|
+
kind: "log",
|
|
37
|
+
ref: path,
|
|
38
|
+
summary: `${label} retained (${size} bytes)`,
|
|
39
|
+
detailLost: false,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch { /* a reclaimed log costs detail, never the outcome */ }
|
|
43
|
+
}
|
|
44
|
+
return evidence;
|
|
45
|
+
}
|
|
46
|
+
/** Shared terminal publication contract for the host and fixed server cancel adapter. */
|
|
47
|
+
export function supervisorTerminalPublication(operation, inspection, refs = evidenceFor(inspection)) {
|
|
48
|
+
const status = inspection.status;
|
|
49
|
+
const outcome = terminalOutcome(status);
|
|
50
|
+
return {
|
|
51
|
+
operationId: operation.operationId,
|
|
52
|
+
eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
|
|
53
|
+
outcome, owner: operation.owner,
|
|
54
|
+
evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
|
|
55
|
+
...(outcome === "lost" ? { detailLost: true } : {}),
|
|
56
|
+
reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/catalog-overlay.ts. Do not edit directly.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
/** Canonical host/server credential binding for branch-local Catalog preferences. */
|
|
4
|
+
export function overlayDigest(value = {}) {
|
|
5
|
+
const canonical = Object.fromEntries(Object.keys(value).sort().map(id => [id,
|
|
6
|
+
Object.fromEntries(Object.entries(value[id]).sort(([a], [b]) => a.localeCompare(b))),
|
|
7
|
+
]));
|
|
8
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
9
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type ThinkingLevel } from "./thinking.mjs";
|
|
2
|
+
export type CatalogPreference = Readonly<{
|
|
3
|
+
bundled?: true;
|
|
4
|
+
model?: string | null;
|
|
5
|
+
effort?: ThinkingLevel | null;
|
|
6
|
+
}>;
|
|
7
|
+
export type CatalogPreferences = Readonly<Record<string, CatalogPreference>>;
|
|
8
|
+
export declare function readCatalogPreferences(root: string): {
|
|
9
|
+
settings: CatalogPreferences;
|
|
10
|
+
digest: string;
|
|
11
|
+
};
|
|
12
|
+
/** Replace only this id's own preferences; null explicitly clears a definition value. */
|
|
13
|
+
export declare function writeCatalogPreferences(root: string, id: string, value: CatalogPreference | ((current: CatalogPreference) => CatalogPreference)): {
|
|
14
|
+
path: string;
|
|
15
|
+
settings: CatalogPreferences;
|
|
16
|
+
digest: string;
|
|
17
|
+
};
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/catalog-preferences.ts. Do not edit directly.
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { THINKING_LEVELS } from "./thinking.mjs";
|
|
7
|
+
const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
|
|
8
|
+
const MODEL = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
9
|
+
function object(value, label) {
|
|
10
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
11
|
+
throw new Error(`${label} must be a JSON object.`);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
function preferences(id, value) {
|
|
15
|
+
if (typeof id !== "string" || !ID.test(id))
|
|
16
|
+
throw new Error(`Invalid catalog id ${JSON.stringify(id)}.`);
|
|
17
|
+
const record = object(value, `Preferences for ${id}`);
|
|
18
|
+
for (const [key, item] of Object.entries(record)) {
|
|
19
|
+
if (key !== "bundled" && key !== "model" && key !== "effort")
|
|
20
|
+
throw new Error(`Unknown preference ${key} for ${id}.`);
|
|
21
|
+
if (key === "bundled" ? item !== true : item !== null && (typeof item !== "string" || (key === "model" ? !MODEL.test(item)
|
|
22
|
+
: !THINKING_LEVELS.includes(item)))) {
|
|
23
|
+
throw new Error(`Invalid ${key} preference for ${id}: ${JSON.stringify(item)}.`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return Object.freeze({
|
|
27
|
+
...(Object.hasOwn(record, "bundled") ? { bundled: true } : {}),
|
|
28
|
+
...(Object.hasOwn(record, "model") ? { model: record.model } : {}),
|
|
29
|
+
...(Object.hasOwn(record, "effort") ? { effort: record.effort } : {}),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function snapshot(values) {
|
|
33
|
+
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]])));
|
|
34
|
+
return { settings, digest: createHash("sha256").update(JSON.stringify(settings)).digest("hex") };
|
|
35
|
+
}
|
|
36
|
+
function stat(path) {
|
|
37
|
+
try {
|
|
38
|
+
return lstatSync(path);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error.code === "ENOENT")
|
|
42
|
+
return undefined;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function checkRoot(root) {
|
|
47
|
+
const info = stat(root);
|
|
48
|
+
if (!info)
|
|
49
|
+
return false;
|
|
50
|
+
if (info.isSymbolicLink())
|
|
51
|
+
throw new Error(`Refusing symlink catalog directory ${root}.`);
|
|
52
|
+
if (!info.isDirectory())
|
|
53
|
+
throw new Error(`Catalog root ${root} must be a directory.`);
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
function checkFile(path) {
|
|
57
|
+
const info = stat(path);
|
|
58
|
+
if (!info)
|
|
59
|
+
return false;
|
|
60
|
+
if (info.isSymbolicLink())
|
|
61
|
+
throw new Error(`Refusing symlink catalog settings file ${path}.`);
|
|
62
|
+
if (!info.isFile())
|
|
63
|
+
throw new Error(`Catalog settings ${path} must be a regular file.`);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
export function readCatalogPreferences(root) {
|
|
67
|
+
root = resolve(root);
|
|
68
|
+
const path = join(root, "settings.json");
|
|
69
|
+
try {
|
|
70
|
+
if (!checkRoot(root) || !checkFile(path))
|
|
71
|
+
return snapshot({});
|
|
72
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
73
|
+
let data;
|
|
74
|
+
try {
|
|
75
|
+
if (!fstatSync(fd).isFile())
|
|
76
|
+
throw new Error("Settings must be a regular file.");
|
|
77
|
+
data = object(JSON.parse(readFileSync(fd, "utf8")), "Catalog settings");
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
closeSync(fd);
|
|
81
|
+
}
|
|
82
|
+
if (data.version !== 1 || !Object.hasOwn(data, "defaults") ||
|
|
83
|
+
Object.keys(data).some(key => key !== "version" && key !== "defaults")) {
|
|
84
|
+
throw new Error("Expected only version: 1 and defaults in catalog settings.");
|
|
85
|
+
}
|
|
86
|
+
const settings = Object.fromEntries(Object.entries(object(data.defaults, "Catalog defaults"))
|
|
87
|
+
.map(([id, value]) => [id, preferences(id, value)]));
|
|
88
|
+
return snapshot(settings);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw new Error(`Cannot read catalog preferences at ${path}: ${error.message}`, { cause: error });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function acquire(path) {
|
|
95
|
+
// Read-only catalog consumers (including the portable CLI) need no lock adapter.
|
|
96
|
+
const lockfile = createRequire(import.meta.url)("proper-lockfile");
|
|
97
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
98
|
+
try {
|
|
99
|
+
return lockfile.lockSync(path, { realpath: false });
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.code !== "ELOCKED" || attempt === 99)
|
|
103
|
+
throw error;
|
|
104
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
throw new Error(`Cannot lock catalog settings at ${path}.`);
|
|
108
|
+
}
|
|
109
|
+
/** Replace only this id's own preferences; null explicitly clears a definition value. */
|
|
110
|
+
export function writeCatalogPreferences(root, id, value) {
|
|
111
|
+
// Validate literal input before touching disk; updater callbacks run under the lock.
|
|
112
|
+
const selected = typeof value === "function" ? (preferences(id, {}), undefined) : preferences(id, value);
|
|
113
|
+
root = resolve(root);
|
|
114
|
+
const path = join(root, "settings.json");
|
|
115
|
+
let release;
|
|
116
|
+
let pending;
|
|
117
|
+
try {
|
|
118
|
+
if (!checkRoot(root)) {
|
|
119
|
+
// Do not create the caller's user/project configuration directories.
|
|
120
|
+
try {
|
|
121
|
+
mkdirSync(root, { mode: 0o700 });
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error.code !== "EEXIST")
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
checkRoot(root);
|
|
128
|
+
}
|
|
129
|
+
checkFile(path);
|
|
130
|
+
release = acquire(path);
|
|
131
|
+
const settings = { ...readCatalogPreferences(root).settings };
|
|
132
|
+
const next = selected ?? preferences(id, value(settings[id] ?? Object.freeze({})));
|
|
133
|
+
if (Object.keys(next).length)
|
|
134
|
+
settings[id] = next;
|
|
135
|
+
else
|
|
136
|
+
delete settings[id];
|
|
137
|
+
const result = snapshot(settings);
|
|
138
|
+
pending = join(root, `.settings.json.${randomUUID()}.tmp`);
|
|
139
|
+
const fd = openSync(pending, "wx", 0o600);
|
|
140
|
+
try {
|
|
141
|
+
writeFileSync(fd, `${JSON.stringify({ version: 1, defaults: result.settings }, null, 2)}\n`);
|
|
142
|
+
fsyncSync(fd);
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
closeSync(fd);
|
|
146
|
+
}
|
|
147
|
+
checkRoot(root);
|
|
148
|
+
checkFile(path);
|
|
149
|
+
renameSync(pending, path);
|
|
150
|
+
return { path, ...result };
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
throw new Error(`Cannot save catalog preferences at ${path}: ${error.message}`, { cause: error });
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
try {
|
|
157
|
+
if (pending)
|
|
158
|
+
rmSync(pending, { force: true });
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
release?.();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|