@astrosheep/keiyaku 4.6.32 → 4.6.33

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 (199) hide show
  1. package/README.md +8 -6
  2. package/build/plugins/claude/skills/keiyaku-akuma/SKILL.md +13 -9
  3. package/build/plugins/claude/skills/keiyaku-babysit/SKILL.md +8 -6
  4. package/build/plugins/claude/skills/keiyaku-workflow/SKILL.md +2 -1
  5. package/build/plugins/codex/skills/keiyaku-akuma/SKILL.md +13 -9
  6. package/build/plugins/codex/skills/keiyaku-babysit/SKILL.md +8 -6
  7. package/build/plugins/codex/skills/keiyaku-workflow/SKILL.md +2 -1
  8. package/build/plugins/opencode/skills/keiyaku-akuma/SKILL.md +13 -9
  9. package/build/plugins/opencode/skills/keiyaku-babysit/SKILL.md +8 -6
  10. package/build/plugins/opencode/skills/keiyaku-workflow/SKILL.md +2 -1
  11. package/build/plugins/pi/README.md +55 -97
  12. package/build/plugins/pi/keiyaku.ts +2 -9
  13. package/build/skills/keiyaku-akuma/SKILL.md +13 -9
  14. package/build/skills/keiyaku-babysit/SKILL.md +8 -6
  15. package/build/skills/keiyaku-workflow/SKILL.md +2 -1
  16. package/build/src/akuma/akuma-instance.d.ts +11 -0
  17. package/build/src/akuma/akuma-instance.js +1 -2
  18. package/build/src/akuma/akuma-observe.js +73 -14
  19. package/build/src/akuma/akuma-selection-execution.d.ts +82 -7
  20. package/build/src/akuma/akuma-selection-execution.js +26 -27
  21. package/build/src/akuma/akuma-wait.d.ts +40 -1
  22. package/build/src/akuma/akuma-wait.js +58 -29
  23. package/build/src/akuma/akuma.d.ts +11 -0
  24. package/build/src/akuma/body.js +13 -18
  25. package/build/src/akuma/call-initial-tell.d.ts +0 -1
  26. package/build/src/akuma/call-initial-tell.js +0 -1
  27. package/build/src/akuma/heart/activity-schema.d.ts +16 -0
  28. package/build/src/akuma/heart/activity-schema.js +7 -0
  29. package/build/src/akuma/heart/index.d.ts +1 -1
  30. package/build/src/akuma/heart/index.js +9 -1
  31. package/build/src/akuma/heart/timeline.js +4 -4
  32. package/build/src/akuma/projection-read.d.ts +4 -2
  33. package/build/src/akuma/projection-read.js +21 -14
  34. package/build/src/akuma/projection.d.ts +94 -2
  35. package/build/src/akuma/projection.js +47 -47
  36. package/build/src/akuma/provider.d.ts +2 -2
  37. package/build/src/akuma/provider.js +27 -20
  38. package/build/src/akuma/providers/acp/core.js +2 -5
  39. package/build/src/akuma/providers/opencode-sdk/events.d.ts +2 -1
  40. package/build/src/akuma/providers/opencode-sdk/events.js +31 -1
  41. package/build/src/akuma/publication.js +3 -2
  42. package/build/src/akuma/selection-observation.d.ts +23 -0
  43. package/build/src/akuma/selection-observation.js +15 -4
  44. package/build/src/akuma/status-projection.d.ts +14 -1
  45. package/build/src/akuma/status-projection.js +40 -2
  46. package/build/src/akuma/turn-drive.js +21 -15
  47. package/build/src/body/amend.js +5 -17
  48. package/build/src/body/decode.js +11 -1
  49. package/build/src/body/envelope.d.ts +5 -1
  50. package/build/src/body/envelope.js +4 -2
  51. package/build/src/body/render.js +4 -6
  52. package/build/src/cli/commands/akuma-grammar.d.ts +3 -5
  53. package/build/src/cli/commands/akuma-grammar.js +22 -40
  54. package/build/src/cli/commands/akuma.d.ts +1 -2
  55. package/build/src/cli/commands/akuma.js +6 -58
  56. package/build/src/cli/commands/contract-grammar.d.ts +1 -0
  57. package/build/src/cli/commands/contract-grammar.js +7 -11
  58. package/build/src/cli/commands/contract-help.d.ts +3 -2
  59. package/build/src/cli/commands/contract-help.js +11 -5
  60. package/build/src/cli/commands/contract.js +3 -0
  61. package/build/src/cli/commands/debt-grammar.js +2 -4
  62. package/build/src/cli/parse.js +1 -4
  63. package/build/src/cli/render/akuma-activity.d.ts +3 -15
  64. package/build/src/cli/render/akuma-activity.js +19 -73
  65. package/build/src/cli/render/akuma.d.ts +5 -11
  66. package/build/src/cli/render/akuma.js +22 -30
  67. package/build/src/cli/render/catalog.js +1 -4
  68. package/build/src/cli/render/contract-history.js +2 -0
  69. package/build/src/cli/render/contract-observation.d.ts +2 -1
  70. package/build/src/cli/render/contract-observation.js +25 -1
  71. package/build/src/cli/render/contract-wait.d.ts +2 -2
  72. package/build/src/cli/render/contract-wait.js +13 -17
  73. package/build/src/cli/render/contract.js +12 -9
  74. package/build/src/cli/render/debt.js +1 -2
  75. package/build/src/cli/render/execution-progress.js +1 -3
  76. package/build/src/cli/render/kanshi-akuma.js +1 -2
  77. package/build/src/cli/render/kanshi.js +11 -17
  78. package/build/src/cli/render/receipt.d.ts +1 -1
  79. package/build/src/cli/render/receipt.js +33 -28
  80. package/build/src/cli/render/reconcile.js +2 -5
  81. package/build/src/cli/render/refusal.js +3 -6
  82. package/build/src/cli/render/terminal.d.ts +2 -4
  83. package/build/src/cli/render/terminal.js +10 -17
  84. package/build/src/cli/render/verbs.d.ts +1 -0
  85. package/build/src/cli/render/verbs.js +19 -17
  86. package/build/src/cli/runtime.js +3 -9
  87. package/build/src/core/facts/codec.js +7 -2
  88. package/build/src/core/facts/eligibility.d.ts +4 -4
  89. package/build/src/core/facts/eligibility.js +11 -0
  90. package/build/src/core/facts/fold.js +9 -5
  91. package/build/src/core/facts/gate.d.ts +5 -1
  92. package/build/src/core/facts/gate.js +14 -10
  93. package/build/src/core/facts/types.d.ts +5 -1
  94. package/build/src/core/facts/types.js +7 -0
  95. package/build/src/core/subject.d.ts +4 -1
  96. package/build/src/core/subject.js +10 -2
  97. package/build/src/core/verbs/amend.d.ts +15 -4
  98. package/build/src/core/verbs/amend.js +19 -9
  99. package/build/src/debt/index.d.ts +0 -1
  100. package/build/src/debt/index.js +6 -11
  101. package/build/src/debt/input.d.ts +2 -1
  102. package/build/src/debt/input.js +6 -4
  103. package/build/src/dispatch/index.d.ts +0 -17
  104. package/build/src/dispatch/index.js +1 -10
  105. package/build/src/git/identity.js +16 -45
  106. package/build/src/git/nuke.js +13 -23
  107. package/build/src/git/observe.d.ts +3 -0
  108. package/build/src/git/observe.js +25 -23
  109. package/build/src/git/process.js +11 -18
  110. package/build/src/git/read-observation.d.ts +5 -4
  111. package/build/src/git/repository.d.ts +2 -0
  112. package/build/src/git/repository.js +13 -1
  113. package/build/src/git/scratch.js +2 -14
  114. package/build/src/git/terminal-reconcile.js +1 -13
  115. package/build/src/index.d.ts +2 -0
  116. package/build/src/kanshi/index.d.ts +0 -1
  117. package/build/src/kanshi/index.js +0 -1
  118. package/build/src/kanshi/read.d.ts +21 -0
  119. package/build/src/kanshi/read.js +2 -1
  120. package/build/src/kanshi/report.d.ts +94 -0
  121. package/build/src/library/address.d.ts +12 -5
  122. package/build/src/library/address.js +18 -32
  123. package/build/src/library/akuma-creation.d.ts +39 -0
  124. package/build/src/library/akuma-creation.js +3 -9
  125. package/build/src/library/continuation.d.ts +10 -0
  126. package/build/src/library/contract-creation.js +10 -11
  127. package/build/src/library/contract-outcomes.d.ts +72 -1
  128. package/build/src/library/contract-outcomes.js +1 -0
  129. package/build/src/library/contract-types.d.ts +18 -0
  130. package/build/src/library/contract-types.js +2 -0
  131. package/build/src/library/contract-wait.d.ts +7 -0
  132. package/build/src/library/contract-wait.js +53 -49
  133. package/build/src/library/delivery.d.ts +25 -0
  134. package/build/src/library/input.d.ts +5 -23
  135. package/build/src/library/input.js +12 -7
  136. package/build/src/library/kei.js +39 -20
  137. package/build/src/library/keiyaku-classify.js +3 -3
  138. package/build/src/library/keiyaku-debt.js +1 -2
  139. package/build/src/library/keiyaku-identity.d.ts +3 -3
  140. package/build/src/library/keiyaku-identity.js +11 -6
  141. package/build/src/library/keiyaku-verbs.d.ts +456 -1362
  142. package/build/src/library/keiyaku-verbs.js +80 -92
  143. package/build/src/library/keiyaku-wait.d.ts +183 -0
  144. package/build/src/library/keiyaku-wait.js +213 -0
  145. package/build/src/library/keiyaku.d.ts +3 -1
  146. package/build/src/library/keiyaku.js +49 -73
  147. package/build/src/{mcp/output.d.ts → library/model-tools.d.ts} +227 -56
  148. package/build/src/library/model-tools.js +347 -0
  149. package/build/src/library/outcome.js +5 -6
  150. package/build/src/library/refusal.d.ts +25 -1
  151. package/build/src/library/refusal.js +4 -5
  152. package/build/src/library/selection.d.ts +12 -0
  153. package/build/src/library/selection.js +1 -2
  154. package/build/src/mcp/adapter.d.ts +0 -6
  155. package/build/src/mcp/adapter.js +10 -159
  156. package/build/src/mcp/description.d.ts +2 -0
  157. package/build/src/mcp/description.js +2 -0
  158. package/build/src/mcp/help.d.ts +1 -1
  159. package/build/src/mcp/help.js +6 -4
  160. package/build/src/pi/index.d.ts +3 -0
  161. package/build/src/pi/index.js +83 -0
  162. package/build/src/protocol/amend.d.ts +14 -3
  163. package/build/src/protocol/amend.js +113 -46
  164. package/build/src/protocol/bind.d.ts +1 -1
  165. package/build/src/protocol/bind.js +5 -16
  166. package/build/src/protocol/completion.d.ts +30 -0
  167. package/build/src/protocol/completion.js +8 -5
  168. package/build/src/protocol/deliver.js +7 -20
  169. package/build/src/protocol/delivery-preview.d.ts +5 -0
  170. package/build/src/protocol/execution-observation.d.ts +8 -0
  171. package/build/src/protocol/intent.d.ts +1 -0
  172. package/build/src/protocol/intent.js +4 -1
  173. package/build/src/protocol/operations.d.ts +54 -16
  174. package/build/src/protocol/operations.js +17 -31
  175. package/build/src/protocol/placement.js +7 -1
  176. package/build/src/protocol/progress.js +0 -6
  177. package/build/src/protocol/read/status.d.ts +40 -0
  178. package/build/src/protocol/read/status.js +7 -10
  179. package/build/src/protocol/reintegrate.js +2 -2
  180. package/build/src/protocol/result-leaves.d.ts +56 -8
  181. package/build/src/protocol/result-leaves.js +11 -2
  182. package/build/src/protocol/run.js +1 -4
  183. package/build/src/protocol/verify.d.ts +10 -0
  184. package/build/src/protocol/verify.js +1 -0
  185. package/build/src/runtime/proc/windows-launch.exe +0 -0
  186. package/build/src/settlement/settle.js +19 -68
  187. package/package.json +7 -3
  188. package/plugins/pi/README.md +55 -97
  189. package/plugins/pi/keiyaku.ts +2 -9
  190. package/skills/keiyaku-akuma/SKILL.md +13 -9
  191. package/skills/keiyaku-babysit/SKILL.md +8 -6
  192. package/skills/keiyaku-workflow/SKILL.md +2 -1
  193. package/build/plugins/pi/akuma-tools.ts +0 -283
  194. package/build/src/body/keys.d.ts +0 -4
  195. package/build/src/body/keys.js +0 -11
  196. package/build/src/kanshi/roster.d.ts +0 -2
  197. package/build/src/kanshi/roster.js +0 -2
  198. package/build/src/mcp/output.js +0 -193
  199. package/plugins/pi/akuma-tools.ts +0 -283
@@ -98,6 +98,20 @@ export function encodeAgentEvent(event) {
98
98
  return event.model === undefined
99
99
  ? { type: event.type }
100
100
  : { type: event.type, model: boundedEventText(event.model) };
101
+ case "permission":
102
+ return marked({
103
+ type: event.type,
104
+ requests: event.requests.slice(0, 32).map((request) => ({
105
+ id: request.id,
106
+ action: boundedEventText(request.action),
107
+ resources: request.resources.slice(0, 32).map(boundedEventText),
108
+ ...(request.tool === undefined ? {} : { tool: boundedEventText(request.tool) }),
109
+ })),
110
+ }, event.requests.length > 32 ||
111
+ event.requests.some((request) => request.action.length > AGENT_EVENT_TEXT_LIMIT ||
112
+ (request.tool !== undefined && request.tool.length > AGENT_EVENT_TEXT_LIMIT) ||
113
+ request.resources.length > 32 ||
114
+ request.resources.some((resource) => resource.length > AGENT_EVENT_TEXT_LIMIT)));
101
115
  case "assistant":
102
116
  return marked({ type: event.type, text: boundedEventText(event.text) }, event.text.length > AGENT_EVENT_TEXT_LIMIT);
103
117
  case "thought":
@@ -211,12 +225,10 @@ export function noteEvent(note) {
211
225
  export function unknownEvent(kind) {
212
226
  return { type: "unknown", kind };
213
227
  }
214
- // Slow consumers may lose reconstructible narration, but session coordinates,
215
- // notes, error events, and the latest runtime-model observation stay
216
- // observable. The one queue reserves a single model slot, so that observation
217
- // never competes for narration admission and no overflow can hide the model a
218
- // Turn proved it ran. A full protected queue replaces one protected item with a
219
- // bounded aggregate note; `end` ignores later emission.
228
+ // Slow consumers may lose reconstructible narration, but the latest model and
229
+ // permission state each have a reserved slot. Superseding an obsolete state
230
+ // (including an empty permission set) cannot compete with narration or overflow.
231
+ // A full protected narration queue coalesces errors; `end` ignores later emission.
220
232
  function isErrorEvent(event) {
221
233
  if (event.type === "note")
222
234
  return true;
@@ -224,11 +236,11 @@ function isErrorEvent(event) {
224
236
  return event.result.status === "error";
225
237
  return event.type === "unknown" && /(?:error|fail|abort|cancel|stop|terminal)/iu.test(event.kind);
226
238
  }
227
- function isModelEvent(event) {
228
- return event.type === "model";
239
+ function isStateEvent(event) {
240
+ return event.type === "model" || event.type === "permission";
229
241
  }
230
242
  function isReconstructibleEvent(event) {
231
- return event.type !== "session" && !isModelEvent(event) && !isErrorEvent(event);
243
+ return event.type !== "session" && !isStateEvent(event) && !isErrorEvent(event);
232
244
  }
233
245
  const AGENT_EVENT_OVERFLOW_PREFIX = "Agent event queue overflow";
234
246
  function overflowEvent(count) {
@@ -248,13 +260,8 @@ export class AgentEventChannel {
248
260
  waiter.resolve({ done: false, value: event });
249
261
  return;
250
262
  }
251
- if (isModelEvent(event)) {
252
- // Model evidence is control state, never narration: it occupies the
253
- // queue's one reserved model slot, so a narration flood and a full
254
- // protected queue both leave it observable. An unconsumed predecessor is
255
- // obsolete, and superseding it is what keeps the newest fact, an unnamed
256
- // one clearing the confirmation it disconfirms.
257
- const obsolete = this.queued.findIndex(isModelEvent);
263
+ if (isStateEvent(event)) {
264
+ const obsolete = this.queued.findIndex((queued) => queued.type === event.type);
258
265
  if (obsolete === -1)
259
266
  this.queued.push(event);
260
267
  else
@@ -277,8 +284,8 @@ export class AgentEventChannel {
277
284
  }
278
285
  this.overflowMarker = undefined;
279
286
  }
280
- const protectedItem = this.queued.findIndex((queued) => queued.type !== "session" && !isModelEvent(queued));
281
- const replacement = protectedItem === -1 ? this.queued.findIndex((queued) => !isModelEvent(queued)) : protectedItem;
287
+ const protectedItem = this.queued.findIndex((queued) => queued.type !== "session" && !isStateEvent(queued));
288
+ const replacement = protectedItem === -1 ? this.queued.findIndex((queued) => !isStateEvent(queued)) : protectedItem;
282
289
  this.overflowCount += 1;
283
290
  const marker = overflowEvent(this.overflowCount);
284
291
  this.queued[replacement] = marker;
@@ -289,9 +296,9 @@ export class AgentEventChannel {
289
296
  }
290
297
  this.queued.push(event);
291
298
  }
292
- /** Narration and protected slots; the reserved model slot is not one of them. */
299
+ /** State snapshots do not spend ordinary narration slots. */
293
300
  narrationCount() {
294
- return this.queued.length - Number(this.queued.some(isModelEvent));
301
+ return this.queued.reduce((count, event) => count + Number(!isStateEvent(event)), 0);
295
302
  }
296
303
  end() {
297
304
  if (this.ended)
@@ -1,7 +1,7 @@
1
1
  import { Readable, Writable } from "node:stream";
2
2
  import { spawnStdioProcess } from "../../../runtime/proc/stdio.js";
3
3
  import { abortable } from "../../abort.js";
4
- import { AgentEventChannel, } from "../../provider.js";
4
+ import { AgentEventChannel, launchPrompt, } from "../../provider.js";
5
5
  import { akumaExecutionEnvironment } from "../execution-environment.js";
6
6
  import { EMPTY_ACP_EVENT_STATE, flushAcpEvents, mapAcpUpdate, } from "./events.js";
7
7
  function diagnostic(acp, error) {
@@ -146,10 +146,7 @@ function beginAcpPrompt(context, child, turn, sessionId, input) {
146
146
  void agent
147
147
  .request(acp.methods.agent.session.prompt, {
148
148
  sessionId,
149
- prompt: [
150
- { type: "text", text: input.body },
151
- ...input.launchTells.map(({ text }) => ({ type: "text", text })),
152
- ],
149
+ prompt: [{ type: "text", text: launchPrompt(input.body, input.launchTells, input.schemaJson) }],
153
150
  })
154
151
  .then((response) => turn.finish(promptResult(response), () => child.endInputAndDrain()), (error) => turn.finish({ kind: "failed", diagnostic: diagnostic(acp, error) }, () => child.endInputAndDrain()));
155
152
  void child.exited.then((exit) => turn.finish({
@@ -1,4 +1,4 @@
1
- import { type AgentEvent, type ToolCall } from "../../provider.js";
1
+ import { type AgentEvent, type PermissionRequest, type ToolCall } from "../../provider.js";
2
2
  type Emitter = {
3
3
  emit(event: AgentEvent): void;
4
4
  };
@@ -9,6 +9,7 @@ type State = {
9
9
  call?: ToolCall;
10
10
  }>;
11
11
  completed: Set<string>;
12
+ permissions: Map<string, PermissionRequest>;
12
13
  };
13
14
  export declare function diagnostic(value: unknown): string;
14
15
  /** Only complete native values enter narration. The caller enforces submission/step correlation. */
@@ -157,6 +157,27 @@ function toolInputStarted(data, state) {
157
157
  if (typeof data.id === "string" && typeof data.name === "string")
158
158
  state.tools.set(data.id, { name: data.name });
159
159
  }
160
+ function permissionEvent(type, data, events, state) {
161
+ const id = text(type === "permission.asked" ? data.id : data.requestID);
162
+ if (id === undefined)
163
+ return;
164
+ if (type === "permission.asked") {
165
+ const action = text(data.action);
166
+ if (action === undefined || !Array.isArray(data.resources))
167
+ return;
168
+ const source = object(data.source);
169
+ const tool = source?.type === "tool" && typeof source.id === "string" ? state.tools.get(source.id)?.name : undefined;
170
+ state.permissions.set(id, {
171
+ id,
172
+ action,
173
+ resources: data.resources.filter((value) => typeof value === "string"),
174
+ ...(tool === undefined ? {} : { tool }),
175
+ });
176
+ }
177
+ else if (!state.permissions.delete(id))
178
+ return;
179
+ events.emit({ type: "permission", requests: [...state.permissions.values()] });
180
+ }
160
181
  /** Only complete native values enter narration. The caller enforces submission/step correlation. */
161
182
  export function mapEvent(value, events, state) {
162
183
  const event = object(value);
@@ -167,6 +188,10 @@ export function mapEvent(value, events, state) {
167
188
  return;
168
189
  const type = event.type;
169
190
  switch (type) {
191
+ case "permission.asked":
192
+ case "permission.replied":
193
+ permissionEvent(type, data, events, state);
194
+ return;
170
195
  case "session.step.started":
171
196
  stepStarted(data, events);
172
197
  return;
@@ -198,5 +223,10 @@ export function mapEvent(value, events, state) {
198
223
  }
199
224
  }
200
225
  export function createEventState(sessionId) {
201
- return { ...(sessionId === undefined ? {} : { sessionId }), tools: new Map(), completed: new Set() };
226
+ return {
227
+ ...(sessionId === undefined ? {} : { sessionId }),
228
+ tools: new Map(),
229
+ completed: new Set(),
230
+ permissions: new Map(),
231
+ };
202
232
  }
@@ -192,10 +192,10 @@ async function awaitAsleepBirth(paths, signal) {
192
192
  ...(signal === undefined ? {} : { signal }),
193
193
  });
194
194
  if (leash === null)
195
- throw new Error("Forked Akuma did not finish its birth body");
195
+ throw new Error("Akuma did not finish its birth body");
196
196
  try {
197
197
  if ((await readHeart(paths)).latestBody?.end !== "exited") {
198
- throw new Error("Forked Akuma birth body did not exit cleanly");
198
+ throw new Error("Akuma birth body did not exit cleanly");
199
199
  }
200
200
  }
201
201
  finally {
@@ -340,6 +340,7 @@ export async function publishPreparedCall(prepared) {
340
340
  try {
341
341
  child = await launchAkuma({
342
342
  allocated,
343
+ awaitAsleep: true,
343
344
  ...(input.signal === undefined ? {} : { signal: input.signal }),
344
345
  launch: async (ready) => {
345
346
  return await input.spawn({
@@ -86,6 +86,17 @@ export declare const akumaObservationSchema: z.ZodReadonly<z.ZodObject<{
86
86
  toolId: z.ZodString;
87
87
  }, z.core.$strict>>>>>;
88
88
  latestActivity: z.ZodExactOptional<z.ZodNumber>;
89
+ awaiting: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
90
+ kind: z.ZodLiteral<"permission">;
91
+ id: z.ZodNumber;
92
+ requests: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
93
+ id: z.ZodString;
94
+ action: z.ZodString;
95
+ resources: z.ZodReadonly<z.ZodArray<z.ZodString>>;
96
+ tool: z.ZodExactOptional<z.ZodString>;
97
+ }, z.core.$strict>>>>;
98
+ clipped: z.ZodExactOptional<z.ZodLiteral<true>>;
99
+ }, z.core.$strict>>>;
89
100
  pending: z.ZodExactOptional<z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
90
101
  id: z.ZodNumber;
91
102
  tellId: z.ZodString;
@@ -274,9 +285,11 @@ export declare const tellFailureSchema: z.ZodUnion<readonly [z.ZodReadonly<z.Zod
274
285
  declare const akumaTextObservationSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
275
286
  kind: z.ZodLiteral<"answered">;
276
287
  answer: z.ZodString;
288
+ completedAt: z.ZodExactOptional<z.ZodString>;
277
289
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
278
290
  kind: z.ZodLiteral<"failed">;
279
291
  diagnostic: z.ZodString;
292
+ completedAt: z.ZodExactOptional<z.ZodString>;
280
293
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
281
294
  kind: z.ZodLiteral<"unanswered">;
282
295
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
@@ -285,6 +298,7 @@ declare const akumaTextObservationSchema: z.ZodUnion<readonly [z.ZodReadonly<z.Z
285
298
  export declare const completedTextObservationSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
286
299
  kind: z.ZodLiteral<"answered">;
287
300
  answer: z.ZodString;
301
+ completedAt: z.ZodExactOptional<z.ZodString>;
288
302
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
289
303
  kind: z.ZodLiteral<"unanswered">;
290
304
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
@@ -297,6 +311,7 @@ export declare const akumaTellResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z
297
311
  input: z.ZodExactOptional<z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
298
312
  kind: z.ZodLiteral<"answered">;
299
313
  answer: z.ZodString;
314
+ completedAt: z.ZodExactOptional<z.ZodString>;
300
315
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
301
316
  kind: z.ZodLiteral<"unanswered">;
302
317
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
@@ -336,6 +351,7 @@ export declare const akumaTellResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z
336
351
  input: z.ZodExactOptional<z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
337
352
  kind: z.ZodLiteral<"answered">;
338
353
  answer: z.ZodString;
354
+ completedAt: z.ZodExactOptional<z.ZodString>;
339
355
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
340
356
  kind: z.ZodLiteral<"unanswered">;
341
357
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
@@ -357,13 +373,16 @@ export declare const akumaTellResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z
357
373
  export declare const akumaAskObservationSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
358
374
  kind: z.ZodLiteral<"answered">;
359
375
  answer: z.ZodJSONSchema;
376
+ completedAt: z.ZodExactOptional<z.ZodString>;
360
377
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
361
378
  kind: z.ZodLiteral<"failed">;
362
379
  diagnostic: z.ZodString;
380
+ completedAt: z.ZodExactOptional<z.ZodString>;
363
381
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
364
382
  kind: z.ZodLiteral<"invalid-output">;
365
383
  diagnostic: z.ZodString;
366
384
  answer: z.ZodString;
385
+ completedAt: z.ZodExactOptional<z.ZodString>;
367
386
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
368
387
  kind: z.ZodLiteral<"unanswered">;
369
388
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
@@ -372,6 +391,7 @@ export declare const akumaAskObservationSchema: z.ZodUnion<readonly [z.ZodReadon
372
391
  export declare const akumaAskNormalResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
373
392
  kind: z.ZodLiteral<"answered">;
374
393
  answer: z.ZodJSONSchema;
394
+ completedAt: z.ZodExactOptional<z.ZodString>;
375
395
  wake: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
376
396
  kind: z.ZodLiteral<"failed">;
377
397
  diagnostic: z.ZodString;
@@ -432,6 +452,7 @@ export declare const akumaAskNormalResultSchema: z.ZodUnion<readonly [z.ZodReado
432
452
  export declare const akumaAskResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
433
453
  kind: z.ZodLiteral<"answered">;
434
454
  answer: z.ZodJSONSchema;
455
+ completedAt: z.ZodExactOptional<z.ZodString>;
435
456
  wake: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
436
457
  kind: z.ZodLiteral<"failed">;
437
458
  diagnostic: z.ZodString;
@@ -491,6 +512,7 @@ export declare const akumaAskResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z.
491
512
  }, z.core.$strict>>, z.ZodReadonly<z.ZodObject<{
492
513
  kind: z.ZodLiteral<"failed">;
493
514
  diagnostic: z.ZodString;
515
+ completedAt: z.ZodExactOptional<z.ZodString>;
494
516
  wake: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
495
517
  kind: z.ZodLiteral<"failed">;
496
518
  diagnostic: z.ZodString;
@@ -511,6 +533,7 @@ export declare const akumaAskResultSchema: z.ZodUnion<readonly [z.ZodReadonly<z.
511
533
  kind: z.ZodLiteral<"invalid-output">;
512
534
  diagnostic: z.ZodString;
513
535
  answer: z.ZodString;
536
+ completedAt: z.ZodExactOptional<z.ZodString>;
514
537
  wake: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
515
538
  kind: z.ZodLiteral<"failed">;
516
539
  diagnostic: z.ZodString;
@@ -113,8 +113,12 @@ export const tellFailureSchema = z.union([
113
113
  z.strictObject({ stage: z.literal("observation"), diagnostic: z.string() }).readonly(),
114
114
  ]);
115
115
  const akumaTextObservationSchema = z.union([
116
- z.strictObject({ kind: z.literal("answered"), answer: z.string() }).readonly(),
117
- z.strictObject({ kind: z.literal("failed"), diagnostic: z.string() }).readonly(),
116
+ z
117
+ .strictObject({ kind: z.literal("answered"), answer: z.string(), completedAt: z.string().exactOptional() })
118
+ .readonly(),
119
+ z
120
+ .strictObject({ kind: z.literal("failed"), diagnostic: z.string(), completedAt: z.string().exactOptional() })
121
+ .readonly(),
118
122
  z.strictObject({ kind: z.literal("unanswered") }).readonly(),
119
123
  z.strictObject({ kind: z.literal("deadline") }).readonly(),
120
124
  ]);
@@ -140,9 +144,16 @@ export const akumaTellResultSchema = z.union([
140
144
  .readonly(),
141
145
  ]);
142
146
  export const akumaAskObservationSchema = z.union([
143
- z.strictObject({ kind: z.literal("answered"), answer: z.json() }).readonly(),
147
+ z.strictObject({ kind: z.literal("answered"), answer: z.json(), completedAt: z.string().exactOptional() }).readonly(),
144
148
  akumaTextObservationSchema.options[1],
145
- z.strictObject({ kind: z.literal("invalid-output"), diagnostic: z.string(), answer: z.string() }).readonly(),
149
+ z
150
+ .strictObject({
151
+ kind: z.literal("invalid-output"),
152
+ diagnostic: z.string(),
153
+ answer: z.string(),
154
+ completedAt: z.string().exactOptional(),
155
+ })
156
+ .readonly(),
146
157
  akumaTextObservationSchema.options[2],
147
158
  akumaTextObservationSchema.options[3],
148
159
  ]);
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { type ActivitySnapshot, type ToolRow } from "./projection.js";
2
+ import { type PermissionRow, type ActivitySnapshot, type ToolRow } from "./projection.js";
3
3
  export declare const currentWorkSchema: z.ZodReadonly<z.ZodObject<{
4
4
  kind: z.ZodEnum<{
5
5
  open: "open";
@@ -15,6 +15,17 @@ export declare const currentWorkSchema: z.ZodReadonly<z.ZodObject<{
15
15
  toolId: z.ZodString;
16
16
  }, z.core.$strict>>>>>;
17
17
  latestActivity: z.ZodExactOptional<z.ZodNumber>;
18
+ awaiting: z.ZodExactOptional<z.ZodReadonly<z.ZodObject<{
19
+ kind: z.ZodLiteral<"permission">;
20
+ id: z.ZodNumber;
21
+ requests: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
22
+ id: z.ZodString;
23
+ action: z.ZodString;
24
+ resources: z.ZodReadonly<z.ZodArray<z.ZodString>>;
25
+ tool: z.ZodExactOptional<z.ZodString>;
26
+ }, z.core.$strict>>>>;
27
+ clipped: z.ZodExactOptional<z.ZodLiteral<true>>;
28
+ }, z.core.$strict>>>;
18
29
  pending: z.ZodExactOptional<z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
19
30
  id: z.ZodNumber;
20
31
  tellId: z.ZodString;
@@ -48,5 +59,7 @@ export declare function renderDiffstat(diffstat: Readonly<{
48
59
  }> | undefined): string;
49
60
  /** Shared neutral presentation, independent of compact clipping and activity selection. */
50
61
  export declare function toolRepr(row: ToolRow): ToolRepr;
62
+ /** A neutral observation of approval work, not a policy or a response channel. */
63
+ export declare function permissionText(row: PermissionRow): string;
51
64
  /** One semantic projection of the already selected retained frontier. */
52
65
  export declare function projectCurrentWork(snapshot: ActivitySnapshot): CurrentWork;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { publicPermissionRequestSchema, } from "./projection.js";
2
3
  import { turnHistoryIdSchema } from "./identity.js";
3
4
  const sequence = z.number().int().nonnegative().safe();
4
5
  const coordinate = z.strictObject({ id: sequence, turnSequence: sequence, toolId: z.string() }).readonly();
@@ -8,6 +9,15 @@ export const currentWorkSchema = z
8
9
  turn: z.strictObject({ sequence, bodySequence: sequence }).readonly().exactOptional(),
9
10
  activeTools: z.array(coordinate).nonempty().readonly().exactOptional(),
10
11
  latestActivity: sequence.exactOptional(),
12
+ awaiting: z
13
+ .strictObject({
14
+ kind: z.literal("permission"),
15
+ id: sequence,
16
+ requests: z.array(publicPermissionRequestSchema).nonempty().readonly(),
17
+ clipped: z.literal(true).exactOptional(),
18
+ })
19
+ .readonly()
20
+ .exactOptional(),
11
21
  pending: z
12
22
  .array(z.strictObject({ id: sequence, tellId: z.string() }).readonly())
13
23
  .nonempty()
@@ -134,9 +144,19 @@ export function toolRepr(row) {
134
144
  const { suffix, diagnostic } = result(row);
135
145
  return { ...core, suffix: `${core.suffix}${suffix}`, diagnostic };
136
146
  }
147
+ /** A neutral observation of approval work, not a policy or a response channel. */
148
+ export function permissionText(row) {
149
+ if (row.requests.length === 0)
150
+ return "Approval wait cleared";
151
+ return `Awaiting approval: ${row.requests
152
+ .map((request) => [request.action, ...(request.tool === undefined ? [] : [request.tool]), ...request.resources].join(" · "))
153
+ .join("; ")}`;
154
+ }
137
155
  function currentAction(row) {
138
156
  let text;
139
- if (row.kind === "tool") {
157
+ if (row.kind === "permission")
158
+ text = permissionText(row);
159
+ else if (row.kind === "tool") {
140
160
  const tool = toolRepr(row);
141
161
  text = `${tool.label} ${tool.text}${tool.suffix}${tool.diagnostic === "" ? "" : ` · ${tool.diagnostic}`}`;
142
162
  }
@@ -156,6 +176,12 @@ function currentAction(row) {
156
176
  ...(clipped ? { clipped: true } : {}),
157
177
  };
158
178
  }
179
+ function awaitedPermission(snapshot, rows) {
180
+ if (snapshot.kind !== "open")
181
+ return undefined;
182
+ const latest = rows.findLast((row) => row.kind === "permission");
183
+ return latest?.requests.length ? latest : undefined;
184
+ }
159
185
  /** One semantic projection of the already selected retained frontier. */
160
186
  export function projectCurrentWork(snapshot) {
161
187
  if (snapshot.kind === "unborn")
@@ -163,7 +189,9 @@ export function projectCurrentWork(snapshot) {
163
189
  const rows = snapshot.entries.flatMap((entry) => (entry.kind === "row" ? [entry.row] : []));
164
190
  const active = rows.filter((row) => row.kind === "tool" && row.state === "active");
165
191
  const pending = rows.flatMap((row) => row.kind === "tell" && row.state === "pending" ? [{ id: row.sequence, tellId: row.tellId }] : []);
166
- const selected = active.at(-1) ??
192
+ const awaiting = awaitedPermission(snapshot, rows);
193
+ const selected = awaiting ??
194
+ active.at(-1) ??
167
195
  rows.findLast((row) => row.kind === "said" || row.kind === "call" || (row.kind === "tell" && row.state === "told"));
168
196
  const summary = selected === undefined ? undefined : currentAction(selected);
169
197
  const outcome = snapshot.kind === "idle" ? snapshot.outcome : undefined;
@@ -178,6 +206,16 @@ export function projectCurrentWork(snapshot) {
178
206
  : {
179
207
  activeTools: active.map((row) => ({ id: row.sequence, turnSequence: row.turnSequence, toolId: row.toolId })),
180
208
  }),
209
+ ...(awaiting === undefined
210
+ ? {}
211
+ : {
212
+ awaiting: {
213
+ kind: "permission",
214
+ id: awaiting.sequence,
215
+ requests: awaiting.requests,
216
+ ...(awaiting.truncated === true ? { clipped: true } : {}),
217
+ },
218
+ }),
181
219
  ...(latest < 0 ? {} : { latestActivity: latest }),
182
220
  ...(pending.length === 0 ? {} : { pending }),
183
221
  ...(outcome === undefined
@@ -170,21 +170,27 @@ async function establishTurnDrive(input, turnSequence, recipe) {
170
170
  }
171
171
  }
172
172
  async function retireProviderCustody(input, turnSequence, attempt) {
173
- const dispose = async (operation) => await Promise.race([
174
- operation().then(async () => {
175
- try {
176
- await attempt.closed;
177
- return { kind: "retired" };
178
- }
179
- catch (error) {
180
- return { kind: "held", error };
181
- }
182
- }, (error) => ({ kind: "held", error })),
183
- abortableDelay(CONTROL_RESPONSE_MS).then(() => ({
184
- kind: "held",
185
- error: new Error(`provider custody remained live after ${CONTROL_RESPONSE_MS}ms`),
186
- })),
187
- ]);
173
+ const dispose = async (operation) => {
174
+ const deadline = new AbortController();
175
+ try {
176
+ await Promise.race([
177
+ (async () => {
178
+ await operation();
179
+ await attempt.closed;
180
+ })(),
181
+ abortableDelay(CONTROL_RESPONSE_MS, deadline.signal).then(() => {
182
+ throw new Error(`provider custody remained live after ${CONTROL_RESPONSE_MS}ms`);
183
+ }),
184
+ ]);
185
+ return { kind: "retired" };
186
+ }
187
+ catch (error) {
188
+ return { kind: "held", error };
189
+ }
190
+ finally {
191
+ deadline.abort();
192
+ }
193
+ };
188
194
  let outcome = await dispose(input.supervisor.forceSignal?.aborted ? attempt.forceDispose : attempt.abort);
189
195
  if (outcome.kind === "retired")
190
196
  return outcome;
@@ -1,7 +1,8 @@
1
1
  import { KeiyakuError } from "../errors.js";
2
2
  import { decodeVerificationDeclarations, VerificationDocumentError } from "./verification.js";
3
3
  import { parseToAST } from "../markdown/parse.js";
4
- import { indexDocument, indexedHeadings, normalizeTitle, rawSlice, sectionContent } from "../markdown/query.js";
4
+ import { indexDocument, indexedHeadings, normalizeTitle, sectionContent } from "../markdown/query.js";
5
+ import { nonblankRaw as nonblank, topLevelSections as sections } from "./envelope.js";
5
6
  import { decodeRegionOrRefusal } from "./region.js";
6
7
  import { contractSectionName, RESERVED_SECTIONS } from "./shape.js";
7
8
  import { renderAmendedContractBody } from "./render.js";
@@ -9,12 +10,6 @@ import { decodeCriteria } from "./criteria.js";
9
10
  function refusal(message) {
10
11
  throw new KeiyakuError("invalid-input", message);
11
12
  }
12
- function nonblank(document, node) {
13
- return rawSlice(document, node.span).trim().length > 0;
14
- }
15
- function sections(document) {
16
- return indexedHeadings(indexDocument(document), { level: 2 }).filter((node) => node.type === "section");
17
- }
18
13
  function operationSections(document) {
19
14
  if (document.frontmatter !== undefined)
20
15
  refusal("amend operations may not contain frontmatter");
@@ -104,9 +99,6 @@ function requireEmpty(document, section) {
104
99
  if (sectionContent(document, section).trim().length > 0)
105
100
  refusal("Remove operation must not have a body");
106
101
  }
107
- function alteredText(body, target, value) {
108
- body[target] = value;
109
- }
110
102
  function applyRemove(body, operation, document) {
111
103
  requireEmpty(document, operation.section);
112
104
  const index = extensionIndex(body, operation.target);
@@ -157,7 +149,7 @@ function applyAppend(body, operation, document) {
157
149
  return;
158
150
  }
159
151
  if (target === "context" || target === "objective" || target === "design") {
160
- alteredText(body, target, appendText(body[target], prose(document, operation.section, operation.target)));
152
+ body[target] = appendText(body[target], prose(document, operation.section, operation.target));
161
153
  return;
162
154
  }
163
155
  if (target !== null)
@@ -178,7 +170,7 @@ function applyReplace(body, operation, document) {
178
170
  return;
179
171
  }
180
172
  if (target === "context" || target === "objective" || target === "design") {
181
- alteredText(body, target, prose(document, operation.section, operation.target));
173
+ body[target] = prose(document, operation.section, operation.target);
182
174
  return;
183
175
  }
184
176
  if (target === "region") {
@@ -193,11 +185,7 @@ function applyReplace(body, operation, document) {
193
185
  }
194
186
  if (target !== null)
195
187
  refusal(`Replace does not support ${operation.target}`);
196
- const index = extensionIndex(body, operation.target);
197
- if (index < 0)
198
- refusal(`unknown extension '${operation.target}'`);
199
- const extension = body.extensions[index];
200
- body.extensions[index] = { ...extension, content: prose(document, operation.section, "extension") };
188
+ applyUpdate(body, operation, document);
201
189
  }
202
190
  function applySet(body, operation, document) {
203
191
  if (contractSectionName(operation.target) !== null || extensionIndex(body, operation.target) >= 0) {
@@ -1,14 +1,24 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { KeiyakuError } from "../errors.js";
2
- import { mintDocumentKey, mintDocumentSegmentKey } from "./keys.js";
3
3
  import { decodeDocumentEnvelope } from "./envelope.js";
4
4
  import { criteriaStructure, decodeCriteria } from "./criteria.js";
5
5
  import { directChildren, rawSlice, sectionContent } from "../markdown/query.js";
6
+ import { documentKey, documentSegmentKey } from "../core/facts/types.js";
6
7
  import { CONTRACT_SECTIONS, RESERVED_SECTIONS } from "./shape.js";
7
8
  import { decodeRegionOrRefusal, regionStructure } from "./region.js";
8
9
  import { decodeVerificationDeclarations, VerificationDocumentError } from "./verification.js";
9
10
  function refusal(message) {
10
11
  throw new KeiyakuError("invalid-input", message);
11
12
  }
13
+ function digest(value) {
14
+ return createHash("sha256").update(Buffer.from(value, "utf8")).digest("hex");
15
+ }
16
+ function mintDocumentKey(source) {
17
+ return documentKey(`document:sha256:${digest(source)}`);
18
+ }
19
+ function mintDocumentSegmentKey(source, span) {
20
+ return documentSegmentKey(`segment:sha256:${digest(source.slice(span.start, span.end))}`);
21
+ }
12
22
  function requireSections(sections) {
13
23
  const diagnostics = [];
14
24
  for (const [name, spec] of Object.entries(CONTRACT_SECTIONS)) {
@@ -1,4 +1,8 @@
1
- import type { DocumentNode, SectionNode } from "../markdown/types.js";
1
+ import type { DocumentNode, MarkdownBlockNode, SectionNode } from "../markdown/types.js";
2
+ /** Whether one block contributes any bytes beyond whitespace. */
3
+ export declare function nonblankRaw(document: DocumentNode, node: MarkdownBlockNode): boolean;
4
+ /** Every top-level H2 section of one parsed document, in source order. */
5
+ export declare function topLevelSections(document: DocumentNode): readonly SectionNode[];
2
6
  export declare function decodeDocumentEnvelope(source: string, kind: "arc" | "contract"): Readonly<{
3
7
  document: DocumentNode;
4
8
  title: SectionNode;
@@ -4,10 +4,12 @@ import { indexDocument, indexedHeadings, normalizeTitle, rawSlice } from "../mar
4
4
  function refusal(message) {
5
5
  throw new KeiyakuError("invalid-input", message);
6
6
  }
7
- function nonblankRaw(document, node) {
7
+ /** Whether one block contributes any bytes beyond whitespace. */
8
+ export function nonblankRaw(document, node) {
8
9
  return rawSlice(document, node.span).trim().length > 0;
9
10
  }
10
- function topLevelSections(document) {
11
+ /** Every top-level H2 section of one parsed document, in source order. */
12
+ export function topLevelSections(document) {
11
13
  return indexedHeadings(indexDocument(document), { level: 2 }).filter((node) => node.type === "section");
12
14
  }
13
15
  export function decodeDocumentEnvelope(source, kind) {
@@ -1,8 +1,9 @@
1
1
  import { formatDuration } from "../duration.js";
2
2
  import { decodeContractDocument } from "./decode.js";
3
3
  import { parseToAST } from "../markdown/parse.js";
4
- import { indexDocument, indexedHeadings, normalizeTitle, rawSlice } from "../markdown/query.js";
4
+ import { normalizeTitle, rawSlice } from "../markdown/query.js";
5
5
  import { CONTRACT_SECTIONS } from "./shape.js";
6
+ import { topLevelSections } from "./envelope.js";
6
7
  function content(value) {
7
8
  return value.trimEnd();
8
9
  }
@@ -65,19 +66,16 @@ export function decodeCanonicalContractDocument(source, options = {}) {
65
66
  const rendered = renderContractBody(decoded);
66
67
  return rendered === decoded.document.bytes ? decoded : decodeContractDocument(rendered, options);
67
68
  }
68
- function sections(document) {
69
- return indexedHeadings(indexDocument(document), { level: 2 }).filter((node) => node.type === "section");
70
- }
71
69
  export function renderAmendedContractBody(currentSource, body, changedSections) {
72
70
  const current = parseToAST(currentSource);
73
71
  const renderedSource = renderContractBody(body);
74
72
  const rendered = parseToAST(renderedSource);
75
- const currentSections = sections(current);
73
+ const currentSections = topLevelSections(current);
76
74
  const preserved = new Map(currentSections.map((node) => [normalizeTitle(node.title), rawSlice(current, node.span)]));
77
75
  const first = currentSections[0];
78
76
  const prefix = first === undefined ? currentSource : currentSource.slice(0, first.span.start);
79
77
  return (prefix +
80
- sections(rendered)
78
+ topLevelSections(rendered)
81
79
  .map((node) => {
82
80
  const name = normalizeTitle(node.title);
83
81
  return changedSections.has(name)