@astrosheep/keiyaku 4.6.32 → 4.6.34

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 (244) hide show
  1. package/README.md +18 -7
  2. package/build/plugins/claude/skills/keiyaku-akuma/SKILL.md +18 -11
  3. package/build/plugins/claude/skills/keiyaku-babysit/SKILL.md +8 -6
  4. package/build/plugins/claude/skills/keiyaku-debt/SKILL.md +2 -1
  5. package/build/plugins/claude/skills/keiyaku-workflow/SKILL.md +2 -1
  6. package/build/plugins/codex/skills/keiyaku-akuma/SKILL.md +18 -11
  7. package/build/plugins/codex/skills/keiyaku-babysit/SKILL.md +8 -6
  8. package/build/plugins/codex/skills/keiyaku-debt/SKILL.md +2 -1
  9. package/build/plugins/codex/skills/keiyaku-workflow/SKILL.md +2 -1
  10. package/build/plugins/opencode/skills/keiyaku-akuma/SKILL.md +18 -11
  11. package/build/plugins/opencode/skills/keiyaku-babysit/SKILL.md +8 -6
  12. package/build/plugins/opencode/skills/keiyaku-debt/SKILL.md +2 -1
  13. package/build/plugins/opencode/skills/keiyaku-workflow/SKILL.md +2 -1
  14. package/build/plugins/pi/README.md +55 -97
  15. package/build/plugins/pi/keiyaku.ts +1 -142
  16. package/build/skills/keiyaku-akuma/SKILL.md +18 -11
  17. package/build/skills/keiyaku-babysit/SKILL.md +8 -6
  18. package/build/skills/keiyaku-debt/SKILL.md +2 -1
  19. package/build/skills/keiyaku-workflow/SKILL.md +2 -1
  20. package/build/src/akuma/akuma-instance.d.ts +11 -0
  21. package/build/src/akuma/akuma-instance.js +1 -2
  22. package/build/src/akuma/akuma-observe.d.ts +8 -0
  23. package/build/src/akuma/akuma-observe.js +81 -14
  24. package/build/src/akuma/akuma-owner.d.ts +1 -0
  25. package/build/src/akuma/akuma-owner.js +3 -5
  26. package/build/src/akuma/akuma-selection-execution.d.ts +82 -7
  27. package/build/src/akuma/akuma-selection-execution.js +26 -27
  28. package/build/src/akuma/akuma-wait.d.ts +155 -1
  29. package/build/src/akuma/akuma-wait.js +94 -34
  30. package/build/src/akuma/akuma.d.ts +17 -1
  31. package/build/src/akuma/akuma.js +37 -18
  32. package/build/src/akuma/body.js +13 -18
  33. package/build/src/akuma/call-initial-tell.d.ts +0 -1
  34. package/build/src/akuma/call-initial-tell.js +0 -1
  35. package/build/src/akuma/heart/activity-schema.d.ts +16 -0
  36. package/build/src/akuma/heart/activity-schema.js +7 -0
  37. package/build/src/akuma/heart/facts.d.ts +1 -0
  38. package/build/src/akuma/heart/facts.js +14 -0
  39. package/build/src/akuma/heart/index.d.ts +7 -1
  40. package/build/src/akuma/heart/index.js +35 -9
  41. package/build/src/akuma/heart/rows.d.ts +1 -0
  42. package/build/src/akuma/heart/rows.js +4 -0
  43. package/build/src/akuma/heart/timeline.js +4 -4
  44. package/build/src/akuma/lineage-cache.d.ts +7 -2
  45. package/build/src/akuma/lineage-cache.js +48 -24
  46. package/build/src/akuma/projection-read.d.ts +4 -2
  47. package/build/src/akuma/projection-read.js +25 -23
  48. package/build/src/akuma/projection.d.ts +94 -2
  49. package/build/src/akuma/projection.js +47 -47
  50. package/build/src/akuma/provider.d.ts +2 -2
  51. package/build/src/akuma/provider.js +27 -20
  52. package/build/src/akuma/providers/acp/core.js +2 -5
  53. package/build/src/akuma/providers/opencode-sdk/events.d.ts +2 -1
  54. package/build/src/akuma/providers/opencode-sdk/events.js +31 -1
  55. package/build/src/akuma/publication.js +3 -2
  56. package/build/src/akuma/selection-observation.d.ts +645 -0
  57. package/build/src/akuma/selection-observation.js +22 -7
  58. package/build/src/akuma/status-projection.d.ts +14 -1
  59. package/build/src/akuma/status-projection.js +40 -2
  60. package/build/src/akuma/turn-drive.js +21 -15
  61. package/build/src/body/amend.js +5 -17
  62. package/build/src/body/decode.js +11 -1
  63. package/build/src/body/envelope.d.ts +5 -1
  64. package/build/src/body/envelope.js +4 -2
  65. package/build/src/body/render.js +4 -6
  66. package/build/src/bounded-list.d.ts +8 -0
  67. package/build/src/bounded-list.js +10 -0
  68. package/build/src/cli/commands/akuma-grammar.d.ts +5 -8
  69. package/build/src/cli/commands/akuma-grammar.js +52 -77
  70. package/build/src/cli/commands/akuma.d.ts +1 -2
  71. package/build/src/cli/commands/akuma.js +12 -61
  72. package/build/src/cli/commands/contract-grammar.d.ts +1 -0
  73. package/build/src/cli/commands/contract-grammar.js +39 -42
  74. package/build/src/cli/commands/contract-help.d.ts +6 -5
  75. package/build/src/cli/commands/contract-help.js +21 -13
  76. package/build/src/cli/commands/contract.d.ts +3 -3
  77. package/build/src/cli/commands/contract.js +13 -9
  78. package/build/src/cli/commands/debt-grammar.js +2 -4
  79. package/build/src/cli/parse.d.ts +4 -10
  80. package/build/src/cli/parse.js +2 -5
  81. package/build/src/cli/render/akuma-activity.d.ts +12 -34
  82. package/build/src/cli/render/akuma-activity.js +99 -180
  83. package/build/src/cli/render/akuma.d.ts +5 -11
  84. package/build/src/cli/render/akuma.js +22 -30
  85. package/build/src/cli/render/catalog.js +4 -6
  86. package/build/src/cli/render/contract-history.d.ts +1 -3
  87. package/build/src/cli/render/contract-history.js +70 -49
  88. package/build/src/cli/render/contract-observation.d.ts +2 -1
  89. package/build/src/cli/render/contract-observation.js +25 -1
  90. package/build/src/cli/render/contract-wait.d.ts +2 -2
  91. package/build/src/cli/render/contract-wait.js +21 -17
  92. package/build/src/cli/render/contract.js +12 -9
  93. package/build/src/cli/render/debt.js +1 -2
  94. package/build/src/cli/render/execution-progress.js +1 -3
  95. package/build/src/cli/render/kanshi-akuma.d.ts +4 -3
  96. package/build/src/cli/render/kanshi-akuma.js +27 -23
  97. package/build/src/cli/render/kanshi.js +45 -60
  98. package/build/src/cli/render/receipt.d.ts +1 -1
  99. package/build/src/cli/render/receipt.js +33 -28
  100. package/build/src/cli/render/reconcile.js +2 -5
  101. package/build/src/cli/render/refusal.js +3 -6
  102. package/build/src/cli/render/terminal.d.ts +2 -4
  103. package/build/src/cli/render/terminal.js +10 -17
  104. package/build/src/cli/render/verbs.d.ts +1 -0
  105. package/build/src/cli/render/verbs.js +39 -34
  106. package/build/src/cli/runtime.js +12 -32
  107. package/build/src/core/facts/codec.js +7 -2
  108. package/build/src/core/facts/eligibility.d.ts +4 -4
  109. package/build/src/core/facts/eligibility.js +11 -0
  110. package/build/src/core/facts/fold.js +9 -5
  111. package/build/src/core/facts/gate.d.ts +5 -1
  112. package/build/src/core/facts/gate.js +14 -10
  113. package/build/src/core/facts/types.d.ts +5 -1
  114. package/build/src/core/facts/types.js +7 -0
  115. package/build/src/core/subject.d.ts +4 -1
  116. package/build/src/core/subject.js +10 -2
  117. package/build/src/core/verbs/amend.d.ts +15 -4
  118. package/build/src/core/verbs/amend.js +19 -9
  119. package/build/src/debt/board.d.ts +2 -1
  120. package/build/src/debt/board.js +3 -3
  121. package/build/src/debt/catalog.js +2 -1
  122. package/build/src/debt/document.d.ts +1 -0
  123. package/build/src/debt/document.js +3 -0
  124. package/build/src/debt/index.d.ts +2 -2
  125. package/build/src/debt/index.js +9 -14
  126. package/build/src/debt/input.d.ts +2 -1
  127. package/build/src/debt/input.js +6 -4
  128. package/build/src/debt/operations.d.ts +2 -1
  129. package/build/src/dispatch/index.d.ts +0 -17
  130. package/build/src/dispatch/index.js +1 -10
  131. package/build/src/git/identity.js +16 -45
  132. package/build/src/git/nuke.js +13 -23
  133. package/build/src/git/observe.d.ts +7 -3
  134. package/build/src/git/observe.js +29 -26
  135. package/build/src/git/process.js +11 -18
  136. package/build/src/git/read-observation.d.ts +5 -4
  137. package/build/src/git/repository.d.ts +2 -0
  138. package/build/src/git/repository.js +13 -1
  139. package/build/src/git/scratch.js +2 -14
  140. package/build/src/git/terminal-reconcile.js +1 -13
  141. package/build/src/history.d.ts +26 -0
  142. package/build/src/history.js +43 -0
  143. package/build/src/index.d.ts +6 -3
  144. package/build/src/kanshi/counts.d.ts +15 -1
  145. package/build/src/kanshi/counts.js +14 -3
  146. package/build/src/kanshi/index.d.ts +3 -4
  147. package/build/src/kanshi/index.js +2 -3
  148. package/build/src/kanshi/read.d.ts +21 -0
  149. package/build/src/kanshi/read.js +7 -3
  150. package/build/src/kanshi/report.d.ts +94 -0
  151. package/build/src/library/address.d.ts +12 -5
  152. package/build/src/library/address.js +18 -32
  153. package/build/src/library/akuma-creation.d.ts +39 -0
  154. package/build/src/library/akuma-creation.js +3 -9
  155. package/build/src/library/akumas.d.ts +5 -1
  156. package/build/src/library/akumas.js +11 -5
  157. package/build/src/library/continuation.d.ts +10 -0
  158. package/build/src/library/contract-composition.js +10 -10
  159. package/build/src/library/contract-creation.js +12 -13
  160. package/build/src/library/contract-outcomes.d.ts +72 -1
  161. package/build/src/library/contract-outcomes.js +1 -0
  162. package/build/src/library/contract-types.d.ts +233 -25
  163. package/build/src/library/contract-types.js +32 -12
  164. package/build/src/library/contract-wait.d.ts +212 -0
  165. package/build/src/library/contract-wait.js +65 -49
  166. package/build/src/library/delivery.d.ts +25 -0
  167. package/build/src/library/input.d.ts +8 -26
  168. package/build/src/library/input.js +17 -12
  169. package/build/src/library/kei.js +167 -90
  170. package/build/src/library/keiyaku-attribution.d.ts +1 -1
  171. package/build/src/library/keiyaku-attribution.js +3 -1
  172. package/build/src/library/keiyaku-classify.js +8 -4
  173. package/build/src/library/keiyaku-debt.d.ts +8 -7
  174. package/build/src/library/keiyaku-debt.js +1 -2
  175. package/build/src/library/keiyaku-identity.d.ts +4 -3
  176. package/build/src/library/keiyaku-identity.js +35 -7
  177. package/build/src/library/keiyaku-verbs.d.ts +974 -1409
  178. package/build/src/library/keiyaku-verbs.js +154 -161
  179. package/build/src/library/keiyaku-wait.d.ts +753 -0
  180. package/build/src/library/keiyaku-wait.js +230 -0
  181. package/build/src/library/keiyaku.d.ts +3110 -29
  182. package/build/src/library/keiyaku.js +342 -438
  183. package/build/src/library/model-tools.d.ts +754 -0
  184. package/build/src/library/model-tools.js +362 -0
  185. package/build/src/library/outcome.js +5 -6
  186. package/build/src/library/refusal.d.ts +25 -1
  187. package/build/src/library/refusal.js +4 -5
  188. package/build/src/library/selection.d.ts +18 -5
  189. package/build/src/library/selection.js +11 -5
  190. package/build/src/mcp/adapter.d.ts +0 -6
  191. package/build/src/mcp/adapter.js +11 -160
  192. package/build/src/mcp/description.d.ts +2 -0
  193. package/build/src/mcp/description.js +2 -0
  194. package/build/src/mcp/help.d.ts +1 -1
  195. package/build/src/mcp/help.js +10 -7
  196. package/build/src/pi/index.d.ts +5 -0
  197. package/build/src/pi/index.js +99 -0
  198. package/build/src/pi/status.d.ts +12 -0
  199. package/build/src/pi/status.js +140 -0
  200. package/build/src/protocol/amend.d.ts +14 -3
  201. package/build/src/protocol/amend.js +113 -46
  202. package/build/src/protocol/bind.d.ts +1 -1
  203. package/build/src/protocol/bind.js +5 -16
  204. package/build/src/protocol/completion.d.ts +30 -0
  205. package/build/src/protocol/completion.js +8 -5
  206. package/build/src/protocol/deliver.js +7 -20
  207. package/build/src/protocol/delivery-preview.d.ts +5 -0
  208. package/build/src/protocol/execution-observation.d.ts +8 -0
  209. package/build/src/protocol/intent.d.ts +1 -0
  210. package/build/src/protocol/intent.js +4 -1
  211. package/build/src/protocol/operations.d.ts +56 -16
  212. package/build/src/protocol/operations.js +18 -32
  213. package/build/src/protocol/placement.js +7 -1
  214. package/build/src/protocol/progress.js +0 -6
  215. package/build/src/protocol/read/status.d.ts +52 -4
  216. package/build/src/protocol/read/status.js +26 -22
  217. package/build/src/protocol/reintegrate.js +2 -2
  218. package/build/src/protocol/result-leaves.d.ts +56 -8
  219. package/build/src/protocol/result-leaves.js +11 -2
  220. package/build/src/protocol/run.js +1 -4
  221. package/build/src/protocol/verify.d.ts +10 -0
  222. package/build/src/protocol/verify.js +1 -0
  223. package/build/src/runtime/proc/windows-launch.exe +0 -0
  224. package/build/src/settlement/settle.js +19 -68
  225. package/package.json +7 -3
  226. package/plugins/paseo/plugin/index.server.ts +6 -2
  227. package/plugins/paseo/plugin/server/attach.ts +68 -48
  228. package/plugins/paseo/plugin/server/directory.ts +259 -0
  229. package/plugins/paseo/plugin/server/mirror-identity.ts +3 -32
  230. package/plugins/paseo/plugin/server/reopen.ts +52 -38
  231. package/plugins/pi/README.md +55 -97
  232. package/plugins/pi/keiyaku.ts +1 -142
  233. package/skills/keiyaku-akuma/SKILL.md +18 -11
  234. package/skills/keiyaku-babysit/SKILL.md +8 -6
  235. package/skills/keiyaku-debt/SKILL.md +2 -1
  236. package/skills/keiyaku-workflow/SKILL.md +2 -1
  237. package/build/plugins/pi/akuma-tools.ts +0 -283
  238. package/build/src/body/keys.d.ts +0 -4
  239. package/build/src/body/keys.js +0 -11
  240. package/build/src/kanshi/roster.d.ts +0 -2
  241. package/build/src/kanshi/roster.js +0 -2
  242. package/build/src/mcp/output.d.ts +0 -385
  243. package/build/src/mcp/output.js +0 -193
  244. package/plugins/pi/akuma-tools.ts +0 -283
@@ -0,0 +1,259 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import type { OwnedSubscription, PaseoAgent, PaseoAgentListResult, PaseoApi } from "@getpaseo/client";
3
+ import { persistedMirrorIdentity } from "./mirror-identity.js";
4
+ import { raceAbort } from "./transport.js";
5
+
6
+ const FILTER = { includeArchived: true, includeBackground: true };
7
+ const STATUS_GROUPS: PaseoAgent["status"][][] = [["running", "initializing"], ["idle", "error", "closed"]];
8
+ const MAX_BUFFERED_AGENTS = 4096;
9
+ type Candidate = Readonly<Pick<PaseoAgent, "id" | "archivedAt">>;
10
+ type Fact = Candidate & Readonly<{
11
+ updatedAt: string;
12
+ native?: { provider: string; sessionId: string };
13
+ mirror?: { world: string; akuId: string };
14
+ }>;
15
+ type Generation = {
16
+ controller: AbortController;
17
+ subscription?: OwnedSubscription<PaseoAgentListResult>;
18
+ unsubscribe?: () => void;
19
+ subscriptionId?: string;
20
+ complete: boolean;
21
+ facts: Map<string, Fact>;
22
+ members: Map<string, Set<string>>;
23
+ revisions: Map<string, number>;
24
+ buffered: Map<string, Fact | undefined>;
25
+ seed: Promise<void>;
26
+ };
27
+
28
+ export class StaleDirectory extends Error {
29
+ constructor(message = "Paseo directory evidence changed") { super(message); }
30
+ }
31
+
32
+ function fact(agent: PaseoAgent): Fact {
33
+ const persistence = agent.persistence;
34
+ const provider = persistence?.metadata?.provider ?? persistence?.provider;
35
+ const mirror = persistedMirrorIdentity(agent);
36
+ return { id: agent.id, archivedAt: agent.archivedAt, updatedAt: agent.updatedAt,
37
+ ...(typeof provider === "string" && persistence?.sessionId
38
+ ? { native: { provider, sessionId: persistence.sessionId } } : {}),
39
+ ...(mirror ? { mirror } : {}),
40
+ };
41
+ }
42
+ const nativeKey = (provider: string, sessionId: string) => JSON.stringify(["native", provider, sessionId]);
43
+ const mirrorKey = (akuId: string) => JSON.stringify(["mirror", akuId]);
44
+ const keys = (value: Fact) => [
45
+ ...(value.native ? [nativeKey(value.native.provider, value.native.sessionId)] : []),
46
+ ...(value.mirror ? [mirrorKey(value.mirror.akuId)] : []),
47
+ ];
48
+ const identity = ({ updatedAt: _updatedAt, ...value }: Fact) => JSON.stringify(value);
49
+
50
+ /** One activation owns this directory, independently of registration handoff. */
51
+ export function createDirectoryIndex() {
52
+ let current: Generation | undefined;
53
+ let closed = false;
54
+ const jobs = new Set<Promise<unknown>>();
55
+ const track = <T>(job: Promise<T>): Promise<T> => {
56
+ jobs.add(job);
57
+ void job.finally(() => jobs.delete(job)).catch(() => {});
58
+ return job;
59
+ };
60
+ const release = (subscription: OwnedSubscription<PaseoAgentListResult>) => track(subscription.release().catch((error: unknown) => {
61
+ console.warn(`Keiyaku directory subscription cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
62
+ }));
63
+ function retire(generation: Generation, reason: unknown = new StaleDirectory()): void {
64
+ if (current === generation) current = undefined;
65
+ generation.complete = false;
66
+ generation.controller.abort(reason);
67
+ generation.unsubscribe?.();
68
+ delete generation.unsubscribe;
69
+ const subscription = generation.subscription;
70
+ delete generation.subscription;
71
+ if (subscription) void release(subscription);
72
+ generation.buffered.clear();
73
+ }
74
+ function check(generation: Generation): void {
75
+ generation.controller.signal.throwIfAborted();
76
+ if (!generation.subscriptionId || generation.subscription?.subscriptionId !== generation.subscriptionId) {
77
+ retire(generation);
78
+ throw new StaleDirectory("Paseo directory connection changed");
79
+ }
80
+ }
81
+ function replace(generation: Generation, id: string, value?: Fact): void {
82
+ const prior = generation.facts.get(id);
83
+ if (prior && value && identity(prior) === identity(value)) {
84
+ generation.facts.set(id, value);
85
+ return;
86
+ }
87
+ const affected = new Set([...(prior ? keys(prior) : []), ...(value ? keys(value) : [])]);
88
+ if (prior) for (const key of keys(prior)) {
89
+ const members = generation.members.get(key)!;
90
+ members.delete(id);
91
+ if (!members.size) generation.members.delete(key);
92
+ }
93
+ generation.facts.delete(id);
94
+ if (value && keys(value).length) {
95
+ generation.facts.set(id, value);
96
+ for (const key of keys(value)) {
97
+ let members = generation.members.get(key);
98
+ if (!members) generation.members.set(key, members = new Set());
99
+ members.add(id);
100
+ }
101
+ }
102
+ for (const key of affected) generation.revisions.set(key, (generation.revisions.get(key) ?? 0) + 1);
103
+ }
104
+ async function bootstrap(generation: Generation, paseo: PaseoApi): Promise<void> {
105
+ const signal = AbortSignal.any([generation.controller.signal, AbortSignal.timeout(4000)]);
106
+ try {
107
+ // The owned stream covers the filter, regardless of this bounded page.
108
+ const result = await raceAbort(signal, () => track(paseo.agents.list({ filter: FILTER,
109
+ page: { limit: 1 }, subscribe: {}, signal: generation.controller.signal }).then((result) => {
110
+ if (generation.controller.signal.aborted) {
111
+ void release(result.subscription);
112
+ throw new StaleDirectory();
113
+ }
114
+ generation.subscription = result.subscription;
115
+ return result;
116
+ })));
117
+ const unsubscribe = result.subscription.subscribe({
118
+ snapshot(snapshot) {
119
+ if (generation.controller.signal.aborted) return;
120
+ if (generation.subscriptionId !== undefined) { retire(generation); return; }
121
+ generation.subscriptionId = snapshot.subscriptionId;
122
+ },
123
+ update(message) {
124
+ if (generation.controller.signal.aborted || message.type !== "agent_update") return;
125
+ try {
126
+ check(generation);
127
+ const update = message.payload;
128
+ const id = update.kind === "upsert" ? update.agent.id : update.agentId;
129
+ const value = update.kind === "upsert" ? fact(update.agent) : undefined;
130
+ if (generation.complete) replace(generation, id, value);
131
+ else {
132
+ generation.buffered.set(id, value);
133
+ if (generation.buffered.size > MAX_BUFFERED_AGENTS) retire(generation, new StaleDirectory("Paseo directory bootstrap update overflow"));
134
+ }
135
+ } catch (error) { retire(generation, error); }
136
+ },
137
+ error(error) { retire(generation, error); },
138
+ });
139
+ generation.unsubscribe = unsubscribe;
140
+ if (generation.controller.signal.aborted) { unsubscribe(); delete generation.unsubscribe; }
141
+ check(generation);
142
+ const staged = new Map<string, Fact>();
143
+ for (const statuses of STATUS_GROUPS) {
144
+ const seen = new Set<string>();
145
+ let cursor: string | undefined;
146
+ for (;;) {
147
+ const page = await raceAbort(signal, () => paseo.agents.list({ filter: { ...FILTER, statuses }, signal,
148
+ page: { limit: 200, ...(cursor ? { cursor } : {}) } }));
149
+ check(generation);
150
+ for (const { agent } of page.entries) {
151
+ const value = fact(agent);
152
+ const prior = staged.get(value.id);
153
+ if (!prior || Date.parse(value.updatedAt) >= Date.parse(prior.updatedAt)) staged.set(value.id, value);
154
+ }
155
+ if (!page.pageInfo.hasMore) break;
156
+ const next = page.pageInfo.nextCursor;
157
+ if (!next || seen.has(next)) throw new Error("incomplete Paseo agent directory pagination");
158
+ seen.add(next);
159
+ cursor = next;
160
+ }
161
+ }
162
+ for (const [id, value] of generation.buffered) {
163
+ if (!value) {
164
+ if (staged.has(id)) throw new StaleDirectory("unordered Paseo directory removal during bootstrap");
165
+ } else {
166
+ const prior = staged.get(id);
167
+ // OwnedSubscription replays updates from before page reads. Never let
168
+ // an older replay undo a newer page; equal conflicting facts cannot prove identity.
169
+ if (prior && identity(prior) !== identity(value)) {
170
+ const order = Date.parse(value.updatedAt) - Date.parse(prior.updatedAt);
171
+ if (order < 0) continue;
172
+ if (!(order > 0)) throw new StaleDirectory("conflicting Paseo directory bootstrap facts");
173
+ }
174
+ staged.set(id, value);
175
+ }
176
+ }
177
+ check(generation);
178
+ for (const value of staged.values()) replace(generation, value.id, value);
179
+ generation.buffered.clear();
180
+ generation.complete = true;
181
+ } catch (error) {
182
+ retire(generation, error);
183
+ throw error;
184
+ }
185
+ }
186
+ return {
187
+ async read(paseo: PaseoApi, signal: AbortSignal) {
188
+ signal.throwIfAborted();
189
+ if (closed) throw new Error("Keiyaku directory index is closed");
190
+ if (current?.complete) {
191
+ try { check(current); } catch { /* Ordinary demand rebuilds disconnected evidence. */ }
192
+ }
193
+ if (!current) {
194
+ const generation: Generation = { controller: new AbortController(), complete: false, facts: new Map(),
195
+ members: new Map(), revisions: new Map(), buffered: new Map(), seed: Promise.resolve() };
196
+ current = generation;
197
+ generation.seed = track(bootstrap(generation, paseo));
198
+ }
199
+ const generation = current;
200
+ await raceAbort(signal, () => generation.seed);
201
+ check(generation);
202
+ const watched = new Map<string, { revision: number; count: number }>();
203
+ function assertCurrent(): void {
204
+ signal.throwIfAborted();
205
+ check(generation);
206
+ for (const [key, { revision }] of watched) if ((generation.revisions.get(key) ?? 0) !== revision) throw new StaleDirectory();
207
+ }
208
+ function candidates(key: string): Fact[] {
209
+ assertCurrent();
210
+ const members = generation.members.get(key);
211
+ watched.set(key, { revision: generation.revisions.get(key) ?? 0, count: members?.size ?? 0 });
212
+ return [...members ?? []].map((id) => generation.facts.get(id)!);
213
+ }
214
+ return {
215
+ signal: generation.controller.signal,
216
+ assertCurrent,
217
+ native(provider: string, sessionId: string): readonly Candidate[] { return candidates(nativeKey(provider, sessionId)); },
218
+ async mirrors(world: string, akuId: string): Promise<readonly Candidate[]> {
219
+ const matching: Candidate[] = [];
220
+ for (const value of candidates(mirrorKey(akuId))) {
221
+ let canonical: string;
222
+ try { canonical = await realpath(value.mirror!.world); }
223
+ catch { throw new Error(`unreadable mirror World for ${akuId}`); }
224
+ if (canonical === world) matching.push(value);
225
+ }
226
+ assertCurrent();
227
+ return matching;
228
+ },
229
+ changed(message?: string): never { assertCurrent(); retire(generation); throw new StaleDirectory(message ?? "Paseo exact agent identity changed"); },
230
+ created(agent: PaseoAgent): void {
231
+ signal.throwIfAborted();
232
+ check(generation);
233
+ const value = fact(agent);
234
+ const ownKey = mirrorKey(value.mirror!.akuId);
235
+ for (const [key, { revision, count }] of watched) {
236
+ const latest = generation.revisions.get(key) ?? 0;
237
+ if (latest === revision) continue;
238
+ // The host may publish our creation before its response. Accept only
239
+ // that single addition, preserving every other watched identity.
240
+ const members = generation.members.get(key);
241
+ const published = generation.facts.get(value.id);
242
+ if (key !== ownKey || latest !== revision + 1 || !published || identity(published) !== identity(value) ||
243
+ members?.size !== count + 1) throw new StaleDirectory();
244
+ }
245
+ replace(generation, agent.id, value);
246
+ watched.set(ownKey, { revision: generation.revisions.get(ownKey) ?? 0, count: generation.members.get(ownKey)!.size });
247
+ assertCurrent();
248
+ },
249
+ };
250
+ },
251
+ async close(): Promise<void> {
252
+ closed = true;
253
+ if (current) retire(current, new Error("Keiyaku directory index is closed"));
254
+ while (jobs.size) await Promise.allSettled([...jobs]);
255
+ },
256
+ };
257
+ }
258
+ export type DirectoryIndex = ReturnType<typeof createDirectoryIndex>;
259
+ export type DirectoryEvidence = Awaited<ReturnType<DirectoryIndex["read"]>>;
@@ -1,9 +1,7 @@
1
1
  import { realpath } from "node:fs/promises";
2
- import type { PaseoAgent, PaseoApi } from "@getpaseo/client";
2
+ import type { PaseoAgent } from "@getpaseo/client";
3
3
  import { z } from "zod";
4
- import { raceAbort } from "./transport.js";
5
4
 
6
- const PAGE_SIZE = 200;
7
5
  const mirrorPersistence = z.object({ version: z.literal(1),
8
6
  data: z.object({ world: z.string(), akuId: z.string() }) });
9
7
 
@@ -14,8 +12,8 @@ export function persistedMirrorIdentity(agent: PaseoAgent): { world: string; aku
14
12
  ? parsed.data.data : undefined;
15
13
  }
16
14
 
17
- export async function matchesCanonicalMirror(agent: PaseoAgent, world: string, akuId: string): Promise<boolean> {
18
- if (agent.archivedAt) return false;
15
+ export async function matchesCanonicalMirror(agent: PaseoAgent, world: string, akuId: string, includeArchived = false): Promise<boolean> {
16
+ if (agent.archivedAt && !includeArchived) return false;
19
17
  const identity = persistedMirrorIdentity(agent);
20
18
  if (!identity || identity.akuId !== akuId) return false;
21
19
  try {
@@ -24,30 +22,3 @@ export async function matchesCanonicalMirror(agent: PaseoAgent, world: string, a
24
22
  return false;
25
23
  }
26
24
  }
27
-
28
- export async function listMirrorCandidates(paseo: PaseoApi, world: string, akuId: string,
29
- includeArchived = false, signal?: AbortSignal): Promise<PaseoAgent[]> {
30
- const candidates: PaseoAgent[] = [];
31
- const seenCursors = new Set<string>();
32
- let cursor: string | undefined;
33
- for (;;) {
34
- const list = () => paseo.agents.list({ filter: { includeArchived: true, includeBackground: true },
35
- ...(signal ? { signal } : {}), page: { limit: PAGE_SIZE, ...(cursor ? { cursor } : {}) } });
36
- const page = await (signal ? raceAbort(signal, list) : list());
37
- for (const { agent } of page.entries) {
38
- if (agent.archivedAt && !includeArchived) continue;
39
- const identity = persistedMirrorIdentity(agent);
40
- if (!identity || identity.akuId !== akuId) continue;
41
- try {
42
- if (await realpath(identity.world) === world) candidates.push(agent);
43
- } catch {
44
- throw new Error(`unreadable mirror World for ${akuId}`);
45
- }
46
- }
47
- if (!page.pageInfo.hasMore) return candidates;
48
- const next = page.pageInfo.nextCursor;
49
- if (!next || next === cursor || seenCursors.has(next)) throw new Error("incomplete Paseo agent directory pagination");
50
- seenCursors.add(next);
51
- cursor = next;
52
- }
53
- }
@@ -1,43 +1,57 @@
1
1
  import { realpath } from "node:fs/promises";
2
- import type { PaseoAgent, PaseoAgentHandle, PaseoApi } from "@getpaseo/client";
3
- import { listMirrorCandidates, matchesCanonicalMirror } from "./mirror-identity.js";
2
+ import type { PaseoAgentTimelineHandle, PaseoApi } from "@getpaseo/client";
3
+ import { matchesCanonicalMirror } from "./mirror-identity.js";
4
+ import { StaleDirectory, type DirectoryIndex } from "./directory.js";
5
+ import { raceAbort } from "./transport.js";
4
6
 
5
- const reopenInFlight = new Map<string, Promise<boolean>>();
7
+ type Target = { world: string; akuId: string };
6
8
 
7
- async function reopenOne(paseo: PaseoApi, candidate: PaseoAgent, world: string, akuId: string): Promise<boolean> {
8
- const current = await paseo.agents.ref(candidate.id).refresh();
9
- if (!current || !(await matchesCanonicalMirror(current.agent, world, akuId))) return false;
10
- const handle: PaseoAgentHandle = paseo.agents.ref(current.agent);
11
- const timeline = await handle.timeline.refetch({ limit: 0 });
12
- if (timeline.error || !timeline.agent || !(await matchesCanonicalMirror(timeline.agent, world, akuId))) return false;
13
- return true;
14
- }
15
-
16
- export async function refreshOrReopen(paseo: PaseoApi, input: { world: string; akuId: string },
17
- refreshLocal: (input: { world: string; akuId: string }) => Promise<{ woken: number }>): Promise<{ woken: number }> {
18
- const world = await realpath(input.world);
19
- const local = await refreshLocal({ world, akuId: input.akuId });
20
- if (local.woken > 0) return local;
21
-
22
- let candidates: PaseoAgent[];
23
- try {
24
- candidates = await listMirrorCandidates(paseo, world, input.akuId);
25
- } catch (error) {
26
- console.warn(`Keiyaku mirror refresh skipped: ${error instanceof Error ? error.message : String(error)}`);
27
- return { woken: 0 };
28
- }
29
- let woken = 0;
30
- for (const candidate of candidates) {
31
- const key = `${candidate.id}\0${world}\0${input.akuId}`;
32
- let reopening = reopenInFlight.get(key);
33
- if (!reopening) {
34
- reopening = reopenOne(paseo, candidate, world, input.akuId).catch((error: unknown) => {
35
- console.warn(`Keiyaku mirror ${candidate.id} was not reopened: ${error instanceof Error ? error.message : String(error)}`);
36
- return false;
37
- }).finally(() => reopenInFlight.delete(key));
38
- reopenInFlight.set(key, reopening);
9
+ /** Recovery and attachment share the activation's current-connection directory. */
10
+ export function createReopener(directory: DirectoryIndex) {
11
+ type Timeline = ReturnType<PaseoAgentTimelineHandle["refetch"]>;
12
+ const inFlight = new Map<string, { signal: AbortSignal; result: Timeline }>();
13
+ return async function refreshOrReopen(paseo: PaseoApi, input: Target,
14
+ refreshLocal: (input: Target) => Promise<{ woken: number }>): Promise<{ woken: number }> {
15
+ const world = await realpath(input.world);
16
+ const local = await refreshLocal({ world, akuId: input.akuId });
17
+ if (local.woken > 0) return local;
18
+ const signal = AbortSignal.timeout(4000);
19
+ try {
20
+ return await raceAbort(signal, async () => {
21
+ for (let attempt = 0; ; attempt++) {
22
+ try {
23
+ const evidence = await directory.read(paseo, signal);
24
+ // Archived mappings still count towards ambiguity.
25
+ const candidates = await evidence.mirrors(world, input.akuId);
26
+ if (candidates.length !== 1 || candidates[0]!.archivedAt) return { woken: 0 };
27
+ const candidate = candidates[0]!;
28
+ const current = await raceAbort(signal, () => paseo.agents.ref(candidate.id).refresh());
29
+ evidence.assertCurrent();
30
+ if (!current) return evidence.changed(`mirror ${candidate.id} disappeared`);
31
+ if (current.agent.id !== candidate.id || !(await matchesCanonicalMirror(current.agent, world, input.akuId)))
32
+ return evidence.changed(`mirror ${candidate.id} changed identity or archive state`);
33
+ evidence.assertCurrent();
34
+ const key = `${candidate.id}\0${world}\0${input.akuId}`;
35
+ let reopening = inFlight.get(key);
36
+ if (!reopening || reopening.signal !== evidence.signal) {
37
+ reopening = { signal: evidence.signal, result: paseo.agents.ref(current.agent).timeline.refetch({ limit: 0 }) };
38
+ inFlight.set(key, reopening);
39
+ void reopening.result.finally(() => { if (inFlight.get(key) === reopening) inFlight.delete(key); }).catch(() => {});
40
+ }
41
+ const timeline = await raceAbort(signal, () => reopening!.result);
42
+ evidence.assertCurrent();
43
+ const matched = !timeline.error && timeline.agent?.id === candidate.id &&
44
+ await matchesCanonicalMirror(timeline.agent, world, input.akuId);
45
+ evidence.assertCurrent();
46
+ return { woken: matched ? 1 : 0 };
47
+ } catch (error) {
48
+ if (!(error instanceof StaleDirectory) || attempt === 1) throw error;
49
+ }
50
+ }
51
+ });
52
+ } catch (error) {
53
+ console.warn(`Keiyaku mirror refresh skipped: ${error instanceof Error ? error.message : String(error)}`);
54
+ return { woken: 0 };
39
55
  }
40
- if (await reopening) woken++;
41
- }
42
- return { woken };
56
+ };
43
57
  }
@@ -1,119 +1,77 @@
1
1
  # Keiyaku in Pi
2
2
 
3
- The existing Pi package entry `plugins/pi/keiyaku.ts` supplies `/keiyaku` (the
4
- status overlay) and registers the package's MCP server for each Pi session. The
5
- 24 MCP tools use `codemode` exposure; no separate `mcp.json` entry or global
6
- `keiyaku-mcp` binary is required. The ten native Akuma tools are temporarily registered with
7
- Pi's `hidden` exposure while their design is unfinished: they are not declared
8
- to the model, discoverable, or callable, even if selected explicitly. The CLI
9
- and `/keiyaku` command remain available. The implementation is retained for
10
- development. It imports only the supported
11
- `@astrosheep/keiyaku` package root. Build the checkout before loading it locally;
12
- an installed npm package already carries its built SDK.
3
+ The shipped Pi entry `plugins/pi/keiyaku.ts` registers native `keiyaku_*` tools
4
+ with `codemode` exposure, supplies `/keiyaku` (the Kanshi overlay), and keeps a
5
+ live status entry. It does not register a Keiyaku MCP server. No `mcp.json`
6
+ entry or global `keiyaku-mcp` binary is required.
7
+
8
+ The extension uses the supported package root for status and `@astrosheep/keiyaku/pi`
9
+ for tool registration. Build a checkout before loading it locally; installed
10
+ packages already carry both compiled entries.
13
11
 
14
12
  ```sh
15
- # Existing installation path; no separate experimental package
16
13
  keiyaku install pi
17
14
  # One-invocation local development, after npm run build
18
15
  pi --extension ./plugins/pi/keiyaku.ts
19
16
  ```
20
17
 
21
- ## Native status
22
-
23
- Interactive Pi sessions show a compact status entry with the current World's
24
- running Akuma, active Contracts, and open Debts across all namespaces. A zero
25
- is an observed empty count; `-` means absent and `?` means unknown or failed.
26
- The entry refreshes after each completed read (five seconds later) and when the
27
- agent settles. It starts with the session and is removed on shutdown or reload;
28
- non-terminal modes do not run the sampler. The `/keiyaku` overlay and native
29
- tools are unchanged.
30
-
31
- ## Native tools
32
-
33
- All tools return the SDK result in `details`, `structuredContent`, and JSON
34
- text. Typed refusals and partial birth results remain data. An exceptional
35
- failure retaining a born Akuma also retains its identity in structured error
36
- data. No native tool shells out to the CLI.
37
-
38
- | Tool | Parameters |
39
- | --- | --- |
40
- | `akuma_spawn` | `akuma` definition name, `body`; optional `workdir`, `detach`, `bare`, `wait`, `timeoutMs` |
41
- | `akuma_status` | `akuma`; optional `repo` |
42
- | `akuma_list` | optional `akumaName`, `limit` |
43
- | `akuma_definitions` | optional `limit` |
44
- | `akuma_tell` | `akuma`, `body`; optional `interrupt`, `detach`, `repo`, `wait`, `timeoutMs` |
45
- | `akuma_ask` | `akuma`, `body`, `schema`; optional `interrupt`, `detach`, `timeoutMs`, `repo` |
46
- | `akuma_wait` | `akuma` array; optional `completion` (`any` or `all`), `timeoutMs`, `repo` |
47
- | `akuma_history` | `akuma`; optional `id`, `last`, `before`, `since`, `limit`, `repo` |
48
- | `akuma_fork` | `akuma`, `at`; optional `detach`, `bare`, `repo` |
49
- | `akuma_kill` | one `akuma` selector; optional `repo` |
50
-
51
- `akuma_spawn` supports every configured provider, not only Pi. Default
52
- `detach: false` launches in the calling Pi session's in-process host scope.
53
- Default `wait: false` returns after birth and first-input admission; these are
54
- **independent choices**. `wait: true` observes the first answer for up to five
55
- minutes by default. `timeoutMs` on spawn requires `wait: true`.
56
- Spawn and Fork pass `bare` through to the SDK: it omits only Keiyaku runtime
57
- instructions and remains frozen through wake and inherited by forks. Providers
58
- without a verified runtime-instruction channel retain their explicit refusal
59
- unless the caller opts out.
60
-
61
- ```json
62
- {"akuma":"worker","body":"Inspect the parser without changing files."}
63
- {"akuma":"worker","body":"Run the checks.","detach":true,"wait":true,"timeoutMs":300000}
18
+ ## Native tools through codemode
19
+
20
+ Every published Keiyaku model tool is registered once when the extension loads,
21
+ under the `keiyaku` namespace. Names prefix the shared catalogue with `keiyaku_`;
22
+ for example, `spawn` becomes `keiyaku_spawn` and `debt.add` becomes
23
+ `keiyaku_debt_add`. Inputs flatten coordinate and business fields into one
24
+ object. Descriptions, annotations, schemas and compact routing projections are
25
+ shared with the standalone MCP adapter, not maintained as another tool list.
26
+ Text uses the existing Keiyaku renderer. Business failures return `isError` with
27
+ failure data where available, rather than throwing away their evidence.
28
+
29
+ ```js
30
+ const ns = await describeNamespace("keiyaku");
31
+ text(ns);
32
+ text(await tools.keiyaku_kanshi({}));
33
+ text(await tools.keiyaku_spawn({akumaName: "intern", prompt: "Inspect the tests"}));
64
34
  ```
65
35
 
66
- Tell, Ask and Fork explicitly select future launch hosting through their own
67
- `detach` option, also defaulting to false. A running Body never moves hosts. A
68
- sleeping Akuma can be woken in the current session even if another host created
69
- it. Ordinary CLI defaults and `--wait` semantics are unchanged.
70
-
71
- World resolves from Pi's `ctx.cwd`. Relative `workdir` and `repo` paths resolve
72
- there too; `repo` supplies Git association/selector context, not a different
73
- World. Caller attribution comes from the current Pi session manager, not ambient
74
- parent Akuma or harness environment declarations. Single targets accept IDs or
75
- World-local aliases. Wait accepts a batch of IDs, aliases or globs. Kill accepts
76
- one selector, including a glob or Contract selector (the latter needs `repo`),
77
- which may expand to several Akumas with one stop result per member. History `id` and Fork `at` are exact returned `turn/n`
78
- identities. Exact history cannot combine with paging or `last`.
79
-
80
- Ask/Wait are unbounded unless `timeoutMs` is supplied. Tell observes its exact
81
- text answer with `wait: true`; its optional `timeoutMs` requires that choice.
82
- Deadline or tool abort ends observation, not admitted work. Ask requires a JSON
83
- Schema document as the provider answer contract and returns parsed JSON without
84
- local schema validation. Tell and spawn carry text only. Schema input to busy
85
- work retains the SDK refusal.
36
+ At `session_start` the extension activates a registered `codemode` tool that
37
+ declares `reachesTools`. The normal Pi CLI includes codemode. SDK hosts must
38
+ load `createCodemodeExtension()` themselves. If it is missing, the extension
39
+ warns once; it never makes Keiyaku tools directly exposed as a fallback.
86
40
 
87
- ## Lifetime
41
+ Each call uses the current context's working directory and session ID. Complete
42
+ Akuma actor declarations take precedence; otherwise the invoking Pi session is
43
+ the explicit caller, ignoring inherited native host IDs. Partial actor
44
+ declarations still refuse. Caller attribution does not rewrite the independently
45
+ selected notification initiator. Neither settings nor process environment is
46
+ modified by the adapter.
47
+
48
+ ## Status and `/keiyaku`
88
49
 
89
- The extension owns one `AkumaHost.inProcess()` scope per Pi session. Orderly
90
- `session_shutdown` closes only that scope's exact in-process launches, including
91
- setup and automatic succession. It never kills by AkuId, so an older session
92
- cannot stop a foreign host's later wake of the same identity. Detached work
93
- survives. Reload and session replacement follow Pi's shutdown/start lifecycle.
50
+ Interactive Pi sessions show counts for running Akumas, active Contracts, and
51
+ open Debts across all namespaces. `0` is observed empty, `-` is absent, and `?`
52
+ is unknown or failed. The sampler refreshes five seconds after each read and on
53
+ `agent_settled`; shutdown or reload removes it. Non-TUI modes run no sampler.
94
54
 
95
- Native tools use the same local SDK composition in external and provider-owned
96
- Pi sessions. Each session owns its own in-process host scope and caller identity.
97
- CLI operations in native tool children likewise run their ordinary local owners.
55
+ `/keiyaku` opens a centered, read-only overlay of `keiyaku kanshi` from `PATH`.
56
+ A failed read shows `status unavailable`. Native model tools do not invoke the
57
+ CLI or a stdio server.
58
+
59
+ ## Lifetime
98
60
 
99
- In-process hosting is shared lifetime, not a sandbox: arbitrary extensions can
100
- block or terminate the runtime. A noncooperative tool/provider can remain
101
- physically live after the Body records hung and releases its leash. Scope close
102
- rejects with that exact launch's retained failure; it never reports physical
103
- retirement based on a later Body's status. Abrupt host death has no graceful
104
- cleanup guarantee, and no daemon or persisted host policy recovers live objects.
105
- Child model usage is not rolled into an already-returned parent tool result.
61
+ Workers use ordinary detached execution, with no per-session Akuma host.
62
+ Cancelling a tool observation or closing Pi does not kill admitted work. Spawn
63
+ and tell return admission; wait observes existing work and ask observes its
64
+ exact structured answer. There is no MCP request timeout around native calls.
106
65
 
107
66
  ## Verification
108
67
 
109
68
  ```sh
110
69
  npm run build
111
- npm test -- tests/akuma-in-process.test.ts tests/pi-akuma-tools.test.ts tests/pi-extension.test.ts tests/package-consumers.test.ts
70
+ npm test -- tests/pi-keiyaku-tools.test.ts tests/keiyaku-caller.test.ts tests/pi-extension.test.ts tests/pi-status.test.ts tests/mcp-adapter.test.ts tests/package-consumers.test.ts
112
71
  ```
113
72
 
114
- The native-tool tests verify that the built package's default extension keeps
115
- the tools hidden. An explicit development fixture registers the same implementation
116
- with direct exposure and executes a deterministic offline model through real Pi tool calls,
117
- SDK operations, Heart/leash, subprocess tools and detached launches. They do not
118
- replace the Body engine or depend on model credentials. These are not real-model
119
- quality or OS sandbox tests.
73
+ The native integration tests load the shipped entry with the real Pi SDK loader,
74
+ run actual QuickJS codemode scripts against an offline synthetic model, and
75
+ launch a real detached ACP fixture. They compare MCP declarations and read
76
+ results, exercise attribution, and retain worker lifetime across observation
77
+ cancellation and session shutdown.