@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31

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 (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,59 @@
1
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
2
+ import { type LearnedWorkflow } from "./learning.js";
3
+ import type { ModelRef } from "./model.js";
4
+ import { type Ledger } from "./paid-calls.js";
5
+ import type { Plane } from "./tool-plane.js";
6
+ import type { Complete } from "./llm.js";
7
+ export declare const LEARNED_WORKFLOW_TOOL = "learned_workflow";
8
+ /** One line of a learned workflow's output for its row: an object's fields as `name value`, each value whole or, when
9
+ * longer than VALUE_MAX, only as its size, and whole fields only until LINE_MAX. Nothing is ever cut inside a value:
10
+ * the timeline redacts the line as it says it (its summary's words), and its redactor matches a held value only whole,
11
+ * so a cut value could leave a prefix it would not find. Newlines are flattened, so the one line it keeps holds every
12
+ * field. An output already cut for the model (learnedText) says so. */
13
+ export declare function outputLine(text: string): string | undefined;
14
+ /** The models a learned workflow's model nodes run on: the run's own (capped and marked: app.ts), as pi-ai's. */
15
+ type RunModels = {
16
+ getModel(provider: string, id: string): unknown;
17
+ getModels(): readonly unknown[];
18
+ completeSimple(model: never, context: never, options?: never): Promise<unknown>;
19
+ };
20
+ export type LearnedWorkflowRun = {
21
+ /** The learned workflows the run's pin names (pinnedWorkflows). */
22
+ workflows: readonly LearnedWorkflow[];
23
+ /** The tools the agent's revision grants: a workflow's call node may name only those a call node runs here
24
+ * (tools.ts learnedWorkflowTools), and of those, none `plane` resolves unavailable. */
25
+ granted: readonly string[];
26
+ /** The run's plane (tool-plane.ts planeOf), as its harness and its tools read it. */
27
+ plane?: Plane;
28
+ env: NodeJS.ProcessEnv;
29
+ work: string;
30
+ models: RunModels;
31
+ /** The run's model a model node of `tier` runs on: the tier's, else the run's own. */
32
+ modelOf(tier: string | undefined): ModelRef | undefined;
33
+ /** The `llm` tool's completion, for a call node that names it. */
34
+ complete?: Complete;
35
+ /** The run's gate's permission of a tool now (tool-gate.ts RunGate policy): a call node's tool set to ask or deny is
36
+ * refused before any node runs, and asked again as each call node runs, a composed workflow's inner ones too, so one
37
+ * set to either since the call began is refused there, never run. None: every tool allowed (a test's run). */
38
+ policy?: (tool: string) => string;
39
+ };
40
+ /** The most characters of a learned workflow's output its answer holds, monid's bound (monid.ts CLIP): within the
41
+ * host's result bound, which each CLI is told to pass whole (host-bounds.test). */
42
+ export declare const LEARNED_CLIP = 60000;
43
+ /** `text`, a learned workflow's output as JSON, cut at LEARNED_CLIP characters (never inside a surrogate pair), saying
44
+ * so. */
45
+ export declare function learnedText(text: string): string;
46
+ /** What a learned workflow's model node is refused with when it names a tool: it runs in a session of its own here.
47
+ * The check before the run refuses such a workflow first (draftProblems); this one holds should it not. */
48
+ export declare const NODE_TOOLS_REFUSED = "a learned workflow's model node runs without tools here";
49
+ /** The tool's description: what it does, and each workflow by name with the line its README says what it does with. */
50
+ export declare const learnedWorkflowDescription: (workflows: readonly LearnedWorkflow[]) => string;
51
+ /** The run's `learned_workflow` tool over `run.workflows`. */
52
+ export declare function learnedWorkflowTool(run: LearnedWorkflowRun): ToolRegistration;
53
+ /** `flow` run on `input` for `run`: its output as JSON, or why it did not run. Never throws, but on an abort. `ledger`:
54
+ * the tool call's, which each call node's paid requests are booked under, as a call of its own within it. */
55
+ export declare function runLearned(run: LearnedWorkflowRun, flow: LearnedWorkflow, input: unknown, signal?: AbortSignal, ledger?: Ledger): Promise<{
56
+ text: string;
57
+ isError: boolean;
58
+ }>;
59
+ export {};
@@ -0,0 +1,191 @@
1
+ import { defineTool } from "@earendil-works/pi-durable";
2
+ import { registerLabel, registerOutcome } from "@parcha/pi-durable-agent/timeline";
3
+ import { sideRequests } from "./cap.js";
4
+ import { draftProblems, LEARNED_MAX_TURNS } from "./learn/index.js";
5
+ import { workflowLine } from "./learning.js";
6
+ import { ledgerOf } from "./paid-calls.js";
7
+ import { forModel } from "./result.js";
8
+ import { deniedText } from "./tool-gate.js";
9
+ import { allows, CALL_TOOLS, learnedDraftTools, toolOf } from "./tools.js";
10
+ export const LEARNED_WORKFLOW_TOOL = "learned_workflow";
11
+ /** The most of a learned workflow's output its result line shows, and the longest value it shows as written. */
12
+ const LINE_MAX = 120;
13
+ const VALUE_MAX = 60;
14
+ /** One line of a learned workflow's output for its row: an object's fields as `name value`, each value whole or, when
15
+ * longer than VALUE_MAX, only as its size, and whole fields only until LINE_MAX. Nothing is ever cut inside a value:
16
+ * the timeline redacts the line as it says it (its summary's words), and its redactor matches a held value only whole,
17
+ * so a cut value could leave a prefix it would not find. Newlines are flattened, so the one line it keeps holds every
18
+ * field. An output already cut for the model (learnedText) says so. */
19
+ export function outputLine(text) {
20
+ const clipped = /\n\[the workflow's output is cut at (\d+) of (\d+) characters\]$/.exec(text);
21
+ if (clipped)
22
+ return `its output is long, cut at ${clipped[1]} of ${clipped[2]} characters`;
23
+ let output;
24
+ try {
25
+ output = JSON.parse(text);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ const said = (value) => {
31
+ const flat = (typeof value === "string" ? value : JSON.stringify(value) ?? String(value)).replace(/\s+/g, " ").trim();
32
+ return flat.length > VALUE_MAX ? `(${flat.length} characters)` : flat;
33
+ };
34
+ if (!output || typeof output !== "object" || Array.isArray(output))
35
+ return said(output);
36
+ const fields = [];
37
+ let length = 0;
38
+ for (const [key, value] of Object.entries(output)) {
39
+ const field = `${key} ${said(value)}`;
40
+ if (fields.length && length + 2 + field.length > LINE_MAX) {
41
+ fields.push("…");
42
+ break;
43
+ }
44
+ fields.push(field);
45
+ length += (fields.length > 1 ? 2 : 0) + field.length;
46
+ }
47
+ return fields.length ? fields.join(", ") : undefined;
48
+ }
49
+ // The timeline's words for a learned workflow's call: the workflow it ran (its name), and, once it returns, its output.
50
+ registerLabel(LEARNED_WORKFLOW_TOOL, (a) => (typeof a.name === "string" && a.name ? `Ran the learned workflow ${a.name}` : "Ran a learned workflow"), undefined, { name: "Run a learned workflow" });
51
+ registerOutcome(LEARNED_WORKFLOW_TOOL, (result) => {
52
+ const line = outputLine(result.text);
53
+ return line === undefined ? undefined : { failed: false, text: line };
54
+ });
55
+ /** The most characters of a learned workflow's output its answer holds, monid's bound (monid.ts CLIP): within the
56
+ * host's result bound, which each CLI is told to pass whole (host-bounds.test). */
57
+ export const LEARNED_CLIP = 60_000;
58
+ /** `text`, a learned workflow's output as JSON, cut at LEARNED_CLIP characters (never inside a surrogate pair), saying
59
+ * so. */
60
+ export function learnedText(text) {
61
+ if (text.length <= LEARNED_CLIP)
62
+ return text;
63
+ const end = /[\uD800-\uDBFF]/.test(text[LEARNED_CLIP - 1] ?? "") ? LEARNED_CLIP - 1 : LEARNED_CLIP;
64
+ return `${text.slice(0, end)}\n[the workflow's output is cut at ${end} of ${text.length} characters]`;
65
+ }
66
+ /** What a learned workflow's model node is refused with when it names a tool: it runs in a session of its own here.
67
+ * The check before the run refuses such a workflow first (draftProblems); this one holds should it not. */
68
+ export const NODE_TOOLS_REFUSED = "a learned workflow's model node runs without tools here";
69
+ /** The tool's description: what it does, and each workflow by name with the line its README says what it does with. */
70
+ export const learnedWorkflowDescription = (workflows) => [
71
+ "Run a workflow this agent learned, as one step: give its name and its input, a JSON object as the workflow's input",
72
+ "schema says. It answers the workflow's output as JSON, or why it did not run. The workflows:",
73
+ ...workflows.map(workflowLine),
74
+ ].join("\n");
75
+ /** One model request as a pi-ai event stream, sent as a side request through `models.completeSimple`: marked and costed
76
+ * on the run's timeline under `learned_workflow`, and under the run's cap. */
77
+ async function sideStream(models, model, context, options) {
78
+ const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
79
+ const stream = createAssistantMessageEventStream();
80
+ sideRequests.set(context, { label: LEARNED_WORKFLOW_TOOL, extraInputTokens: 0, maxFeeUsd: 0, feeUsd: () => 0 });
81
+ void (async () => {
82
+ try {
83
+ const message = (await models.completeSimple(model, context, options));
84
+ if (message.stopReason === "error" || message.stopReason === "aborted")
85
+ stream.push({ type: "error", reason: message.stopReason, error: message });
86
+ else
87
+ stream.push({ type: "done", reason: message.stopReason, message });
88
+ stream.end(message);
89
+ }
90
+ catch (error) {
91
+ const failed = { role: "assistant", content: [], stopReason: "error", errorMessage: String(error?.message ?? error), timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
92
+ stream.push({ type: "error", reason: "error", error: failed });
93
+ stream.end(failed);
94
+ }
95
+ })();
96
+ return stream;
97
+ }
98
+ /** The run's `learned_workflow` tool over `run.workflows`. */
99
+ export function learnedWorkflowTool(run) {
100
+ const names = run.workflows.map(({ name }) => name);
101
+ return defineTool({
102
+ name: LEARNED_WORKFLOW_TOOL,
103
+ description: learnedWorkflowDescription(run.workflows),
104
+ // Never run again after a crash (pi-durable's "unsafe"; a HostTool's "never": host-tools.ts REPLAY).
105
+ replay: "unsafe",
106
+ parameters: {
107
+ type: "object",
108
+ additionalProperties: false,
109
+ required: ["name", "input"],
110
+ properties: {
111
+ name: { type: "string", enum: names, description: "The learned workflow to run." },
112
+ input: { type: "object", description: "The workflow's input, as its input schema says." },
113
+ },
114
+ },
115
+ execute: async (args, api, context) => {
116
+ const { name, input } = (args ?? {});
117
+ const flow = run.workflows.find((workflow) => workflow.name === name);
118
+ if (!flow)
119
+ return forModel(`No learned workflow of this agent is named ${JSON.stringify(name)}. Its workflows: ${names.join(", ")}.`, { isError: true });
120
+ const said = await runLearned(run, flow, input, context?.abortSignal, ledgerOf(api, context));
121
+ return forModel(said.text, { isError: said.isError });
122
+ },
123
+ });
124
+ }
125
+ /** `flow` run on `input` for `run`: its output as JSON, or why it did not run. Never throws, but on an abort. `ledger`:
126
+ * the tool call's, which each call node's paid requests are booked under, as a call of its own within it. */
127
+ export async function runLearned(run, flow, input, signal, ledger) {
128
+ const refuse = (why) => ({ text: `The learned workflow ${flow.name} was not run: ${why}`, isError: true });
129
+ if (!input || typeof input !== "object" || Array.isArray(input))
130
+ return refuse("its input must be a JSON object");
131
+ const dsl = await import("@parcha/agentrun-dsl");
132
+ // Checked again at the call, against the agent's own tools as its run has them, before any node runs: what merged under
133
+ // another revision may name one it has no more.
134
+ // The tools the gate allows now; one set to ask or deny is refused in the words a workflow revision's call node is.
135
+ const { tools, gated } = learnedDraftTools(run.granted, (name) => run.policy?.(name) ?? "allow", run.plane);
136
+ const problems = draftProblems(dsl, flow.workflow, tools, gated);
137
+ if (problems.length)
138
+ return refuse(problems.map(({ detail }) => detail).join("; "));
139
+ const doc = JSON.parse(flow.workflow);
140
+ const { createPiHostRunner } = await import("@parcha/agentrun-pi");
141
+ const runners = new Map();
142
+ const runnerFor = async (tier) => {
143
+ const known = runners.get(tier ?? "default");
144
+ if (known)
145
+ return known;
146
+ const ref = run.modelOf(tier);
147
+ if (!ref)
148
+ throw new Error("the run has no model for its model nodes");
149
+ const model = run.models.getModel(ref.provider, ref.modelId);
150
+ if (!model)
151
+ throw new Error(`the model ${ref.provider}/${ref.modelId} is not known here`);
152
+ const registry = { getAll: () => run.models.getModels(), streamSimple: (m, ctx, options) => sideStream(run.models, m, ctx, options) };
153
+ const runner = createPiHostRunner({ cwd: run.work, model: model, modelRegistry: registry }, { tools: [], maxTurns: LEARNED_MAX_TURNS });
154
+ runners.set(tier ?? "default", runner);
155
+ return runner;
156
+ };
157
+ const runNode = async (request) => {
158
+ if (request.tools?.length)
159
+ throw new Error(`${NODE_TOOLS_REFUSED}: its node "${request.label}" names ${request.tools.join(", ")}`);
160
+ // Its own signal, which the DSL ties to the call's (a sibling's failure, a deadline, the call's stop).
161
+ return (await runnerFor(request.tier))(request);
162
+ };
163
+ const runEffect = async ({ node, input: given, signal: own, executionPath, item }) => {
164
+ const tool = node.via === "tool" ? node.tool : undefined;
165
+ const effect = tool && allows(CALL_TOOLS, tool) && tools.includes(tool) ? toolOf(tool)?.effect : undefined;
166
+ if (!effect)
167
+ throw new Error(`call node "${node.label}": this agent runs no tool ${tool ?? `via ${node.via}`}`);
168
+ // The gate's one rule, read as each call node runs, as a workflow revision's call node reads it (app.ts runEffect):
169
+ // a tool set to deny since the call began is refused in the gate's words, one set to ask too, since a call node
170
+ // cannot wait for an approval. Neither runs.
171
+ const permission = run.policy?.(tool) ?? "allow";
172
+ if (permission === "deny")
173
+ throw new Error(deniedText(tool));
174
+ if (permission === "ask")
175
+ throw new Error(`This ${tool} call needs a person's approval, which a workflow's call node cannot wait for; it was not run.`);
176
+ // Its paid requests booked under the tool's call, as a call of its own: the node, its execution path, its item in a map.
177
+ const booked = ledger ? { ledger: { call: `${ledger.call}/${node.label}@${executionPath ?? ""}${item ? `#${item.index}` : ""}`, record: ledger.record } } : {};
178
+ return effect(given, { signal: own, env: run.env, work: run.work, ...(run.complete ? { complete: run.complete } : {}), ...booked });
179
+ };
180
+ try {
181
+ const result = await dsl.runWorkflow(doc, input, { runNode: runNode, runEffect: runEffect, ...(signal ? { signal } : {}) });
182
+ if (result.status !== "complete")
183
+ return refuse(`it ended ${result.status}`);
184
+ return { text: learnedText(JSON.stringify(result.output ?? null)), isError: false };
185
+ }
186
+ catch (error) {
187
+ if (signal?.aborted)
188
+ throw error;
189
+ return { text: `The learned workflow ${flow.name} failed: ${String(error?.message ?? error).slice(0, 1000)}`, isError: true };
190
+ }
191
+ }
@@ -18,6 +18,20 @@ type NoteView = {
18
18
  superseded_by: string | null;
19
19
  text: string;
20
20
  etag: string;
21
+ retired?: Retired;
22
+ last_change?: LastChange;
23
+ };
24
+ /** When a retired note, skill or draft was retired, and by whom: a person (its retire's commit), else a run. */
25
+ type Retired = {
26
+ at: string;
27
+ by: "person" | "run";
28
+ };
29
+ /** The newest change to a note, skill or draft (its file: the note, a SKILL.md, a draft's README.md): what it was, by
30
+ * whom and when. A person's is named by its commit (`learning: <kind> by a person: <file>`); a run's merge is `learned`. */
31
+ type LastChange = {
32
+ kind: "approved" | "edited" | "created" | "retired" | "restored" | "learned";
33
+ by: "person" | "run";
34
+ at: string;
21
35
  };
22
36
  type Change = {
23
37
  by: {
@@ -51,7 +65,18 @@ type LearnedView = {
51
65
  run: string | null;
52
66
  bytes: number;
53
67
  etag: string;
68
+ retired?: Retired;
69
+ last_change?: LastChange;
70
+ };
71
+ /** For tests: how many times a pending count was read from a folder (once per commit of its main). */
72
+ export declare const pendingTestHooks: {
73
+ reads: number;
54
74
  };
75
+ /** How many of agent `agentId`'s learned items wait for its owner's OK on its folder's main: notes, skills and workflow
76
+ * drafts held with `status: pending`, as the learning view reads them (notesAt, learnedAt). Read once per commit of
77
+ * main (a list of agents asks for every agent): the commit is resolved each time, the folder only when it moved. A
78
+ * folder never made has none waiting; one that cannot be read is undefined (the caller shows no count). */
79
+ export declare function pendingCount(data: string, agentId: string): Promise<number | undefined>;
55
80
  /** GET /agents/{id}/learning: main, its index, the first page of its notes and of its log, and how the agent's runs
56
81
  * fared and what learning changed for them (`counts`, `impact`: learning-run.ts, from the runs' rows and the learning
57
82
  * ledger); an agent with no folder (its learning never on) has an empty one. */
@@ -69,7 +94,10 @@ export declare function agentLearning(data: string, agentId: string, shown: Show
69
94
  agent: string;
70
95
  main: string;
71
96
  index: string;
72
- notes: Page<NoteView>;
97
+ notes: Page<NoteView & {
98
+ last_change?: LastChange;
99
+ retired?: Retired;
100
+ }>;
73
101
  skills: LearnedView[];
74
102
  workflows: LearnedView[];
75
103
  log: Page<Change>;
@@ -114,6 +142,7 @@ export declare function writeNote(data: string, agentId: string, raw: string, in
114
142
  body?: Buffer;
115
143
  refuse: readonly string[];
116
144
  approve?: boolean;
145
+ restore?: boolean;
117
146
  }): Promise<{
118
147
  status: 200 | 201;
119
148
  file: string;
@@ -16,12 +16,13 @@
16
16
  // the same link rule, so a link at the folder is an error on either, never followed. A text that leaves holding one of
17
17
  // the host's secrets as they are now (a value made secret after it was written) is cut of it, a file's name holding
18
18
  // one reads "[redacted]" whole, and a diff's file holding one is withheld.
19
+ import { existsSync } from "node:fs";
19
20
  import { rm } from "node:fs/promises";
20
21
  import { join } from "node:path";
21
- import { approve, buildIndex, CAPS, checkNote, INDEX_FILE, INDEX_LINES, isHeld, learnedFront, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, SKILLS_DIR, supersede, WORKFLOWS_DIR } from "./learn/index.js";
22
+ import { approve, buildIndex, CAPS, checkNote, frontKeys, INDEX_FILE, INDEX_LINES, isHeld, LEARNED_KEYS, learnedFront, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, skillProblems, SKILLS_DIR, supersede, unstorable, WORKFLOWS_DIR } from "./learn/index.js";
22
23
  import { ApiError, invalid } from "./errors.js";
23
24
  import { homeOf, readJson } from "./files.js";
24
- import { agentFolder, changedOrder, checkOut, detailShown, git, line, mainOf, notesView, openAgentRepo, PROPOSAL, readBlobs, readFolder, readPin, secretsShown, withAgentRepo } from "./learning.js";
25
+ import { agentFolder, checkOut, detailShown, git, line, mainOf, notesView, openAgentRepo, PROPOSAL, readBlobs, readFolder, readPin, secretsShown, withAgentRepo } from "./learning.js";
25
26
  import { isObject } from "./validate.js";
26
27
  /** A file on main larger than this is not read: a note is at most 4 KB (learn/check.ts CAPS.note). */
27
28
  const FILE_CAP = 1 << 20;
@@ -38,6 +39,7 @@ const APPROVED_VIA = "Approved-Via: console";
38
39
  /** What a retire adds to a note, on top of the note cap a retired note may fill (learn/notes.ts retire). */
39
40
  const RETIRED_LINE = Buffer.byteLength("status: retired\n");
40
41
  const utf8 = new TextDecoder("utf-8", { fatal: true });
42
+ const PERSON_KINDS = ["approved", "edited", "created", "retired", "restored"];
41
43
  export { secretsShown } from "./learning.js";
42
44
  /** The few values last kept, by key, oldest dropped first: at most `entries` of them, `bytes` in all by their sizes. */
43
45
  class Recent {
@@ -184,27 +186,75 @@ async function notesAt(home, repo, sha) {
184
186
  const known = parsedAt.get(key);
185
187
  if (known)
186
188
  return known;
187
- const [{ index, notes }, touched] = await Promise.all([readAt(home, repo, sha), changedOrder(home, repo, sha)]);
189
+ const [{ index, notes }, { order: touched, changes }] = await Promise.all([readAt(home, repo, sha), historyAt(home, repo, sha)]);
188
190
  const rank = (note) => (note.status === "active" ? 0 : 1);
189
- const parsed = { index, notes: [...notes.values()].sort((a, b) => rank(a) - rank(b) || (touched.get(a.file) ?? Infinity) - (touched.get(b.file) ?? Infinity) || (a.file < b.file ? -1 : 1)) };
191
+ const parsed = { index, changes, notes: [...notes.values()].sort((a, b) => rank(a) - rank(b) || (touched.get(a.file) ?? Infinity) - (touched.get(b.file) ?? Infinity) || (a.file < b.file ? -1 : 1)) };
190
192
  parsedAt.set(key, parsed, 2 * parsed.notes.reduce((size, note) => size + note.text.length + 256, index.length));
191
193
  return parsed;
192
194
  }
195
+ /** What a commit's change was, as the view says it (LastChange), or undefined for a commit that is neither: a person's
196
+ * names its kind in the fixed prefix of its subject, `learning: <kind> by a person: `; a run's merge carries its Run-Id
197
+ * trailer, `learned`. Nothing else is read (no other part of the subject, no body). */
198
+ function changeOf(at, subject, runId) {
199
+ if (runId.trim())
200
+ return { kind: "learned", by: "run", at };
201
+ for (const kind of PERSON_KINDS)
202
+ if (subject.startsWith(`learning: ${kind} by a person: `))
203
+ return { kind, by: "person", at };
204
+ return undefined;
205
+ }
206
+ /** The log fields changeOf reads (LAST_FORMAT), after the record separator: the commit's time, subject, Changed-By and Run-Id. */
207
+ const LAST_FORMAT = "%cI%x1f%s%x1f%(trailers:key=Run-Id,valueonly,separator=%x2C)";
208
+ /** Folds one record of a LAST_FORMAT walk (newest first) into `out`, for the files it changed. */
209
+ function foldHistory(out, head, files) {
210
+ const [at = "", subject = "", runId = ""] = head.split("\x1f");
211
+ const change = changeOf(at, subject, runId);
212
+ for (const file of files) {
213
+ const known = out.get(file);
214
+ if (!known)
215
+ out.set(file, { at, ...(change ? { last: change } : {}), ...(change?.kind === "retired" ? { retire: change } : {}) });
216
+ else if (!known.retire && change?.kind === "retired")
217
+ known.retire = change;
218
+ }
219
+ }
220
+ /** A retired item's `retired`: its newest retire by a person, else (retired some other way) its newest change's time. */
221
+ const retiredOf = (history) => (history ? (history.retire ? { at: history.retire.at, by: "person" } : { at: history.at, by: "run" }) : undefined);
222
+ /** Commit `sha`'s first-parent history, read in one walk: each file's place by its newest change (0 for the newest
223
+ * commit's, as learning.ts changedOrder orders a run's notes) and that change (changeOf). */
224
+ async function historyAt(home, repo, sha) {
225
+ const order = new Map();
226
+ const changes = new Map();
227
+ recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", `--format=%x1e${LAST_FORMAT}`, sha])).forEach(({ head, files }, i) => {
228
+ for (const file of files)
229
+ if (!order.has(file))
230
+ order.set(file, i);
231
+ foldHistory(changes, head, files);
232
+ });
233
+ return { order, changes };
234
+ }
235
+ /** A note as the view shows it, with its last change, and when and by whom it was retired on a retired one. */
236
+ const withChanges = (view, history) => ({
237
+ ...view,
238
+ ...(history?.last ? { last_change: history.last } : {}),
239
+ ...(view.status === "retired" && history ? { retired: retiredOf(history) } : {}),
240
+ });
193
241
  /** By the folder and the commit: its skills and drafts, raw (each answer cuts them of the host's secrets as they are
194
242
  * then), for the 8 commits last read. */
195
243
  const learnedAtCache = new Recent(8, 4 << 20);
196
244
  /** The run whose merge last changed each of commit `sha`'s files under skills/ and workflows/: its first-parent log's
197
245
  * commits with a Run-Id, newest first, read once (a person's approval, which names none, changes no answer). */
198
246
  async function lastRuns(home, repo, sha) {
199
- const out = new Map();
200
- for (const { head, files } of recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", "--format=%x1e%(trailers:key=Run-Id,valueonly,separator=%x2C)", sha, "--", SKILLS_DIR, WORKFLOWS_DIR]))) {
201
- const run = head.split(",")[0].trim();
247
+ const runs = new Map();
248
+ const changes = new Map();
249
+ for (const { head, files } of recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", `--format=%x1e${LAST_FORMAT}`, sha, "--", SKILLS_DIR, WORKFLOWS_DIR]))) {
250
+ const run = (head.split("\x1f")[2] ?? "").split(",")[0].trim();
251
+ foldHistory(changes, head, files);
202
252
  if (run)
203
253
  for (const file of files)
204
- if (!out.has(file))
205
- out.set(file, run);
254
+ if (!runs.has(file))
255
+ runs.set(file, run);
206
256
  }
207
- return out;
257
+ return { runs, changes };
208
258
  }
209
259
  /** Commit `sha`'s skills and workflow drafts, by name: each skill's SKILL.md and each draft's workflow.json with its
210
260
  * README.md, regular files under FILE_CAP, with what their front matter says. A draft without its README, or a file
@@ -224,7 +274,7 @@ async function learnedAt(home, repo, sha) {
224
274
  }
225
275
  const fronts = new Map([...entries].filter(([path]) => !path.endsWith("/workflow.json")).map(([path, { oid }]) => [path, oid]));
226
276
  // A folder with none reads no history for them.
227
- const [texts, runs] = entries.size ? await Promise.all([textsOf(home, repo, fronts), lastRuns(home, repo, sha)]) : [new Map(), new Map()];
277
+ const [texts, { runs, changes }] = entries.size ? await Promise.all([textsOf(home, repo, fronts), lastRuns(home, repo, sha)]) : [new Map(), { runs: new Map(), changes: new Map() }];
228
278
  const skills = [];
229
279
  const workflows = [];
230
280
  for (const [path, { size }] of entries) {
@@ -237,6 +287,11 @@ async function learnedAt(home, repo, sha) {
237
287
  continue;
238
288
  const said = learnedFront(front.text);
239
289
  const item = { name: place.name, file: path, ...(place.kind === "workflow" ? { readme: held } : {}), description: said?.description ?? "", status: learnedStatus(front.text), run: runs.get(path) ?? null, bytes: size, etag: etagOf(front.oid) };
290
+ const history = changes.get(held);
291
+ if (history?.last)
292
+ item.last_change = history.last;
293
+ if (item.status === "retired")
294
+ item.retired = retiredOf(history);
240
295
  (place.kind === "skill" ? skills : workflows).push(item);
241
296
  }
242
297
  const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -267,6 +322,47 @@ async function pageRequest(home, repo, query, fallback) {
267
322
  throw new ApiError("bad_request", "cursor is not one this server gave");
268
323
  return { limit, at: { sha: named[1], offset: Number(named[2]) } };
269
324
  }
325
+ /** For tests: how many times a pending count was read from a folder (once per commit of its main). */
326
+ export const pendingTestHooks = { reads: 0 };
327
+ /** By agent: its folder's main commit and how many of its items wait for the owner's OK there. */
328
+ const pendingBy = new Map();
329
+ const pendingReads = new Map();
330
+ /** How many of agent `agentId`'s learned items wait for its owner's OK on its folder's main: notes, skills and workflow
331
+ * drafts held with `status: pending`, as the learning view reads them (notesAt, learnedAt). Read once per commit of
332
+ * main (a list of agents asks for every agent): the commit is resolved each time, the folder only when it moved. A
333
+ * folder never made has none waiting; one that cannot be read is undefined (the caller shows no count). */
334
+ export async function pendingCount(data, agentId) {
335
+ try {
336
+ const { home, repo } = await placeOf(data, agentId);
337
+ // A folder never made (no .git) holds nothing yet: 0. One whose .git git cannot read (an invalid repository, git
338
+ // missing) is unknown: undefined, so the count is left out rather than shown as 0.
339
+ if (existsSync(join(repo, ".git")) && !(await git(home, repo, ["rev-parse", "--git-dir"]).then(() => true, () => false)))
340
+ return undefined;
341
+ const sha = await mainOf(home, repo);
342
+ if (!sha)
343
+ return 0;
344
+ const known = pendingBy.get(agentId);
345
+ if (known?.sha === sha)
346
+ return known.pending;
347
+ // Requests that miss together share one read of the commit (cleared once it settles, so a failure is not kept).
348
+ const key = `${agentId}\0${sha}`;
349
+ let reading = pendingReads.get(key);
350
+ if (!reading) {
351
+ pendingTestHooks.reads += 1;
352
+ reading = Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha)]).then(([{ notes }, { skills, workflows }]) => {
353
+ const pending = notes.filter((note) => note.status === "pending").length + [...skills, ...workflows].filter((item) => item.status === "pending").length;
354
+ pendingBy.set(agentId, { sha, pending });
355
+ return pending;
356
+ });
357
+ pendingReads.set(key, reading);
358
+ void reading.finally(() => pendingReads.delete(key)).catch(() => undefined);
359
+ }
360
+ return await reading;
361
+ }
362
+ catch {
363
+ return undefined;
364
+ }
365
+ }
270
366
  /** GET /agents/{id}/learning: main, its index, the first page of its notes and of its log, and how the agent's runs
271
367
  * fared and what learning changed for them (`counts`, `impact`: learning-run.ts, from the runs' rows and the learning
272
368
  * ledger); an agent with no folder (its learning never on) has an empty one. */
@@ -275,8 +371,10 @@ export async function agentLearning(data, agentId, shown, counts, impact) {
275
371
  const sha = await mainOf(home, repo);
276
372
  if (!sha)
277
373
  return { agent: agentId, main: null, index: "", notes: EMPTY, skills: [], workflows: [], log: EMPTY, counts, impact };
278
- const [{ index, notes }, { skills, workflows }, log] = await Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha), logPage(home, repo, sha, 0, LOG_PAGE, shown)]);
279
- return { agent: agentId, main: sha, index: shown.text(index), notes: pageOf(notes, sha, 0, NOTES_PAGE, (note) => noteView(note, shown)), skills: skills.map((item) => learnedView(item, shown)), workflows: workflows.map((item) => learnedView(item, shown)), log, counts, impact };
374
+ const [{ index, notes, changes }, { skills, workflows }, log] = await Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha), logPage(home, repo, sha, 0, LOG_PAGE, shown)]);
375
+ // Each note's last change, from the notes' walk; a skill's or a draft's is on it (learnedAt). A retired one says when
376
+ // and by whom it was retired, from the same change.
377
+ return { agent: agentId, main: sha, index: shown.text(index), notes: pageOf(notes, sha, 0, NOTES_PAGE, (note) => withChanges(noteView(note, shown), changes.get(note.file))), skills: skills.map((item) => learnedView(item, shown)), workflows: workflows.map((item) => learnedView(item, shown)), log, counts, impact };
280
378
  }
281
379
  /** GET /agents/{id}/learning/notes?cursor=&limit=&status=: a page of the notes, ordered as the view's, from what the
282
380
  * commit's first read kept. */
@@ -289,8 +387,9 @@ export async function learningNotes(data, agentId, query, shown) {
289
387
  const sha = at?.sha ?? (await mainOf(home, repo));
290
388
  if (!sha)
291
389
  return EMPTY;
292
- const { notes } = await notesAt(home, repo, sha);
293
- return pageOf(status === null ? notes : notes.filter((note) => note.status === status), sha, at?.offset ?? 0, limit, (note) => noteView(note, shown));
390
+ const { notes, changes } = await notesAt(home, repo, sha);
391
+ const listed = status === null ? notes : notes.filter((note) => note.status === status);
392
+ return pageOf(listed, sha, at?.offset ?? 0, limit, (note) => withChanges(noteView(note, shown), changes.get(note.file)));
294
393
  }
295
394
  /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, reading only its own. */
296
395
  export async function learningLog(data, agentId, query, shown) {
@@ -322,6 +421,8 @@ function fileOf(raw, use) {
322
421
  throw new ApiError("bad_request", "A workflow is approved by its README.md, the file that says it waits.");
323
422
  if (use === "retire" && place.kind === "workflow")
324
423
  throw new ApiError("bad_request", "A workflow is retired by its README.md, the file that says whether it is in use.");
424
+ if (use === "restore" && place.kind === "workflow")
425
+ throw new ApiError("bad_request", "A workflow is restored by its README.md, the file that says whether it is in use.");
325
426
  return file;
326
427
  }
327
428
  if (file === INDEX_FILE && use !== "read")
@@ -396,6 +497,19 @@ function conditionOf(ifMatch, ifNoneMatch, put) {
396
497
  throw new ApiError("precondition_required", put ? "A write names the version it read: If-Match with the note's ETag to edit it, or If-None-Match: * to create it." : "A retire names the version it read: If-Match with the note's ETag.");
397
498
  return { ...(match?.length ? { match } : {}), absent };
398
499
  }
500
+ /** Whether `file` waited for its owner's OK (status pending) just before a person last retired it on `main`'s line. */
501
+ async function heldBeforeRetire(home, repo, main, file, learned) {
502
+ const retire = line(await git(home, repo, ["log", "--first-parent", "-1", "--format=%H", "--fixed-strings", `--grep=learning: retired by a person: ${file}`, main, "--", file]));
503
+ if (!retire)
504
+ return false;
505
+ const before = await git(home, repo, ["cat-file", "blob", `${retire}^:${file}`]).then((out) => out.toString("utf8"), () => undefined);
506
+ if (before === undefined)
507
+ return false;
508
+ if (learned)
509
+ return learnedStatus(before) === "pending";
510
+ const note = parseNoteFile(file, before);
511
+ return !Array.isArray(note) && note.status === "pending";
512
+ }
399
513
  /** PUT /agents/{id}/learning/files/{file} (`body`, the note's whole text), or POST .../retire or .../approve (`approve`;
400
514
  * no body), as a person: the precondition, then the checks (a retire's and an approve's, the note's format alone: never
401
515
  * its secrets), then one commit on main in the agent's queue, on the folder agentFolder checked: the note, and MEMORY.md
@@ -405,7 +519,7 @@ function conditionOf(ifMatch, ifNoneMatch, put) {
405
519
  * the checks refuse is never written to git. A retire of a note that is not active, and an edit that changes nothing,
406
520
  * commit nothing. `refuse`: the host's secrets. */
407
521
  export async function writeNote(data, agentId, raw, input) {
408
- const file = fileOf(raw, input.approve ? "approve" : input.body === undefined ? "retire" : "write");
522
+ const file = fileOf(raw, input.approve ? "approve" : input.restore ? "restore" : input.body === undefined ? "retire" : "write");
409
523
  // A skill's SKILL.md or a draft's README.md: only ever approved or retired here.
410
524
  const learned = learnedPlace(file);
411
525
  const condition = conditionOf(input.ifMatch, input.ifNoneMatch, input.body !== undefined);
@@ -451,7 +565,47 @@ export async function writeNote(data, agentId, raw, input) {
451
565
  // Beside the note itself: what an approve marks of the notes the approved one supersedes.
452
566
  const also = new Map();
453
567
  const notes = main ? (await readAt(home, repo, main)).notes : new Map();
454
- if (text === undefined && learned && !input.approve) {
568
+ let heldBefore = false;
569
+ if (input.restore) {
570
+ // Restored, a retired note, skill or draft is active again: given to every later run. It is checked again as a
571
+ // new one is (secrets' shapes, the host's values, hidden characters, its format, every file of a skill's or a
572
+ // draft's folder): a retire takes a leaking one out of every run unchecked, and a restore never brings it back.
573
+ // One that waited for its owner's OK before its retire is recorded as their approval too (Approved-Via).
574
+ heldBefore = await heldBeforeRetire(home, repo, main, file, Boolean(learned));
575
+ if (learned) {
576
+ const status = learnedStatus(current.text);
577
+ const kind = learned.kind === "skill" ? "skill" : "workflow";
578
+ if (status !== "retired")
579
+ throw new ApiError("bad_request", `The ${kind} is not retired: it is ${status}.`);
580
+ text = released(current.text);
581
+ const problems = skillProblems(text, learned.name).map((detail) => printable({ rule: kind, path: file, detail }, input.refuse));
582
+ const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
583
+ if (extra.length)
584
+ problems.push(printable({ rule: "skill_front_matter", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned ${kind} sets name and description alone` }, input.refuse));
585
+ const folder = `${learned.kind === "skill" ? SKILLS_DIR : WORKFLOWS_DIR}/${learned.name}/`;
586
+ const others = (await git(home, repo, ["ls-tree", "-r", "-z", "--name-only", main, "--", folder])).toString("utf8").split("\0").filter((path) => path && path !== file);
587
+ const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...(await Promise.all(others.map(async (path) => ({ path, status: "modified", bytes: await git(home, repo, ["cat-file", "blob", `${main}:${path}`]) }))))];
588
+ problems.push(...unstorable(changes, input.refuse));
589
+ if (problems.length)
590
+ throw refused(problems);
591
+ }
592
+ else {
593
+ const note = parseNoteFile(file, current.text);
594
+ if (Array.isArray(note))
595
+ throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
596
+ if (note.status !== "retired")
597
+ throw new ApiError("bad_request", `The note is not retired: it is ${note.status}.`);
598
+ text = approve(current.text);
599
+ const { problems } = checkNote(file, Buffer.from(text, "utf8"), input.refuse);
600
+ if (problems.length)
601
+ throw refused(problems);
602
+ // What it supersedes, and is active still, is superseded now, as an approval marks it.
603
+ for (const old of note.supersedes)
604
+ if (notes.get(old)?.status === "active")
605
+ also.set(old, supersede(notes.get(old).text, file));
606
+ }
607
+ }
608
+ else if (text === undefined && learned && !input.approve) {
455
609
  // Retired, as a note is: no later run is given it. One already retired is answered as it is; nothing else in
456
610
  // the folder changes.
457
611
  if (learnedStatus(current.text) === "retired")
@@ -502,7 +656,7 @@ export async function writeNote(data, agentId, raw, input) {
502
656
  if (lines > INDEX_LINES)
503
657
  throw refused([{ rule: "index_full", detail: `the index would hold ${lines} lines; it holds at most ${INDEX_LINES}, so retire a note first` }]);
504
658
  const parent = main ?? (await openAgentRepo(home, repo, check));
505
- const subject = `learning: ${input.approve ? "approved" : given === undefined ? "retired" : current ? "edited" : "created"} by a person: ${file}`;
659
+ const subject = `learning: ${input.approve ? "approved" : input.restore ? "restored" : given === undefined ? "retired" : current ? "edited" : "created"} by a person: ${file}`;
506
660
  const env = { GIT_INDEX_FILE: join(repo, ".git", "person.index") };
507
661
  let commit;
508
662
  let oid;
@@ -517,7 +671,7 @@ export async function writeNote(data, agentId, raw, input) {
517
671
  await git(home, repo, ["update-index", "-z", "--index-info"], entries, env);
518
672
  const tree = line(await git(home, repo, ["write-tree"], "", env));
519
673
  // Who approved, and how, in the trailers; the commit's own date is when. Never the note's text.
520
- const trailers = input.approve ? `${BY_USER}\n${APPROVED_VIA}` : BY_USER;
674
+ const trailers = input.approve || heldBefore ? `${BY_USER}\n${APPROVED_VIA}` : BY_USER;
521
675
  commit = line(await git(home, repo, ["commit-tree", tree, "-p", parent, "-m", subject, "-m", trailers]));
522
676
  }
523
677
  finally {