pi-better-subagents 0.33.0 → 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.
Files changed (34) hide show
  1. package/agent-catalog.mjs +24 -0
  2. package/agent-commands.ts +71 -4
  3. package/agent-inspection.ts +2 -1
  4. package/agents-catalog-tool.ts +8 -1
  5. package/catalog-host-admission.ts +69 -0
  6. package/catalog-overlay.ts +10 -0
  7. package/catalog-runtime.ts +10 -2
  8. package/catalog-store.ts +23 -0
  9. package/catalog-ui.ts +26 -10
  10. package/docs/agent-catalog-operations.md +38 -0
  11. package/index.ts +12 -7
  12. package/launch-abort.ts +21 -0
  13. package/package.json +1 -1
  14. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  15. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  16. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  17. package/runtime-client/artifacts/darwin-x64.json +1 -1
  18. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  19. package/runtime-client/artifacts/linux-arm64.json +1 -1
  20. package/runtime-client/artifacts/linux-x64.gz +0 -0
  21. package/runtime-client/artifacts/linux-x64.json +1 -1
  22. package/runtime-client/src/daemon-owner.mjs +2 -1
  23. package/runtime-client/src/runtime/work-client.mjs +16 -2
  24. package/shared-catalog.ts +69 -0
  25. package/shared-operation-coordinator/assignment-observation.mjs +18 -1
  26. package/shared-operation-coordinator/src/discovery.ts +9 -0
  27. package/shared-operation-coordinator/src/operations.ts +6 -4
  28. package/shared-operation-coordinator/src/result-supervision.ts +128 -0
  29. package/shared-operation-coordinator/src/schema.ts +19 -1
  30. package/shared-operation-coordinator/src/store.ts +20 -0
  31. package/shared-operation-coordinator/src/types.ts +6 -0
  32. package/shared-work-client.d.mts +4 -1
  33. package/shared-work-client.mjs +16 -2
  34. package/skill-picker.ts +6 -2
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 = createDefinition({ ...loc, definition, scope: scope.value, replace: false });
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 existingLookup = matchExisting(listScopeAgents(loc, scope.value).agents, document.proposedId, sourceRef);
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." };
@@ -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({
@@ -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 snapshot = withAgentSessionSettings(loadCatalog(host), host.sessionSettings ?? deps.sessionSettings?.snapshot());
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 {
@@ -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
+ }
@@ -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
package/catalog-store.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  parseDefinition,
38
38
  serializeDefinition,
39
39
  type CatalogDefinition,
40
+ type AgentDefinition,
40
41
  type CatalogKind,
41
42
  type CatalogScope,
42
43
  type Diagnostic,
@@ -151,6 +152,14 @@ class FrozenMap<K, V> extends Map<K, V> {
151
152
  }
152
153
  }
153
154
 
155
+ /** Rebuild the same immutable domain value after a JSON socket round trip. */
156
+ export function catalogSnapshotFromWire(wire: Omit<CatalogSnapshot, "roles" | "agents"> & {
157
+ roles: Iterable<readonly [string, CatalogEntry]>;
158
+ agents: Iterable<readonly [string, CatalogEntry]>;
159
+ }): CatalogSnapshot {
160
+ return deepFreeze({ ...wire, roles: FrozenMap.fill(wire.roles), agents: FrozenMap.fill(wire.agents) });
161
+ }
162
+
154
163
  export function defaultUserRoot(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
155
164
  const configured = env.PI_CODING_AGENT_DIR?.trim();
156
165
  return configured ? configured : join(home, ".pi", "agent");
@@ -178,6 +187,20 @@ export function contentDigest(raw: string): string {
178
187
  return createHash("sha256").update(raw).digest("hex");
179
188
  }
180
189
 
190
+ /** Import matching needs every source in the destination scope, including shadowed IDs. */
191
+ export function listScopedAgents(input: LoadCatalogInput, scope: "user" | "project"): { agents: { path: string; definition: AgentDefinition }[]; diagnostics: Diagnostic[] } {
192
+ const diagnostics: Diagnostic[] = [];
193
+ if (scope === "project" && !input.projectTrusted) throw new Error("Project catalog access requires a trusted host.");
194
+ const config = input.projectConfigDirName ?? DEFAULT_PROJECT_CONFIG_DIR_NAME;
195
+ if (!isSafeConfigDirName(config)) throw new Error("Unsafe project config directory");
196
+ const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
197
+ const occurrences = new Map<string, Occurrence[]>();
198
+ collectDirectory(directory, scope, "agent", occurrences, diagnostics);
199
+ const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
200
+ ? [{ path: item.path, definition: item.parse.definition }] : []);
201
+ return { agents, diagnostics };
202
+ }
203
+
181
204
  /** Read every source again. Identical bytes produce the same digest and a new object. */
182
205
  export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
183
206
  const loadedAt = new Date().toISOString();
package/catalog-ui.ts CHANGED
@@ -6,8 +6,17 @@ import type { AgentSessionOverrides, AgentSettingKey } from "./agent-session-set
6
6
  import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
7
7
 
8
8
  type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string; inverse?(text: string): string };
9
+ type EditResult = { ok: boolean; message: string };
10
+ type PendingEdit = EditResult | Promise<EditResult>;
11
+
12
+ function settleEdit(result: PendingEdit, done: (result: EditResult) => void, failed: (error: unknown) => void) {
13
+ if (result instanceof Promise) void result.then(done, failed);
14
+ else done(result);
15
+ }
9
16
 
10
17
  export interface CatalogEditor {
18
+ beginEdit?(id: string): void;
19
+ onChange?(changed: () => void): void;
11
20
  get(): OperationList;
12
21
  /** Available foreground models, used only when the session scope is empty. */
13
22
  models(): readonly string[];
@@ -16,12 +25,12 @@ export interface CatalogEditor {
16
25
  settings(): AgentSessionOverrides;
17
26
  change(id: string, key: AgentSettingKey, value: string | null): void;
18
27
  /** Skill exposure is edited through the definition save path, not session settings. */
19
- changeSkills?(entry: OperationView, edit: SkillExposureEdit): { ok: boolean; message: string };
28
+ changeSkills?(entry: OperationView, edit: SkillExposureEdit): PendingEdit;
20
29
  /** Loaded Pi skill metadata for the checkbox picker. */
21
30
  discoverSkills?(): readonly DiscoveredSkill[];
22
- save(id: string): { ok: boolean; message: string };
23
- resetToBundled?(entry: OperationView): { ok: boolean; message: string };
24
- resetDefinition?(entry: OperationView): { ok: boolean; message: string };
31
+ save(id: string): PendingEdit;
32
+ resetToBundled?(entry: OperationView): PendingEdit;
33
+ resetDefinition?(entry: OperationView): PendingEdit;
25
34
  }
26
35
 
27
36
  function stateLabel(entry: OperationView): string {
@@ -208,12 +217,13 @@ export function createCatalogComponent(
208
217
  const highlight = (text: string, width: number) => theme.bg?.("selectedBg", theme.bold?.(cell(text, width)) ?? cell(text, width)) ?? theme.fg("accent", text);
209
218
  function report(text: string, failed = false) { message = text; error = failed; requestRender(); }
210
219
  function refresh() { if (editor) catalog = editor.get(); }
220
+ editor?.onChange?.(() => { refresh(); requestRender(); });
211
221
  function save() {
212
222
  if (!editor || !selected()) return;
213
223
  try {
214
- const result = editor.save(selected()!.id);
215
- refresh();
216
- report(result.message, !result.ok);
224
+ settleEdit(editor.save(selected()!.id), result => {
225
+ refresh(); report(result.message, !result.ok);
226
+ }, cause => report(String(cause), true));
217
227
  } catch (cause) { report(String(cause instanceof Error ? cause.message : cause), true); }
218
228
  }
219
229
  function canReset(entry: OperationView | undefined): boolean {
@@ -227,13 +237,14 @@ export function createCatalogComponent(
227
237
  function reset(entry = selected(), definition = false) {
228
238
  if (!entry || !(definition ? canResetDefinition(entry) : canReset(entry))) return;
229
239
  try {
230
- const result = definition ? editor!.resetDefinition!(entry) : editor!.resetToBundled!(entry);
240
+ settleEdit(definition ? editor!.resetDefinition!(entry) : editor!.resetToBundled!(entry), result => {
231
241
  refresh();
232
242
  settingRow = 0;
233
243
  scroll = 0;
234
244
  resetPointerRows = [];
235
245
  resetPointerEntry = undefined;
236
246
  report(result.message, !result.ok);
247
+ }, cause => report(String(cause), true));
237
248
  } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
238
249
  }
239
250
  /** Selectable setting rows in display order; Reset is a row, not a save action. */
@@ -268,9 +279,10 @@ export function createCatalogComponent(
268
279
  apply(paths) {
269
280
  if (!editor?.changeSkills) return { ok: false, message: "Skill editing is unavailable." };
270
281
  try {
271
- const result = editor.changeSkills(current, paths.length === 0
282
+ const pending = editor.changeSkills(current, paths.length === 0
272
283
  ? { mode: "none" }
273
284
  : { mode: "explicit", paths: [...paths] });
285
+ const finish = (result: EditResult) => {
274
286
  if (result.ok) {
275
287
  refresh();
276
288
  report(paths.length === 0
@@ -278,6 +290,8 @@ export function createCatalogComponent(
278
290
  : result.message, false);
279
291
  }
280
292
  return { ok: result.ok, message: result.message };
293
+ };
294
+ return pending instanceof Promise ? pending.then(finish) : finish(pending);
281
295
  } catch (cause) {
282
296
  return { ok: false, message: cause instanceof Error ? cause.message : String(cause) };
283
297
  }
@@ -308,10 +322,11 @@ export function createCatalogComponent(
308
322
  picker.onSelect = (item) => {
309
323
  if (item.value === "select") { openSkillPaths(current); return; }
310
324
  try {
311
- const result = editor!.changeSkills!(current, item.value === "none" ? { mode: "none" } : { mode: "inherit" });
325
+ settleEdit(editor!.changeSkills!(current, item.value === "none" ? { mode: "none" } : { mode: "inherit" }), result => {
312
326
  refresh();
313
327
  picker = undefined;
314
328
  report(result.message, !result.ok);
329
+ }, cause => report(String(cause), true));
315
330
  } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
316
331
  };
317
332
  const selectedIndex = skillChoiceIndex(current);
@@ -320,6 +335,7 @@ export function createCatalogComponent(
320
335
  function edit() {
321
336
  const current = selected();
322
337
  if (!current || !editor) return;
338
+ editor.beginEdit?.(current.id);
323
339
  const keys = settingKeys(current);
324
340
  const key = keys[settingRow];
325
341
  if (!key) { settingRow = 0; return; }
@@ -4,6 +4,44 @@ Commands, the read-only discovery tool, and the Codex importer for `pi-agent/v1`
4
4
 
5
5
  ## Commands
6
6
 
7
+ ### Shared runtime writes
8
+
9
+ Production catalog reads and persistent edits use the canonical agent directory's
10
+ server. Each edit submits the content revision read by that invocation. If another
11
+ client changed the catalog, the server returns `catalog-conflict`; reopen the view
12
+ before trying again. A conflict does not overwrite the newer definition or discard
13
+ the current session branch's temporary choices. Model/effort still use the existing
14
+ `agents/settings.json`; skill changes still use the original Markdown definition.
15
+
16
+ The server serializes cooperating clients' comparison and atomic writes. A direct
17
+ external editor does not participate in this transaction and can race the revision
18
+ comparison and rename. This is not a filesystem-wide compare-and-swap guarantee.
19
+ Open catalog views subscribe to source revisions. The server shares filesystem
20
+ watches and reconciles at most 64 subscribed scopes once per second, including
21
+ paths created after subscription. Revoked subscriptions discard project data;
22
+ the fixed host revalidates its current context before resubscribing. A disconnected
23
+ or missing host requires reopening the view. External changes are
24
+ also visible on the next explicit catalog request. An admitted launch or
25
+ batch retains its frozen snapshot; later changes affect future admission only,
26
+ not an existing attempt, continuation recipe, tools, or sandbox permissions.
27
+
28
+ The fixed Pi host adapter reads the actual workspace, session, branch, overlay
29
+ revision, and `ctx.isProjectTrusted()` decision. It creates an unguessable grant
30
+ in the canonical agent directory's private `catalog-host-admission` directory
31
+ (0700; records 0600). The server checks the record, secret hash, generation,
32
+ exact scope, and live host connection on every request using that grant.
33
+ Issuance is not a socket operation or a tool. Session strings and wire trust
34
+ booleans cannot issue a grant. The CLI's fixed adapter uses the existing SDK
35
+ trust store rather than accepting a project trust argument.
36
+
37
+ The host revalidates its context before catalog operations and at a bounded
38
+ interval while connected. Trust or branch changes invalidate the old grant.
39
+ Host shutdown and connection loss revoke it; reconnect requires current host
40
+ validation and a new grant. Session-only trust does not update the user's trust
41
+ store. Grants remain control metadata, never definition fields, index rows,
42
+ protocol logs, or launch recipes. As in the server's existing security model,
43
+ a process fully controlling the same UID is outside this boundary.
44
+
7
45
  `/agents` is one Pi command. Dialogs use `ctx.ui.select`, `confirm`, `input`, and `editor`. `ctx.hasUI` is false in print and JSON mode. When a choice or confirmation is required there, the command returns `clarification-needed` and writes nothing.
8
46
 
9
47
  In an interactive TUI, `/agents`, `/agents list`, and `/agents show` open a focused catalog view instead of leaving the listing in a persistent widget. Rows align name, effective model, source, and launch state; narrow terminals retain name and model. The model is the resolved actual model when available, otherwise the requested or inherited preference, or `not resolved`. Type to filter by id, name, description, or base role; use Up/Down and Enter to inspect. The detail view opens **Settings**, with Model, Effort, Skills, launch resolution, and diagnostics. **Instructions** contains the complete effective prompt (role plus agent in add mode, agent text in replace mode); this is not the task-specific launch prompt. **Files** shows definition and saved-config sources plus current session edits. Tab and Shift+Tab cycle between these pages; `p` opens Instructions. Up/Down selects settings or scrolls the current page. Left or Escape returns to Settings, then list, clears the filter, then closes. `/agents show <id>` opens that definition directly. Print/JSON callers still receive the complete text and structured result; bare `/agents` still returns help outside the custom TUI.