pi-better-subagents 0.32.7 → 0.34.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/README.md +13 -0
- package/agent-catalog.mjs +24 -0
- package/agent-commands.ts +71 -4
- package/agent-inspection.ts +2 -1
- package/agents-catalog-tool.ts +8 -1
- package/assignment-outcomes.ts +14 -3
- package/assignment-projection.mjs +12 -4
- package/assignment-report.ts +92 -0
- package/catalog-host-admission.ts +69 -0
- package/catalog-overlay.ts +10 -0
- package/catalog-runtime.ts +10 -2
- package/catalog-store.ts +23 -0
- package/catalog-ui.ts +26 -10
- package/child-operations.ts +2 -0
- package/child-ownership.ts +1 -1
- package/docs/agent-catalog-operations.md +38 -0
- package/health-observation.ts +9 -4
- package/index.ts +154 -84
- package/launch-abort.ts +21 -0
- package/list.mjs +1 -1
- package/navigator.mjs +2 -1
- package/operation-bridge-types.ts +18 -1
- package/output-payload.ts +2 -0
- package/package.json +4 -2
- package/parse.ts +7 -6
- package/registry.ts +4 -2
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -0
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -0
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -0
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -0
- package/runtime-client/scripts/private-runtime/format.mjs +90 -0
- package/runtime-client/src/daemon-owner.mjs +218 -0
- package/runtime-client/src/runtime/client.mjs +130 -0
- package/runtime-client/src/runtime/root.mjs +41 -0
- package/runtime-client/src/runtime/socket.mjs +9 -0
- package/runtime-client/src/runtime/status-cli.mjs +14 -0
- package/runtime-client/src/runtime/work-client.mjs +102 -0
- package/runtime-client/src/startup/artifact.mjs +76 -0
- package/runtime-client/src/startup/install.mjs +184 -0
- package/runtime-client/src/startup/managed-types.mjs +1 -0
- package/runtime-client/src/startup/runtime.mjs +120 -0
- package/session-store.ts +85 -30
- package/shared-catalog.ts +69 -0
- package/shared-harness-settings.ts +4 -2
- package/shared-log-utils.ts +18 -7
- package/shared-navigator.ts +16 -4
- package/shared-operation-coordinator/assignment-observation.mjs +80 -3
- package/shared-operation-coordinator/index.ts +2 -0
- package/shared-operation-coordinator/src/discovery.ts +9 -0
- package/shared-operation-coordinator/src/errors.ts +2 -0
- package/shared-operation-coordinator/src/operations.ts +6 -4
- package/shared-operation-coordinator/src/result-supervision.ts +128 -0
- package/shared-operation-coordinator/src/schema.ts +39 -1
- package/shared-operation-coordinator/src/store.ts +55 -0
- package/shared-operation-coordinator/src/task-cancellation.ts +224 -0
- package/shared-operation-coordinator/src/types.ts +6 -0
- package/shared-work-client.d.mts +12 -0
- package/shared-work-client.mjs +102 -0
- package/skill-picker.ts +6 -2
- package/tools.ts +39 -2
- package/work-observation.ts +177 -0
- package/worker-operations-host.ts +3 -0
- package/worker-waits.ts +50 -13
package/README.md
CHANGED
|
@@ -6,6 +6,19 @@
|
|
|
6
6
|
|
|
7
7
|
Use `pi-better-subagents` when you want Pi to launch independent agent work without blocking the current conversation. Each subagent runs in its own `pi -p` child process, reports back when finished, and keeps durable logs for later inspection.
|
|
8
8
|
|
|
9
|
+
## Runtime Status
|
|
10
|
+
|
|
11
|
+
Run `pi-subagents-runtime-status` to ensure the manifest-pinned local server and
|
|
12
|
+
print its canonical agent root, build, Node version, instance and capabilities as JSON.
|
|
13
|
+
This command does not create a hosted Pi session or require Harness.
|
|
14
|
+
The first use installs a verified private Node 24 and locked server dependencies.
|
|
15
|
+
Set `PI_OFFLINE=1` to require the cached runtime without downloads.
|
|
16
|
+
`PI_CODING_AGENT_DIR` selects the agent root; `PI_SERVER_DIR` selects the initial
|
|
17
|
+
transport directory. Later calls for the same canonical root reuse the registered
|
|
18
|
+
transport, including calls from Background Tasks or another package installation.
|
|
19
|
+
An incompatible or unhealthy live owner is an error, not a reason to replace it.
|
|
20
|
+
The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
|
|
21
|
+
|
|
9
22
|
## Screenshots
|
|
10
23
|
|
|
11
24
|
<p><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-subagents.png" alt="pi-better-subagents rendered in Pi" width="49%" /><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/overview/pi-better-subagents.png" alt="pi-better-subagents package overview" width="49%" /></p>
|
package/agent-catalog.mjs
CHANGED
|
@@ -3,6 +3,30 @@ import { readFileSync, realpathSync } from 'node:fs';
|
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
|
|
5
5
|
export async function runCli(args = process.argv.slice(2), input = () => readFileSync(0, 'utf8')) {
|
|
6
|
+
if (args[0] === 'list' || args[0] === 'inspect') {
|
|
7
|
+
let remote, closeHost;
|
|
8
|
+
try {
|
|
9
|
+
if (args.length > (args[0] === 'list' ? 1 : 2) || args[0] === 'inspect' && !args[1]) throw new Error('Usage: pi-agent-catalog list | inspect <id>');
|
|
10
|
+
const { register } = await import('tsx/esm/api');
|
|
11
|
+
register();
|
|
12
|
+
const { openSharedCatalog } = await import('./shared-catalog.ts');
|
|
13
|
+
const { noteCatalogHostContext, closeCatalogHost } = await import('./catalog-host-admission.ts');
|
|
14
|
+
closeHost = closeCatalogHost;
|
|
15
|
+
const { getAgentDir, ProjectTrustStore, SettingsManager } = await import('@earendil-works/pi-coding-agent');
|
|
16
|
+
const cwd = realpathSync(process.cwd());
|
|
17
|
+
const settings = SettingsManager.create(cwd, getAgentDir(), { projectTrusted: false });
|
|
18
|
+
if (settings.drainErrors().length) throw new Error('Cannot verify CLI project trust');
|
|
19
|
+
noteCatalogHostContext({ cwd, isProjectTrusted: () => new ProjectTrustStore(getAgentDir()).get(cwd) ?? settings.getDefaultProjectTrust() === 'always' }, () => ({}));
|
|
20
|
+
const { presentCatalog, presentCatalogEntry } = await import('./agent-inspection.ts');
|
|
21
|
+
remote = await openSharedCatalog(process.cwd());
|
|
22
|
+
const snapshot = await remote.get();
|
|
23
|
+
const view = args[0] === 'list' ? presentCatalog(snapshot) : presentCatalogEntry(snapshot, args[1]);
|
|
24
|
+
console.log(JSON.stringify(view));
|
|
25
|
+
closeCatalogHost();
|
|
26
|
+
return view.found === false ? 2 : 0;
|
|
27
|
+
} catch (error) { console.error(`pi-agent-catalog: ${error.message}`); return 2; }
|
|
28
|
+
finally { remote?.close(); closeHost?.(); }
|
|
29
|
+
}
|
|
6
30
|
if (args.includes('--help')) {
|
|
7
31
|
console.log('pi-agent-catalog [resolve-workers] < request.json\nResolves shared agent roles against explicit host model and effort capabilities. No workers are launched.');
|
|
8
32
|
return 0;
|
package/agent-commands.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
EFFORT_LEVELS,
|
|
19
19
|
canonicalRoleId,
|
|
20
20
|
parseDefinition,
|
|
21
|
+
serializeDefinition,
|
|
21
22
|
shortRoleName,
|
|
22
23
|
type AgentDefinition,
|
|
23
24
|
type Diagnostic,
|
|
@@ -27,6 +28,7 @@ import {
|
|
|
27
28
|
} from "./catalog-schema.ts";
|
|
28
29
|
import {
|
|
29
30
|
createDefinition,
|
|
31
|
+
catalogSnapshotFromWire,
|
|
30
32
|
defaultUserRoot,
|
|
31
33
|
loadCatalog,
|
|
32
34
|
projectCatalogPaths,
|
|
@@ -53,6 +55,7 @@ import { resolveRoleAssignment } from "./role-assignment.ts";
|
|
|
53
55
|
import { saveAgentSessionDefaults, withAgentSessionSettings, type AgentSessionOverrides, type AgentSessionSettings } from "./agent-session-settings.ts";
|
|
54
56
|
import { saveSkillExposure } from "./catalog-skill-edits.ts";
|
|
55
57
|
import type { DiscoveredSkill } from "./skill-picker.ts";
|
|
58
|
+
import { openSharedCatalog } from "./shared-catalog.ts";
|
|
56
59
|
|
|
57
60
|
const MODEL_PATTERN = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
58
61
|
const TIER_PATTERN = /^[a-z][a-z0-9-]{0,32}$/;
|
|
@@ -68,6 +71,9 @@ const USAGE = [
|
|
|
68
71
|
].join("\n");
|
|
69
72
|
|
|
70
73
|
export interface AgentCommandDeps {
|
|
74
|
+
sharedCatalog?: boolean;
|
|
75
|
+
/** Invocation-local server state; never reused across workspaces or branches. */
|
|
76
|
+
sharedState?: { snapshot: CatalogSnapshot; edit: (edit: Record<string, unknown>) => Promise<any>; scopedAgents: (scope: "user" | "project") => Promise<ReturnType<typeof listScopeAgents>>; beginEdit?: (id: string) => void; onChange?: (changed: () => void) => void; revoked?: boolean };
|
|
71
77
|
userRoot?: string;
|
|
72
78
|
bundledRoot?: string;
|
|
73
79
|
projectConfigDirName?: string;
|
|
@@ -127,6 +133,7 @@ export interface AgentCommandResult {
|
|
|
127
133
|
}
|
|
128
134
|
|
|
129
135
|
interface CatalogLocation {
|
|
136
|
+
snapshot?: CatalogSnapshot;
|
|
130
137
|
cwd: string;
|
|
131
138
|
userRoot: string;
|
|
132
139
|
projectTrusted: boolean;
|
|
@@ -195,6 +202,42 @@ export async function executeAgentsCommand(args: string, host: AgentCommandHost,
|
|
|
195
202
|
return finish(host, result("ok", "help", false, USAGE));
|
|
196
203
|
}
|
|
197
204
|
const command = parsed.positionals[0]!;
|
|
205
|
+
if ((deps.sharedCatalog ?? !deps.userRoot) && !deps.sharedState) {
|
|
206
|
+
const loc = location(host, deps);
|
|
207
|
+
const remote = await openSharedCatalog(host.cwd, loc.userRoot, "agents-command", loc.projectTrusted);
|
|
208
|
+
const writes = new Set<Promise<unknown>>();
|
|
209
|
+
const listeners = new Set<() => void>();
|
|
210
|
+
const editRevisions = new Map<string, string>();
|
|
211
|
+
try {
|
|
212
|
+
const state = { snapshot: await remote.get(), revoked: false, scopedAgents: remote.scopedAgents, beginEdit(id: string) { editRevisions.set(id, state.snapshot.revision); }, onChange(changed: () => void) { listeners.add(changed); }, edit(edit: Record<string, unknown>) {
|
|
213
|
+
if (state.revoked) return Promise.reject(new Error("catalog-host-revoked: reopen the catalog"));
|
|
214
|
+
const write = (async () => {
|
|
215
|
+
const result = await remote.edit({ expectedRevision: editRevisions.get(edit.catalogId as string) ?? state.snapshot.revision, ...edit });
|
|
216
|
+
if (result.ok) editRevisions.delete(edit.catalogId as string);
|
|
217
|
+
state.snapshot = await remote.get();
|
|
218
|
+
return result;
|
|
219
|
+
})();
|
|
220
|
+
writes.add(write);
|
|
221
|
+
void write.then(() => writes.delete(write), () => writes.delete(write));
|
|
222
|
+
return write;
|
|
223
|
+
} };
|
|
224
|
+
let subscriptionChanged = false;
|
|
225
|
+
const initialSnapshot = await remote.subscribe(snapshot => {
|
|
226
|
+
subscriptionChanged = true;
|
|
227
|
+
if (snapshot) { state.snapshot = snapshot; state.revoked = false; }
|
|
228
|
+
else {
|
|
229
|
+
state.revoked = true;
|
|
230
|
+
state.snapshot = catalogSnapshotFromWire({ schema: state.snapshot.schema, revision: "revoked", digest: "revoked", loadedAt: new Date().toISOString(),
|
|
231
|
+
roles: [], agents: [], blocked: [], diagnostics: [diagnostic("catalog-host-revoked", "Catalog access changed. Reopen the catalog.")] });
|
|
232
|
+
}
|
|
233
|
+
for (const changed of listeners) changed();
|
|
234
|
+
});
|
|
235
|
+
// A queued update or revocation can arrive before subscribe resolves.
|
|
236
|
+
if (!subscriptionChanged) state.snapshot = initialSnapshot;
|
|
237
|
+
return await executeAgentsCommand(args, host, { ...deps, sharedState: state });
|
|
238
|
+
}
|
|
239
|
+
finally { await Promise.allSettled(writes); remote.close(); }
|
|
240
|
+
}
|
|
198
241
|
const loc = location(host, deps);
|
|
199
242
|
if (command === "list") return finishInspection(host, await runList(parsed, loc, deps), deps);
|
|
200
243
|
if (command === "show" || command === "inspect") return finishInspection(host, await runShow(command, parsed, host, loc, deps), deps);
|
|
@@ -250,7 +293,7 @@ async function runList(parsed: ParsedArgs, loc: CatalogLocation, deps: AgentComm
|
|
|
250
293
|
|
|
251
294
|
async function runReload(parsed: ParsedArgs, loc: CatalogLocation, deps: AgentCommandDeps): Promise<AgentCommandResult> {
|
|
252
295
|
if (parsed.positionals.length > 1) return result("error", "reload", false, "reload does not take extra arguments.");
|
|
253
|
-
const listed = presentCatalog(withAgentSessionSettings(refreshCatalog(loc), loc.sessionSettings), deps.enrich, deps.readSkillDefaults);
|
|
296
|
+
const listed = presentCatalog(loc.snapshot ?? withAgentSessionSettings(refreshCatalog(loc), loc.sessionSettings), deps.enrich, deps.readSkillDefaults);
|
|
254
297
|
return {
|
|
255
298
|
...result("ok", "reload", false, `Reloaded revision ${listed.revision} for inspection. The next launch reads the files again on its own; this command is not a prerequisite.\n${listed.text}`),
|
|
256
299
|
diagnostics: listed.diagnostics,
|
|
@@ -380,7 +423,9 @@ async function runCreate(
|
|
|
380
423
|
provenance: { origin: "local" },
|
|
381
424
|
body: instructions ?? "",
|
|
382
425
|
};
|
|
383
|
-
const saved =
|
|
426
|
+
const saved = deps.sharedState ? await deps.sharedState.edit({ action: "definition", catalogId: definition.id, markdown: serializeDefinition(definition).markdown, scope: scope.value, replace: false })
|
|
427
|
+
: createDefinition({ ...loc, definition, scope: scope.value, replace: false });
|
|
428
|
+
if (deps.sharedState) loc.snapshot = withAgentSessionSettings(deps.sharedState.snapshot, loc.sessionSettings);
|
|
384
429
|
if (!saved.ok || !saved.path) {
|
|
385
430
|
return { ...result("error", "create", false, saved.diagnostics.map((item) => item.message).join("\n") || "Create did not write a file."), diagnostics: saved.diagnostics };
|
|
386
431
|
}
|
|
@@ -460,7 +505,8 @@ async function runImport(
|
|
|
460
505
|
return result("error", "import-codex", false, `Unknown role ${shortRoleName(roleId)}. Valid roles: ${roles.map((role) => shortRoleName(role.id)).join(", ")}. Nothing was imported.`);
|
|
461
506
|
}
|
|
462
507
|
const sourceRef = codexSourceRef(resolved);
|
|
463
|
-
const
|
|
508
|
+
const scoped = deps.sharedState ? await deps.sharedState.scopedAgents(scope.value) : listScopeAgents(loc, scope.value);
|
|
509
|
+
const existingLookup = matchExisting(scoped.agents, document.proposedId, sourceRef);
|
|
464
510
|
if (existingLookup.conflict) return clarification("import-codex", `${existingLookup.conflict} Nothing was imported.`);
|
|
465
511
|
if (!roleId) {
|
|
466
512
|
if (!host.hasUI) {
|
|
@@ -528,9 +574,10 @@ async function runImport(
|
|
|
528
574
|
return clarification("import-codex", `${preview.text}\nReplacement was not confirmed. The existing definition was left unchanged.`);
|
|
529
575
|
}
|
|
530
576
|
}
|
|
531
|
-
const saved = existingLookup.match
|
|
577
|
+
const saved = deps.sharedState ? await deps.sharedState.edit({ action: "definition", catalogId: built.definition.id, markdown: serializeDefinition(built.definition).markdown, scope: scope.value, replace: !!existingLookup.match }) : existingLookup.match
|
|
532
578
|
? saveDefinition({ ...loc, definition: built.definition, scope: scope.value, replace: true })
|
|
533
579
|
: createDefinition({ ...loc, definition: built.definition, scope: scope.value, replace: false });
|
|
580
|
+
if (deps.sharedState) loc.snapshot = withAgentSessionSettings(deps.sharedState.snapshot, loc.sessionSettings);
|
|
534
581
|
if (!saved.ok || !saved.path) {
|
|
535
582
|
return { ...result("error", "import-codex", false, saved.diagnostics.map((item) => item.message).join("\n") || "Import did not write a file."), diagnostics: [...parsedSource.diagnostics, ...built.diagnostics, ...saved.diagnostics] };
|
|
536
583
|
}
|
|
@@ -692,6 +739,7 @@ function scopeLabel(scope: "user" | "project"): string {
|
|
|
692
739
|
|
|
693
740
|
function location(host: AgentCommandHost, deps: AgentCommandDeps): CatalogLocation {
|
|
694
741
|
return {
|
|
742
|
+
snapshot: deps.sharedState ? withAgentSessionSettings(deps.sharedState.snapshot, deps.sessionSettings?.snapshot()) : undefined,
|
|
695
743
|
cwd: host.cwd,
|
|
696
744
|
userRoot: deps.userRoot ?? defaultUserRoot(),
|
|
697
745
|
projectTrusted: host.isProjectTrusted(),
|
|
@@ -702,6 +750,7 @@ function location(host: AgentCommandHost, deps: AgentCommandDeps): CatalogLocati
|
|
|
702
750
|
}
|
|
703
751
|
|
|
704
752
|
function readCatalog(loc: CatalogLocation): CatalogSnapshot {
|
|
753
|
+
if (loc.snapshot) return loc.snapshot;
|
|
705
754
|
return withAgentSessionSettings(loadCatalog(loc), loc.sessionSettings);
|
|
706
755
|
}
|
|
707
756
|
|
|
@@ -754,12 +803,18 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
|
|
|
754
803
|
let viewportHeight = 30;
|
|
755
804
|
await host.ui.custom<void>((tui, theme, _keys, done) =>
|
|
756
805
|
createCatalogComponent(entries, theme, () => tui.requestRender(), () => done(), view?.id, deps.sessionSettings ? {
|
|
806
|
+
onChange: deps.sharedState?.onChange,
|
|
807
|
+
beginEdit: deps.sharedState?.beginEdit,
|
|
757
808
|
get: () => presentCatalog(readCatalog(location(host, deps)), deps.enrich, deps.readSkillDefaults),
|
|
758
809
|
models: () => deps.editableModels?.() ?? [],
|
|
759
810
|
scopedModels: () => host.scopedModels ?? [],
|
|
760
811
|
settings: () => deps.sessionSettings!.snapshot(),
|
|
761
812
|
change: (id, key, value) => deps.sessionSettings!.change(id, key, value),
|
|
762
813
|
changeSkills(entry, edit) {
|
|
814
|
+
if (deps.sharedState) return deps.sharedState.edit({ action: "skills", catalogId: entry.id, edit }).then(saved => {
|
|
815
|
+
if (saved.ok && saved.path) { commandResult.wrote = true; commandResult.path = saved.path; commandResult.scope = saved.scope; }
|
|
816
|
+
return { ok: saved.ok, message: saved.message };
|
|
817
|
+
});
|
|
763
818
|
const result = saveSkillExposure({ ...location(host, deps), entry }, edit);
|
|
764
819
|
if (result.ok && result.path) {
|
|
765
820
|
commandResult.wrote = true;
|
|
@@ -770,6 +825,10 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
|
|
|
770
825
|
},
|
|
771
826
|
discoverSkills: () => deps.discoveredSkills ?? [],
|
|
772
827
|
save(id) {
|
|
828
|
+
if (deps.sharedState) return deps.sharedState.edit({ action: "preferences", catalogId: id, preferences: deps.sessionSettings!.snapshot()[id] ?? {} }).then(saved => {
|
|
829
|
+
if (saved.ok) { commandResult.wrote = true; commandResult.path = saved.path; commandResult.scope = saved.scope; }
|
|
830
|
+
return { ok: saved.ok, message: saved.ok ? `Defaults saved (${saved.scope}): ${id}.` : saved.diagnostics.map((item: Diagnostic) => item.message).join(" ") };
|
|
831
|
+
});
|
|
773
832
|
const loc = location(host, deps);
|
|
774
833
|
const saved = saveAgentSessionDefaults(loadCatalog(loc), id, deps.sessionSettings!.snapshot(), loc);
|
|
775
834
|
if (saved.ok) {
|
|
@@ -780,6 +839,10 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
|
|
|
780
839
|
return { ok: saved.ok, message: saved.ok ? `Defaults saved (${saved.scope}): ${id}.` : saved.diagnostics.map((item) => item.message).join(" ") };
|
|
781
840
|
},
|
|
782
841
|
resetToBundled(entry) {
|
|
842
|
+
if (deps.sharedState) return deps.sharedState.edit({ action: "reset-runtime", catalogId: entry.id }).then(saved => {
|
|
843
|
+
if (saved.ok) { commandResult.wrote = true; commandResult.path = saved.path; commandResult.scope = saved.scope; deps.sessionSettings!.reset(entry.id); }
|
|
844
|
+
return { ok: saved.ok, message: saved.ok ? `Bundled model/effort restored: ${entry.id}. Role instructions unchanged.` : saved.diagnostics.map((item: Diagnostic) => item.message).join(" ") };
|
|
845
|
+
});
|
|
783
846
|
const source = entry.winningSource;
|
|
784
847
|
if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
|
|
785
848
|
const reset = resetRuntimeToBundled({ ...location(host, deps), id: entry.id, expectedPath: source.path, expectedDigest: source.contentDigest });
|
|
@@ -797,6 +860,10 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
|
|
|
797
860
|
: reset.diagnostics.map(item => item.message).join(" ") };
|
|
798
861
|
},
|
|
799
862
|
resetDefinition(entry) {
|
|
863
|
+
if (deps.sharedState) return deps.sharedState.edit({ action: "reset-definition", catalogId: entry.id }).then(saved => {
|
|
864
|
+
if (saved.ok) { commandResult.wrote = true; commandResult.path = saved.path; commandResult.scope = saved.scope; }
|
|
865
|
+
return { ok: saved.ok, message: saved.ok ? `Bundled instructions restored: ${entry.id}. Model/effort kept. Backup: ${saved.backupPath}.` : saved.diagnostics.map((item: Diagnostic) => item.message).join(" ") };
|
|
866
|
+
});
|
|
800
867
|
if (entry.identity.scope === "bundled") return { ok: true, message: `Already using bundled instructions: ${entry.id}. Model/effort unchanged.` };
|
|
801
868
|
const source = entry.winningSource;
|
|
802
869
|
if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
|
package/agent-inspection.ts
CHANGED
|
@@ -73,6 +73,7 @@ export interface LaunchEnrichment {
|
|
|
73
73
|
export type LaunchEnricher = (input: {
|
|
74
74
|
inspection: CatalogInspection;
|
|
75
75
|
snapshotDigest: string;
|
|
76
|
+
snapshot?: CatalogSnapshot;
|
|
76
77
|
}) => LaunchEnrichment | undefined;
|
|
77
78
|
|
|
78
79
|
/** The active default a launch would use when the definition chooses nothing. */
|
|
@@ -290,7 +291,7 @@ export function presentCatalogEntry(
|
|
|
290
291
|
let enrichmentFailed = false;
|
|
291
292
|
if (enrich && inspection.found) {
|
|
292
293
|
try {
|
|
293
|
-
enrichment = enrich({ inspection, snapshotDigest: snapshot.digest });
|
|
294
|
+
enrichment = enrich({ inspection, snapshotDigest: snapshot.digest, snapshot });
|
|
294
295
|
} catch (error) {
|
|
295
296
|
enrichmentFailed = true;
|
|
296
297
|
validation.push({
|
package/agents-catalog-tool.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { presentCatalog, presentCatalogEntry, type LaunchEnricher, type ReadSkil
|
|
|
7
7
|
import { canonicalCatalogId } from "./catalog-schema.ts";
|
|
8
8
|
import { defaultUserRoot, loadCatalog } from "./catalog-store.ts";
|
|
9
9
|
import { withAgentSessionSettings, type AgentSessionOverrides, type AgentSessionSettings } from "./agent-session-settings.ts";
|
|
10
|
+
import { openSharedCatalog } from "./shared-catalog.ts";
|
|
10
11
|
|
|
11
12
|
type TypeModule = {
|
|
12
13
|
Object: (value: unknown) => unknown;
|
|
@@ -24,6 +25,7 @@ export interface DiscoveryHost {
|
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
export interface DiscoveryDeps {
|
|
28
|
+
sharedCatalog?: boolean;
|
|
27
29
|
userRoot?: string;
|
|
28
30
|
bundledRoot?: string;
|
|
29
31
|
projectConfigDirName?: string;
|
|
@@ -72,7 +74,12 @@ export function agentsCatalogTool(Type: TypeModule, deps: DiscoveryDeps = {}) {
|
|
|
72
74
|
return toolError(`agents_catalog action must be list or inspect, got ${JSON.stringify(action ?? "")}. It does not create, import, reload, or launch. Nothing was written.`);
|
|
73
75
|
}
|
|
74
76
|
const host = resolveHost(ctx, deps);
|
|
75
|
-
const
|
|
77
|
+
const remote = (deps.sharedCatalog ?? !deps.userRoot) ? await openSharedCatalog(host.cwd, host.userRoot, "catalog-tool", host.projectTrusted) : undefined;
|
|
78
|
+
let snapshot;
|
|
79
|
+
try {
|
|
80
|
+
snapshot = remote ? await remote.get(host.sessionSettings ?? deps.sessionSettings?.snapshot())
|
|
81
|
+
: withAgentSessionSettings(loadCatalog(host), host.sessionSettings ?? deps.sessionSettings?.snapshot());
|
|
82
|
+
} finally { remote?.close(); }
|
|
76
83
|
if (action === "list") {
|
|
77
84
|
const listed = presentCatalog(snapshot, deps.enrich, deps.readSkillDefaults);
|
|
78
85
|
return {
|
package/assignment-outcomes.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { RunMeta } from "./registry.ts";
|
|
|
7
7
|
import { processStartToken } from "./registry.ts";
|
|
8
8
|
import type { PermissionSnapshot } from "./permission-policy.ts";
|
|
9
9
|
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
10
|
+
import { readAssignmentReport } from "./assignment-report.ts";
|
|
10
11
|
|
|
11
12
|
export const ASSIGNMENT_OUTCOMES_VERSION = 1;
|
|
12
13
|
const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
|
|
@@ -62,13 +63,23 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
|
|
|
62
63
|
if (!recoveryFailure && meta.status !== "killed" && meta.operations?.resumeLaunchToken && waits.some((w) => !w.acknowledgement && ["resuming", "ready"].includes(w.phase))) return null;
|
|
63
64
|
// A coherent attempt exit does not establish interpretation or completion.
|
|
64
65
|
if (meta.status === "completed" && waits.some((w) => !w.acknowledgement)) return null;
|
|
66
|
+
let report = null;
|
|
67
|
+
let invalidReport = "";
|
|
68
|
+
try { report = readAssignmentReport(meta); }
|
|
69
|
+
catch { if (meta.status === "completed") invalidReport = "Assignment completion is unverified: retained report evidence is unavailable or changed."; }
|
|
70
|
+
const complete = meta.status === "completed" && (report ? report.status === "complete"
|
|
71
|
+
: !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
|
|
65
72
|
return store.recordAssignmentOutcome({ ...binding, revision: 1,
|
|
66
|
-
outcome:
|
|
67
|
-
reason: meta.failureReason || (meta.status === "completed" ? "Assigned work and required interpretation are complete."
|
|
73
|
+
outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
|
|
74
|
+
reason: meta.failureReason || invalidReport || (meta.status === "completed" && report ? report.reason : complete ? "Assigned work and required interpretation are complete."
|
|
75
|
+
: meta.status === "completed" ? "Assignment completion is unverified: the attempt exited without an evidence-backed completion decision. Inspect retained output and continue unfinished work or report a concrete blocker."
|
|
76
|
+
: `Assignment ended ${meta.status}; retained attempt evidence is available.`),
|
|
68
77
|
processUncertain: meta.status === "lost" || typeof meta.exitCode !== "number"
|
|
69
78
|
|| waits.some((w) => w.dependencies.some((d) => d.terminalRevision === 0)
|
|
70
79
|
|| store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0),
|
|
71
|
-
evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` }
|
|
80
|
+
evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` },
|
|
81
|
+
...(report ? [{ kind: "artifact" as const, ref: meta.assignmentReport!.path, summary: report.reason },
|
|
82
|
+
...report.evidence.map((e) => ({ kind: "artifact" as const, ref: e.path, summary: e.explanation }))] : [])],
|
|
72
83
|
waits: waits.map((w) => ({ waitId: w.waitId, generation: w.generation, cancelEpoch: w.cancelEpoch })),
|
|
73
84
|
});
|
|
74
85
|
});
|
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
3
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
4
|
import { homedir, tmpdir } from "node:os";
|
|
4
5
|
import { join } from "node:path";
|
|
5
6
|
import { readAssignmentWaits } from "./shared-operation-coordinator/assignment-observation.mjs";
|
|
6
7
|
|
|
7
8
|
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
9
|
+
const observations = new AsyncLocalStorage();
|
|
10
|
+
|
|
11
|
+
/** Bind an immutable observation to one read call, never to a supervision loop. */
|
|
12
|
+
export function withAssignmentObservations(rows, read) {
|
|
13
|
+
return observations.run(new Map(rows.map(row => [row.meta.id, row.assignment])), read);
|
|
14
|
+
}
|
|
8
15
|
|
|
9
16
|
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
10
17
|
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
@@ -176,6 +183,7 @@ export function createAssignmentProjector(options = {}) {
|
|
|
176
183
|
let prepared;
|
|
177
184
|
const snapshots = new Map();
|
|
178
185
|
const readSnapshot = (meta) => {
|
|
186
|
+
if (options.attempts) return options.attempts;
|
|
179
187
|
const key = conversationKey(meta.sessionId, meta.cwd);
|
|
180
188
|
if (!snapshots.has(key)) {
|
|
181
189
|
prepared ??= prepareAttemptIndex(options);
|
|
@@ -183,7 +191,7 @@ export function createAssignmentProjector(options = {}) {
|
|
|
183
191
|
}
|
|
184
192
|
return snapshots.get(key);
|
|
185
193
|
};
|
|
186
|
-
return (meta, processStatus = meta.status) => assignmentFromSnapshot(meta, processStatus, options,
|
|
194
|
+
return (meta, processStatus = meta.status) => observations.getStore()?.get(meta.id) ?? assignmentFromSnapshot(meta, processStatus, options,
|
|
187
195
|
() => readSnapshot(meta));
|
|
188
196
|
}
|
|
189
197
|
|
|
@@ -220,7 +228,7 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
|
220
228
|
const status = current.id === meta.id ? processStatus : current.status;
|
|
221
229
|
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
222
230
|
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
223
|
-
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
231
|
+
? (options.observe ?? ((owner) => readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"), owner)))(
|
|
224
232
|
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
225
233
|
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
226
234
|
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
@@ -231,6 +239,6 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
|
231
239
|
return projectAssignment(current, status, observation);
|
|
232
240
|
}
|
|
233
241
|
|
|
234
|
-
export function assignmentDiagnostic(assignment) {
|
|
235
|
-
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
242
|
+
export function assignmentDiagnostic(assignment, options = {}) {
|
|
243
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}.${options.includeEvidence === false ? "" : ` Evidence: ${assignment.evidence.join(", ")}`}`;
|
|
236
244
|
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, mkdirSync, openSync, readSync, realpathSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { runDir, writeMeta, type RunMeta } from "./registry.ts";
|
|
6
|
+
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
7
|
+
import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
|
|
8
|
+
|
|
9
|
+
const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
|
|
10
|
+
const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
11
|
+
function retainedBytes(path: string, limit: number): Buffer {
|
|
12
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
13
|
+
try {
|
|
14
|
+
const stat = fstatSync(fd);
|
|
15
|
+
if (!stat.isFile() || stat.size > limit) throw new Error("Retained assignment evidence exceeds its bound.");
|
|
16
|
+
const bytes = Buffer.alloc(stat.size);
|
|
17
|
+
if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Retained assignment evidence changed.");
|
|
18
|
+
return bytes;
|
|
19
|
+
} finally { closeSync(fd); }
|
|
20
|
+
}
|
|
21
|
+
export interface AssignmentReport {
|
|
22
|
+
version: 1; assignmentId: string; attemptId: string; requestDigest: string; status: "complete" | "incomplete"; reason: string;
|
|
23
|
+
evidence: Array<{ path: string; digest: string; source: string; explanation: string }>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
|
|
27
|
+
export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
|
|
28
|
+
const meta = assertAuthority();
|
|
29
|
+
const report = input as { status: string; reason: string; evidence: Array<{ path: string; explanation: string }> };
|
|
30
|
+
if (!["complete", "incomplete"].includes(report.status) || !report.reason?.trim() || report.reason.length > 2048
|
|
31
|
+
|| !Array.isArray(report.evidence) || report.evidence.length < 1 || report.evidence.length > 4) throw new Error("Invalid assignment report.");
|
|
32
|
+
const root = realpathSync(meta.cwd);
|
|
33
|
+
const directory = join(runDir(id), "assignment-report-v1");
|
|
34
|
+
const captured = (meta.operations?.policy.sandbox as { permissions?: Partial<PermissionProfile> } | null)?.permissions;
|
|
35
|
+
if (captured && captured.projectFiles !== "read" && captured.projectFiles !== "read-write") throw new Error("Captured assignment evidence read permission refused.");
|
|
36
|
+
for (const policy of [current?.permissions, current?.subagentPermissions]) {
|
|
37
|
+
if (policy?.enabled && policy.projectFiles !== "read" && policy.projectFiles !== "read-write") throw new Error("Current assignment evidence read permission refused.");
|
|
38
|
+
}
|
|
39
|
+
if (meta.operations?.policy.sandbox && !current?.permissions) throw new Error("Current assignment evidence read authority unavailable.");
|
|
40
|
+
const requestDigest = hash(JSON.stringify([report.status, report.reason, report.evidence.map((e) => [e.path, e.explanation])]));
|
|
41
|
+
if (meta.assignmentReport) {
|
|
42
|
+
const accepted = readAssignmentReport(meta)!;
|
|
43
|
+
if (accepted.requestDigest !== requestDigest) throw new Error("Conflicting assignment report refused.");
|
|
44
|
+
return { reportId: meta.assignmentReport.digest, status: accepted.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
45
|
+
}
|
|
46
|
+
const snapshots = report.evidence.map((e) => {
|
|
47
|
+
if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
|
|
48
|
+
const source = realpathSync(resolve(root, e.path));
|
|
49
|
+
if (!inside(root, source) || credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
|
|
50
|
+
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
51
|
+
try {
|
|
52
|
+
const stat = fstatSync(fd);
|
|
53
|
+
if (!stat.isFile() || stat.size > 65536) throw new Error("Assignment evidence must be a file of at most 65536 bytes.");
|
|
54
|
+
const bytes = Buffer.alloc(stat.size);
|
|
55
|
+
if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
|
|
56
|
+
return { bytes, digest: hash(bytes), source, explanation: e.explanation };
|
|
57
|
+
} finally { closeSync(fd); }
|
|
58
|
+
});
|
|
59
|
+
const retained: AssignmentReport = { version: 1, assignmentId: meta.assignment!.assignmentId, attemptId: id, requestDigest,
|
|
60
|
+
status: report.status as AssignmentReport["status"], reason: report.reason,
|
|
61
|
+
evidence: snapshots.map(({ digest, source, explanation }) => ({ path: join(directory, digest), digest, source, explanation })) };
|
|
62
|
+
const text = JSON.stringify(retained);
|
|
63
|
+
if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
|
|
64
|
+
const digest = hash(text);
|
|
65
|
+
const latest = assertAuthority();
|
|
66
|
+
if (latest.assignmentReport) {
|
|
67
|
+
if (latest.assignmentReport.digest !== digest) throw new Error("Conflicting assignment report refused.");
|
|
68
|
+
readAssignmentReport(latest);
|
|
69
|
+
} else {
|
|
70
|
+
mkdirSync(directory, { recursive: true });
|
|
71
|
+
for (const snapshot of snapshots) writeFileSync(join(directory, snapshot.digest), snapshot.bytes, { mode: 0o600 });
|
|
72
|
+
const path = join(directory, `${digest}.json`);
|
|
73
|
+
writeFileSync(path, text, { mode: 0o600 });
|
|
74
|
+
writeMeta({ ...latest, assignmentReport: { version: 1, assignmentId: retained.assignmentId, attemptId: id, digest, path } });
|
|
75
|
+
}
|
|
76
|
+
return { reportId: digest, status: report.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
|
|
80
|
+
const ref = meta.assignmentReport;
|
|
81
|
+
if (!ref) return null;
|
|
82
|
+
if (ref.version !== 1 || !/^[a-f0-9]{64}$/.test(ref.digest) || ref.assignmentId !== meta.assignment?.assignmentId || ref.attemptId !== meta.id
|
|
83
|
+
|| ref.path !== join(runDir(meta.id), "assignment-report-v1", `${ref.digest}.json`)) throw new Error("Foreign assignment report reference.");
|
|
84
|
+
const text = retainedBytes(ref.path, 65536).toString("utf8");
|
|
85
|
+
if (hash(text) !== ref.digest) throw new Error("Retained assignment report changed.");
|
|
86
|
+
const report = JSON.parse(text) as AssignmentReport;
|
|
87
|
+
if (report.version !== 1 || report.assignmentId !== ref.assignmentId || report.attemptId !== meta.id) throw new Error("Foreign assignment report.");
|
|
88
|
+
for (const e of report.evidence) {
|
|
89
|
+
if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest) || hash(retainedBytes(e.path, 65536)) !== e.digest) throw new Error("Retained assignment evidence changed.");
|
|
90
|
+
}
|
|
91
|
+
return report;
|
|
92
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { processStartToken } from "./registry.ts";
|
|
5
|
+
import { WorkClient } from "./shared-work-client.mjs";
|
|
6
|
+
import type { AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
7
|
+
import { overlayDigest } from "./catalog-overlay.ts";
|
|
8
|
+
export { overlayDigest } from "./catalog-overlay.ts";
|
|
9
|
+
|
|
10
|
+
type HostContext = { cwd: string; isProjectTrusted(): boolean; sessionManager?: { getSessionId?(): string; getLeafId?(): string | null } };
|
|
11
|
+
export function createCatalogHostAdapter() {
|
|
12
|
+
let current: { ctx: HostContext; overlay: () => AgentSessionOverrides } | undefined;
|
|
13
|
+
let live: { client: WorkClient; path: string; key: string; authority: Record<string, unknown> } | undefined;
|
|
14
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
15
|
+
let epoch = 0;
|
|
16
|
+
let admitting: Promise<Record<string, unknown> | undefined> = Promise.resolve(undefined);
|
|
17
|
+
|
|
18
|
+
/** Fixed Pi adapter only. Never exposed as a tool or socket issuance operation. */
|
|
19
|
+
function noteCatalogHostContext(ctx: HostContext, overlay: () => AgentSessionOverrides) {
|
|
20
|
+
current = { ctx, overlay };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function closeCatalogHost() {
|
|
24
|
+
epoch++;
|
|
25
|
+
clearInterval(timer); timer = undefined;
|
|
26
|
+
if (live) { live.client.close(); rmSync(live.path, { force: true }); live = undefined; }
|
|
27
|
+
current = undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function catalogHostAuthority(agentDir: string, cwd: string, socketPath: string) {
|
|
31
|
+
admitting = admitting.catch(() => undefined).then(() => admit(agentDir, cwd, socketPath));
|
|
32
|
+
return admitting;
|
|
33
|
+
}
|
|
34
|
+
async function admit(agentDir: string, cwd: string, socketPath: string) {
|
|
35
|
+
const admittedEpoch = epoch;
|
|
36
|
+
if (!current || realpathSync(current.ctx.cwd) !== realpathSync(cwd)) return undefined;
|
|
37
|
+
const ctx = current.ctx;
|
|
38
|
+
const scope = { cwd: realpathSync(cwd), sessionId: ctx.sessionManager?.getSessionId?.() ?? `local-${process.pid}`,
|
|
39
|
+
branchId: ctx.sessionManager?.getLeafId?.() ?? "root", projectTrusted: typeof ctx.isProjectTrusted === "function" && ctx.isProjectTrusted(),
|
|
40
|
+
overlayDigest: overlayDigest(current.overlay()) };
|
|
41
|
+
const key = JSON.stringify([agentDir, socketPath, scope]);
|
|
42
|
+
if (live?.key === key && !live.client.closed) return live.authority;
|
|
43
|
+
if (live) { live.client.close(); rmSync(live.path, { force: true }); live = undefined; }
|
|
44
|
+
const root = join(realpathSync(agentDir), "catalog-host-admission");
|
|
45
|
+
mkdirSync(root, { mode: 0o700, recursive: true });
|
|
46
|
+
const stat = lstatSync(root);
|
|
47
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.()) throw new Error("Unsafe catalog host admission directory");
|
|
48
|
+
const id = randomUUID(), secret = randomBytes(32).toString("hex"), generation = randomUUID();
|
|
49
|
+
const path = join(root, `${id}.json`), staging = join(root, `.${id}`);
|
|
50
|
+
const authority = { id, secret, generation, cwd: scope.cwd, sessionId: scope.sessionId, branchId: scope.branchId };
|
|
51
|
+
const client = new WorkClient(socketPath, agentDir, ["runtime-catalog-v1"]);
|
|
52
|
+
try {
|
|
53
|
+
const hello = await client.ready;
|
|
54
|
+
const pidStartTime = processStartToken(process.pid);
|
|
55
|
+
if (!pidStartTime) throw new Error("catalog-host-identity-unavailable");
|
|
56
|
+
writeFileSync(staging, JSON.stringify({ version: 1, id, generation, serverInstance: hello.instanceId, pid: process.pid, pidStartTime, secretHash: hash(secret), ...scope }), { mode: 0o600, flag: "wx" });
|
|
57
|
+
renameSync(staging, path);
|
|
58
|
+
await client.request("runtime_bind_catalog_host", { authority });
|
|
59
|
+
if (epoch !== admittedEpoch || !current) throw new Error("catalog-host-revoked");
|
|
60
|
+
live = { client, path, key, authority };
|
|
61
|
+
if (!timer) { timer = setInterval(() => { void catalogHostAuthority(agentDir, current?.ctx.cwd ?? cwd, socketPath).catch(() => closeCatalogHost()); }, 500); timer.unref(); }
|
|
62
|
+
return authority;
|
|
63
|
+
} catch (error) { client.close(); rmSync(path, { force: true }); rmSync(staging, { force: true }); throw error; }
|
|
64
|
+
}
|
|
65
|
+
return { noteCatalogHostContext, closeCatalogHost, catalogHostAuthority };
|
|
66
|
+
}
|
|
67
|
+
export const { noteCatalogHostContext, closeCatalogHost, catalogHostAuthority } = createCatalogHostAdapter();
|
|
68
|
+
|
|
69
|
+
function hash(value: string) { return createHash("sha256").update(value).digest("hex"); }
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
3
|
+
|
|
4
|
+
/** Canonical host/server credential binding for branch-local Catalog preferences. */
|
|
5
|
+
export function overlayDigest(value: AgentSessionOverrides = {}): string {
|
|
6
|
+
const canonical = Object.fromEntries(Object.keys(value).sort().map(id => [id,
|
|
7
|
+
Object.fromEntries(Object.entries(value[id]!).sort(([a], [b]) => a.localeCompare(b))),
|
|
8
|
+
]));
|
|
9
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
10
|
+
}
|
package/catalog-runtime.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { configureTierPolicy, DEFAULT_TIER_POLICY, type TierPolicy, type TierSpe
|
|
|
25
25
|
import { canonicalAgentId, canonicalRoleId, shortRoleName, type Diagnostic, type ThinkingLevel } from "./catalog-schema.ts";
|
|
26
26
|
import { withAgentSessionSettings, type AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
27
27
|
import { currentSandboxPermissions } from "./permission-policy.ts";
|
|
28
|
+
import { openSharedCatalog } from "./shared-catalog.ts";
|
|
28
29
|
|
|
29
30
|
export interface CatalogHost {
|
|
30
31
|
cwd: string;
|
|
@@ -164,9 +165,16 @@ export function loadLaunchSnapshot(host: CatalogHost): CatalogSnapshot {
|
|
|
164
165
|
}), host.getSessionSettings?.() ?? host.sessionSettings);
|
|
165
166
|
}
|
|
166
167
|
|
|
168
|
+
/** Admit once per launch/batch; callers retain this frozen value for every job. */
|
|
169
|
+
export async function loadSharedLaunchSnapshot(host: CatalogHost): Promise<CatalogSnapshot> {
|
|
170
|
+
const remote = await openSharedCatalog(host.cwd, host.userRoot, "catalog-launch", host.projectTrusted);
|
|
171
|
+
try { return await remote.get(host.getSessionSettings?.() ?? host.sessionSettings); }
|
|
172
|
+
finally { remote.close(); }
|
|
173
|
+
}
|
|
174
|
+
|
|
167
175
|
export function createLaunchEnricher(pi?: unknown): LaunchEnricher {
|
|
168
176
|
let cache: { key: string; rows: Map<string, CatalogResolutionAttachment> } | undefined;
|
|
169
|
-
return ({ inspection, snapshotDigest }) => {
|
|
177
|
+
return ({ inspection, snapshotDigest, snapshot: admittedSnapshot }) => {
|
|
170
178
|
const host = notedHost.current;
|
|
171
179
|
if (!host?.cwd || !host.registry || typeof host.registry.getAvailable !== "function") return undefined;
|
|
172
180
|
const config = loadConfig();
|
|
@@ -185,7 +193,7 @@ export function createLaunchEnricher(pi?: unknown): LaunchEnricher {
|
|
|
185
193
|
availability: availability.key,
|
|
186
194
|
});
|
|
187
195
|
if (!cache || cache.key !== key) {
|
|
188
|
-
const snapshot = loadLaunchSnapshot({ ...host, userRoot: host.userRoot ?? defaultUserRoot() });
|
|
196
|
+
const snapshot = admittedSnapshot ?? loadLaunchSnapshot({ ...host, userRoot: host.userRoot ?? defaultUserRoot() });
|
|
189
197
|
if (snapshot.digest !== snapshotDigest) return undefined;
|
|
190
198
|
const registry = availability.models === undefined
|
|
191
199
|
? host.registry
|