@astrosheep/keiyaku 4.6.24 → 4.6.26

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.
@@ -51,7 +51,7 @@ type InterruptAdmission = Extract<InterruptTellAdmission, {
51
51
  }>, "kind"> & Readonly<{
52
52
  kind: "admitted";
53
53
  }>);
54
- export declare function settleAkumaKill(paths: AkumaPaths, signal?: AbortSignal, retainLeash?: boolean): Promise<Readonly<{
54
+ export declare function settleAkumaKill(paths: AkumaPaths, signal?: AbortSignal, retainLeash?: boolean, admitted?: () => void): Promise<Readonly<{
55
55
  evidence: KillEvidence;
56
56
  leash?: HeldAkumaLeash;
57
57
  }>>;
@@ -47,8 +47,9 @@ async function takeLeashUntilSignal(paths, bodySequence, signal) {
47
47
  return { kind: "unavailable", evidence: "untidy" };
48
48
  return { kind: "unavailable", evidence: "unavailable" };
49
49
  }
50
- export async function settleAkumaKill(paths, signal, retainLeash = false) {
50
+ export async function settleAkumaKill(paths, signal, retainLeash = false, admitted) {
51
51
  const request = await requestStop(paths, new Date().toISOString(), signal);
52
+ admitted?.();
52
53
  if (request.kind !== "requested") {
53
54
  // A witnessed Body was already settled: the kill witness Heart recorded is
54
55
  // the kill evidence, not a stop outcome.
@@ -92,11 +93,14 @@ export async function settleAkumaKill(paths, signal, retainLeash = false) {
92
93
  }
93
94
  }
94
95
  export async function killAkumaWithRecovery(paths, recover, signal) {
96
+ let admitted = false;
95
97
  try {
96
- return (await settleAkumaKill(paths, signal)).evidence;
98
+ return (await settleAkumaKill(paths, signal, false, () => {
99
+ admitted = true;
100
+ })).evidence;
97
101
  }
98
102
  finally {
99
- if (recover !== undefined)
103
+ if (admitted && recover !== undefined)
100
104
  void recover(paths).catch(() => undefined);
101
105
  }
102
106
  }
@@ -333,6 +333,7 @@ async function runBodyTurns(input) {
333
333
  await putDownIfControlled(launch.paths, supervisor, bodySequence, runtime.now, turnOutcome);
334
334
  return;
335
335
  }
336
+ await supervisor.refresh();
336
337
  continue;
337
338
  }
338
339
  const schema = launchTells.find((tell) => tell.schemaJson !== undefined)?.schemaJson ?? launch.initialSchemaJson;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrosheep/keiyaku",
3
- "version": "4.6.24",
3
+ "version": "4.6.26",
4
4
  "workspaces": [
5
5
  "plugins/square",
6
6
  "plugins/paseo/forwarder"
@@ -65,8 +65,8 @@
65
65
  },
66
66
  "devDependencies": {
67
67
  "@earendil-works/pi-coding-agent": "^1.4.0",
68
- "@getpaseo/plugin": "0.11.2",
69
- "@getpaseo/server": "0.11.2",
68
+ "@getpaseo/plugin": "0.14.0",
69
+ "@getpaseo/server": "0.14.0",
70
70
  "@types/cross-spawn": "^6.0.6",
71
71
  "@types/node": "^25.0.0",
72
72
  "@types/ws": "^8.18.2",
@@ -81,10 +81,10 @@
81
81
  "dependencies": {
82
82
  "@agentclientprotocol/sdk": "^1.3.0",
83
83
  "@anthropic-ai/claude-agent-sdk": "^0.3.226",
84
- "@astrosheep/keiyaku-plugin-square": "0.1.18",
85
- "@astrosheep/square": "^0.3.104",
86
- "@getpaseo/client": "0.11.2",
87
- "@getpaseo/protocol": "0.11.2",
84
+ "@astrosheep/keiyaku-plugin-square": "0.1.20",
85
+ "@astrosheep/square": "^0.3.106",
86
+ "@getpaseo/client": "0.14.0",
87
+ "@getpaseo/protocol": "0.14.0",
88
88
  "@opencode/client": "2.0.20",
89
89
  "@opencode/schema": "2.0.20",
90
90
  "cross-spawn": "^7.0.6",
@@ -4,14 +4,20 @@ import { createSdkTransport } from "./server/sdk.js";
4
4
  import { attach } from "./server/attach.js";
5
5
  import { attachRpc } from "./shared/attach-rpc.js";
6
6
  import { refreshRpc } from "./shared/refresh-rpc.js";
7
+ import { refreshOrReopen } from "./server/reopen.js";
8
+ import { createRegistrationHandoff, registerRegistrationHooks } from "./server/handoff.js";
7
9
 
8
10
  export default function contribute(server: PluginServerContext) {
9
11
  const transport = createSdkTransport();
10
- const mirror = createProvider(transport);
12
+ const handoff = createRegistrationHandoff();
13
+ const mirror = createProvider(transport, handoff);
11
14
  server.registerProvider(mirror.provider);
12
- server.handle(refreshRpc, (input) => mirror.refresh(input));
13
- server.handle(attachRpc, (input, context) => attach(input, context, mirror.sync));
15
+ server.handle(refreshRpc, (input, context) => refreshOrReopen(context.paseo, input, mirror.refresh));
16
+ server.handle(attachRpc, (input, context) => attach(input, context));
17
+ const removeHooks = registerRegistrationHooks(server, handoff);
14
18
  return async () => {
19
+ removeHooks();
20
+ await handoff.close();
15
21
  try { await mirror.close(); } finally { await transport.close(); }
16
22
  };
17
23
  }
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "id": "keiyaku-paseo",
3
- "requirements": { "paseo": ">=0.11.2" }
3
+ "requirements": { "paseo": ">=0.14.0" }
4
4
  }
@@ -7,8 +7,7 @@ function skip(reason: string) {
7
7
  console.warn(`Keiyaku mirror not attached: ${reason}`);
8
8
  return { attached: false };
9
9
  }
10
- export async function attach(input: z.output<typeof attachRpc.input>, { paseo }: PluginHandlerContext,
11
- sync: (input: { world: string; akuId: string }) => Promise<void>) {
10
+ export async function attach(input: z.output<typeof attachRpc.input>, { paseo }: PluginHandlerContext) {
12
11
  const caller = input.caller;
13
12
  if (caller?.kind !== "external") return skip("caller is not an external host");
14
13
  const native = ["codex", "pi", "claude"].includes(caller.integration);
@@ -44,9 +43,5 @@ export async function attach(input: z.output<typeof attachRpc.input>, { paseo }:
44
43
  config: { provider: "keiyaku/mirror", options: { world, akuId: input.akuId } },
45
44
  idempotencyKey: `keiyaku:${world}:${input.akuId}`,
46
45
  });
47
- // Creation returns only after the host has registered and subscribed to the session.
48
- // Opening's ready event is too early to restore running presentation there.
49
- try { await sync({ world, akuId: input.akuId }); }
50
- catch (error) { console.warn(`Keiyaku mirror attached, but synchronization failed: ${error instanceof Error ? error.message : String(error)}`); }
51
46
  return { attached: true };
52
47
  }
@@ -0,0 +1,114 @@
1
+ import type { PaseoApi } from "@getpaseo/client";
2
+ import type { PluginHookContext, PluginServerContext, PluginSessionOpenRequest } from "@getpaseo/plugin/server";
3
+ import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
4
+
5
+ type ObservedSession = Readonly<{ observe(reannounce?: boolean): Promise<void> }>;
6
+ type Attempt = {
7
+ agentId: string;
8
+ controller: AbortController;
9
+ timer: ReturnType<typeof setTimeout>;
10
+ unsubscribeContext: () => void;
11
+ subscription?: Awaited<ReturnType<PaseoApi["agents"]["list"]>>["subscription"];
12
+ session?: ObservedSession;
13
+ idleObserved: boolean;
14
+ syncing: boolean;
15
+ active: boolean;
16
+ cleanup?: Promise<void>;
17
+ };
18
+ const ATTEMPT_TIMEOUT_MS = 90_000;
19
+
20
+ export function registerRegistrationHooks(server: Pick<PluginServerContext, "before" | "on">,
21
+ handoff: ReturnType<typeof createRegistrationHandoff>): () => void {
22
+ const removeBefore = server.before("agent.session_open", ({ request }, context) => handoff.beforeOpen(request, context));
23
+ const removeArchived = server.on("agent.archived", ({ agent }) => handoff.closed(agent.id));
24
+ const removeClosed = server.on("agent.closed", ({ agent }) => handoff.closed(agent.id));
25
+ return () => { removeBefore(); removeArchived(); removeClosed(); };
26
+ }
27
+
28
+ export function createRegistrationHandoff() {
29
+ const attempts = new Map<string, Attempt>();
30
+ const release = (attempt: Attempt): Promise<void> => {
31
+ if (attempt.cleanup) return attempt.cleanup;
32
+ if (!attempt.active) return Promise.resolve();
33
+ attempt.active = false;
34
+ clearTimeout(attempt.timer);
35
+ attempt.controller.abort();
36
+ attempt.unsubscribeContext();
37
+ if (attempts.get(attempt.agentId) === attempt) attempts.delete(attempt.agentId);
38
+ attempt.cleanup = attempt.subscription?.release().catch((error: unknown) => {
39
+ console.warn(`Keiyaku mirror registration subscription cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
40
+ }) ?? Promise.resolve();
41
+ return attempt.cleanup;
42
+ };
43
+ const synchronize = (attempt: Attempt): void => {
44
+ if (!attempt.active || attempt.syncing || !attempt.idleObserved || !attempt.session) return;
45
+ attempt.syncing = true;
46
+ void attempt.session.observe(true).catch((error: unknown) => {
47
+ console.warn(`Keiyaku mirror registration synchronization failed: ${error instanceof Error ? error.message : String(error)}`);
48
+ }).finally(async () => { await release(attempt); });
49
+ };
50
+ const update = (attempt: Attempt, message: SessionOutboundMessage): void => {
51
+ if (!attempt.active || !attempt.session || message.type !== "agent_update" || message.payload.kind !== "upsert") return;
52
+ const { agent } = message.payload;
53
+ if (agent.id !== attempt.agentId || agent.provider !== "keiyaku" || agent.status !== "idle" || agent.archivedAt) return;
54
+ attempt.idleObserved = true;
55
+ synchronize(attempt);
56
+ };
57
+
58
+ return {
59
+ async beforeOpen(request: PluginSessionOpenRequest, context: PluginHookContext): Promise<void> {
60
+ if (request.provider !== "keiyaku") return;
61
+ const agentId = request.agentId;
62
+ if (!agentId) return;
63
+ const prior = attempts.get(agentId);
64
+ if (prior) await release(prior);
65
+ const controller = new AbortController();
66
+ let attempt!: Attempt;
67
+ const abortFromContext = () => { void release(attempt); };
68
+ context.signal.addEventListener("abort", abortFromContext, { once: true });
69
+ attempt = {
70
+ agentId, controller, timer: setTimeout(() => release(attempt), ATTEMPT_TIMEOUT_MS),
71
+ unsubscribeContext: () => context.signal.removeEventListener("abort", abortFromContext),
72
+ idleObserved: false, syncing: false, active: true,
73
+ };
74
+ attempts.set(agentId, attempt);
75
+ if (context.signal.aborted) {
76
+ await release(attempt);
77
+ return;
78
+ }
79
+ try {
80
+ const result = await context.paseo.agents.list({ filter: { includeArchived: true, includeBackground: true },
81
+ page: { limit: 1 }, subscribe: {}, signal: controller.signal });
82
+ const subscription = result.subscription;
83
+ if (!subscription) throw new Error("Paseo did not establish the agent directory subscription");
84
+ attempt.subscription = subscription;
85
+ if (!attempt.active) {
86
+ await subscription.release();
87
+ return;
88
+ }
89
+ subscription.subscribe({ snapshot: () => {}, update: (message) => update(attempt, message) });
90
+ } catch (error) {
91
+ await release(attempt);
92
+ console.warn(`Keiyaku mirror registration observation unavailable: ${error instanceof Error ? error.message : String(error)}`);
93
+ }
94
+ },
95
+ providerReady(agentId: string | undefined, session: ObservedSession): void {
96
+ if (!agentId) return;
97
+ const attempt = attempts.get(agentId);
98
+ if (!attempt?.active) return;
99
+ attempt.session = session;
100
+ synchronize(attempt);
101
+ },
102
+ providerClosed(agentId: string | undefined, session: ObservedSession): Promise<void> {
103
+ const attempt = agentId ? attempts.get(agentId) : undefined;
104
+ return attempt?.session === session ? release(attempt) : Promise.resolve();
105
+ },
106
+ closed(agentId: string): Promise<void> {
107
+ const attempt = attempts.get(agentId);
108
+ return attempt ? release(attempt) : Promise.resolve();
109
+ },
110
+ async close(): Promise<void> {
111
+ await Promise.all([...attempts.values()].map(release));
112
+ },
113
+ };
114
+ }
@@ -8,14 +8,19 @@ import { createMirror } from "./mirror.js";
8
8
  import { modelConfig } from "./model.js";
9
9
  import type { StopAttempt } from "./stop.js";
10
10
 
11
+ type RegistrationHandoff = Readonly<{
12
+ providerReady(agentId: string | undefined, session: Readonly<{ observe(reannounce?: boolean): Promise<void> }>): void;
13
+ providerClosed(agentId: string | undefined, session: Readonly<{ observe(reannounce?: boolean): Promise<void> }>): Promise<void> | void;
14
+ }>;
15
+
11
16
  const identity = z.object({ world: z.string().min(1), akuId: z.string().regex(/^aku\//u) });
12
- export function createProvider(transport: AkumaTransport) {
13
- const sessions = new Set<{ world: string; akuId: string; observe(reannounce?: boolean): Promise<void>; stop(): Promise<void> }>();
17
+ export function createProvider(transport: AkumaTransport, handoff?: RegistrationHandoff) {
18
+ const sessions = new Set<{ agentId: string | undefined; world: string; akuId: string; observe(reannounce?: boolean): Promise<void>; stop(): Promise<void> }>();
14
19
  const provider: ProviderRegistration = {
15
20
  id: "keiyaku", label: "Keiyaku", description: "Akuma runtime mirror",
16
21
  async connect(request): Promise<ProviderConnection> {
17
22
  if (!request.versions.includes(1)) throw new Error("Provider protocol version 1 is required");
18
- const capabilities = negotiateProviderCapabilities(request.capabilities, ["session.persistence", "prompt.message", "prompt.steer"]);
23
+ const capabilities = negotiateProviderCapabilities(request.capabilities, ["session.persistence", "prompt.message", "prompt.steer", "session.can_stop_runtime"]);
19
24
  const listeners = new Set<(event: ProviderEvent) => void>();
20
25
  const local = new Map<string, { stop(): Promise<void>; stopExecution(requestId: string): Promise<void>; prompt(prompt: ProviderPrompt): Promise<void> }>();
21
26
  let closed = false;
@@ -36,6 +41,7 @@ export function createProvider(transport: AkumaTransport) {
36
41
  const world = await realpath(target.world);
37
42
  const mirror = createMirror(input.sessionId, emit);
38
43
  const cancellation = new AbortController();
44
+ const agentId = input.config.env.PASEO_AGENT_ID;
39
45
  // The opening window seeds retained state instead of announcing it.
40
46
  const skipRetained = input.history === "skip";
41
47
  let opening = true;
@@ -127,7 +133,7 @@ export function createProvider(transport: AkumaTransport) {
127
133
  return running;
128
134
  }
129
135
  const session = {
130
- world, akuId: target.akuId,
136
+ agentId, world, akuId: target.akuId,
131
137
  observe,
132
138
  async prompt(prompt: ProviderPrompt) {
133
139
  const respond = (result: Extract<ProviderEvent, { type: "session.prompt_result" }>["result"]) => emit({
@@ -180,6 +186,7 @@ export function createProvider(transport: AkumaTransport) {
180
186
  releaseObservation();
181
187
  sessions.delete(session);
182
188
  local.delete(input.sessionId);
189
+ await handoff?.providerClosed(agentId, session);
183
190
  await Promise.allSettled([...submissions]);
184
191
  await stopping;
185
192
  await running;
@@ -228,7 +235,13 @@ export function createProvider(transport: AkumaTransport) {
228
235
  // Ready names the first observed window, or the explicit report that
229
236
  // none could be read. It never waits for the observation to end.
230
237
  await session.observe();
231
- if (!cancellation.signal.aborted) emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
238
+ if (!cancellation.signal.aborted) {
239
+ handoff?.providerReady(agentId, session);
240
+ emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
241
+ }
242
+ } else if (input.type === "session.can_stop_runtime") {
243
+ emit({ type: "session.can_stop_runtime", requestId: input.requestId, sessionId: input.sessionId,
244
+ canStop: !local.has(input.sessionId) });
232
245
  } else if (input.type === "session.interrupt" || input.type === "session.close") {
233
246
  const session = local.get(input.sessionId);
234
247
  if (input.type === "session.close") {
@@ -0,0 +1,78 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import type { PaseoAgent, PaseoAgentHandle, PaseoApi } from "@getpaseo/client";
3
+ import { z } from "zod";
4
+
5
+ const PAGE_SIZE = 200;
6
+ const mirrorPersistence = z.object({ version: z.literal(1),
7
+ data: z.object({ world: z.string(), akuId: z.string() }) });
8
+ const reopenInFlight = new Map<string, Promise<boolean>>();
9
+
10
+ function metadataMatches(agent: PaseoAgent, akuId: string): boolean {
11
+ if (agent.provider !== "keiyaku" || agent.archivedAt || agent.persistence?.provider !== "keiyaku") return false;
12
+ const parsed = mirrorPersistence.safeParse(agent.persistence.metadata?.pluginProviderPersistence);
13
+ return parsed.success && parsed.data.data.world.length > 0 && parsed.data.data.akuId === akuId;
14
+ }
15
+
16
+ async function matchesCanonicalIdentity(agent: PaseoAgent, world: string, akuId: string): Promise<boolean> {
17
+ if (!metadataMatches(agent, akuId)) return false;
18
+ const parsed = mirrorPersistence.parse(agent.persistence!.metadata!.pluginProviderPersistence);
19
+ try {
20
+ return await realpath(parsed.data.world) === world && parsed.data.akuId === akuId;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ async function listCandidates(paseo: PaseoApi, world: string, akuId: string): Promise<PaseoAgent[]> {
27
+ const candidates: PaseoAgent[] = [];
28
+ const seenCursors = new Set<string>();
29
+ let cursor: string | undefined;
30
+ for (;;) {
31
+ const page = await paseo.agents.list({ filter: { includeArchived: true, includeBackground: true },
32
+ page: { limit: PAGE_SIZE, ...(cursor ? { cursor } : {}) } });
33
+ for (const { agent } of page.entries) if (await matchesCanonicalIdentity(agent, world, akuId)) candidates.push(agent);
34
+ if (!page.pageInfo.hasMore) return candidates;
35
+ const next = page.pageInfo.nextCursor;
36
+ if (!next || next === cursor || seenCursors.has(next)) throw new Error("incomplete Paseo agent directory pagination");
37
+ seenCursors.add(next);
38
+ cursor = next;
39
+ }
40
+ }
41
+
42
+ async function reopenOne(paseo: PaseoApi, candidate: PaseoAgent, world: string, akuId: string): Promise<boolean> {
43
+ const current = await paseo.agents.ref(candidate.id).refresh();
44
+ if (!current || !(await matchesCanonicalIdentity(current.agent, world, akuId))) return false;
45
+ const handle: PaseoAgentHandle = paseo.agents.ref(current.agent);
46
+ const timeline = await handle.timeline.refetch({ limit: 0 });
47
+ if (timeline.error || !timeline.agent || !(await matchesCanonicalIdentity(timeline.agent, world, akuId))) return false;
48
+ return true;
49
+ }
50
+
51
+ export async function refreshOrReopen(paseo: PaseoApi, input: { world: string; akuId: string },
52
+ refreshLocal: (input: { world: string; akuId: string }) => Promise<{ woken: number }>): Promise<{ woken: number }> {
53
+ const world = await realpath(input.world);
54
+ const local = await refreshLocal({ world, akuId: input.akuId });
55
+ if (local.woken > 0) return local;
56
+
57
+ let candidates: PaseoAgent[];
58
+ try {
59
+ candidates = await listCandidates(paseo, world, input.akuId);
60
+ } catch (error) {
61
+ console.warn(`Keiyaku mirror refresh skipped: ${error instanceof Error ? error.message : String(error)}`);
62
+ return { woken: 0 };
63
+ }
64
+ let woken = 0;
65
+ for (const candidate of candidates) {
66
+ const key = `${candidate.id}\0${world}\0${input.akuId}`;
67
+ let reopening = reopenInFlight.get(key);
68
+ if (!reopening) {
69
+ reopening = reopenOne(paseo, candidate, world, input.akuId).catch((error: unknown) => {
70
+ console.warn(`Keiyaku mirror ${candidate.id} was not reopened: ${error instanceof Error ? error.message : String(error)}`);
71
+ return false;
72
+ }).finally(() => reopenInFlight.delete(key));
73
+ reopenInFlight.set(key, reopening);
74
+ }
75
+ if (await reopening) woken++;
76
+ }
77
+ return { woken };
78
+ }