@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.46
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.
- package/CHANGELOG.md +148 -5
- package/README.md +385 -305
- package/dist/acp-package.d.ts +28 -0
- package/dist/acp-package.js +23 -0
- package/dist/adapter-facts.d.ts +8 -1
- package/dist/adapter-facts.js +9 -1
- package/dist/adapters.d.ts +5 -0
- package/dist/adapters.js +36 -3
- package/dist/agent-delete.d.ts +50 -0
- package/dist/agent-delete.js +125 -0
- package/dist/agents-store.d.ts +9 -3
- package/dist/agents-store.js +22 -8
- package/dist/agents.d.ts +5 -1
- package/dist/agents.js +8 -4
- package/dist/api-only.d.ts +8 -3
- package/dist/api-only.js +10 -4
- package/dist/archil-routes.d.ts +5 -1
- package/dist/archil-routes.js +57 -2
- package/dist/browser-wait-ended.d.ts +2 -0
- package/dist/browser-wait-ended.js +2 -0
- package/dist/calendar/ics-faux.d.ts +3 -1
- package/dist/calendar/ics-faux.js +12 -2
- package/dist/calendar/tools.js +5 -2
- package/dist/chatgpt-plan.js +3 -1
- package/dist/claude-login.d.ts +135 -0
- package/dist/claude-login.js +244 -0
- package/dist/cli.js +62 -19
- package/dist/composio-preset.js +69 -7
- package/dist/composio-triggers.d.ts +14 -0
- package/dist/composio-triggers.js +79 -15
- package/dist/computer-attach.d.ts +40 -5
- package/dist/computer-attach.js +130 -15
- package/dist/computer-keys.d.ts +3 -0
- package/dist/computer-keys.js +7 -1
- package/dist/computer-live.js +3 -2
- package/dist/computers.d.ts +21 -10
- package/dist/computers.js +39 -28
- package/dist/console/assets/index-C2MYaUBa.css +1 -0
- package/dist/console/assets/index-CZZeCReB.js +701 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.d.ts +1 -1
- package/dist/dial-relay.d.ts +29 -0
- package/dist/dial-relay.js +94 -0
- package/dist/email/tools.js +10 -5
- package/dist/env-proxy.d.ts +2 -0
- package/dist/env-proxy.js +35 -0
- package/dist/errors.d.ts +3 -1
- package/dist/errors.js +7 -4
- package/dist/faux-computers.d.ts +8 -2
- package/dist/faux-computers.js +83 -6
- package/dist/harness-archive.d.ts +67 -0
- package/dist/harness-archive.js +177 -0
- package/dist/harness-goose.d.ts +34 -0
- package/dist/harness-goose.js +87 -0
- package/dist/harness-install.d.ts +21 -0
- package/dist/harness-install.js +24 -11
- package/dist/harness-opencode/adapter.js +1 -1
- package/dist/harness-table.d.ts +9 -1
- package/dist/harness-table.js +20 -3
- package/dist/harness.d.ts +1 -2
- package/dist/harness.js +3 -4
- package/dist/host.js +2 -1
- package/dist/import.d.ts +10 -0
- package/dist/import.js +28 -8
- package/dist/key-check.js +3 -0
- package/dist/learn/audit.d.ts +6 -6
- package/dist/learn/audit.js +3 -7
- package/dist/learn/check.d.ts +23 -89
- package/dist/learn/check.js +57 -335
- package/dist/learn/commit.d.ts +63 -90
- package/dist/learn/commit.js +124 -316
- package/dist/learn/compile.d.ts +53 -50
- package/dist/learn/compile.js +89 -104
- package/dist/learn/corrections.d.ts +13 -0
- package/dist/learn/corrections.js +23 -0
- package/dist/learn/delete.d.ts +5 -5
- package/dist/learn/delete.js +8 -10
- package/dist/learn/folder.d.ts +35 -47
- package/dist/learn/folder.js +118 -134
- package/dist/learn/index.d.ts +3 -5
- package/dist/learn/index.js +6 -9
- package/dist/learn/learning.sh +45 -15
- package/dist/learn/promote.d.ts +23 -5
- package/dist/learn/promote.js +40 -2
- package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
- package/dist/learn/{skills.js → workflow-draft.js} +48 -58
- package/dist/learn/workflow-nodes.js +1 -1
- package/dist/learned-workflow.js +2 -2
- package/dist/learning-cost.d.ts +38 -24
- package/dist/learning-cost.js +41 -24
- package/dist/learning-routes.d.ts +91 -170
- package/dist/learning-routes.js +183 -421
- package/dist/learning-run.d.ts +19 -40
- package/dist/learning-run.js +23 -93
- package/dist/learning-setting.d.ts +21 -10
- package/dist/learning-setting.js +47 -11
- package/dist/learning-words.d.ts +28 -74
- package/dist/learning-words.js +64 -162
- package/dist/learning.d.ts +61 -392
- package/dist/learning.js +101 -651
- package/dist/live-reach.d.ts +25 -2
- package/dist/live-reach.js +46 -4
- package/dist/llms.txt +1 -1
- package/dist/local-models.d.ts +3 -11
- package/dist/local-models.js +5 -6
- package/dist/mcp-servers-store.d.ts +4 -4
- package/dist/model-form.js +6 -5
- package/dist/model.d.ts +4 -0
- package/dist/model.js +26 -9
- package/dist/native/binding.js +1 -1
- package/dist/native/connection.js +1 -1
- package/dist/native/discovery.js +1 -1
- package/dist/native/instructions.d.ts +3 -0
- package/dist/native/instructions.js +5 -3
- package/dist/native/remote-worker-bridge.js +9 -43
- package/dist/native/remote.d.ts +8 -15
- package/dist/native/remote.js +3 -3
- package/dist/native/schema.js +1 -1
- package/dist/native/types.d.ts +2 -2
- package/dist/openapi.js +273 -319
- package/dist/paid-calls.d.ts +8 -0
- package/dist/paid-calls.js +20 -0
- package/dist/particle-provider.d.ts +11 -0
- package/dist/particle-provider.js +135 -0
- package/dist/port-models.d.ts +12 -4
- package/dist/port-models.js +28 -11
- package/dist/print.d.ts +27 -0
- package/dist/print.js +21 -0
- package/dist/provider.d.ts +7 -0
- package/dist/provider.js +15 -1
- package/dist/reflect-range.js +2 -3
- package/dist/run-launch.d.ts +14 -28
- package/dist/run-launch.js +9 -12
- package/dist/run-learning-served.d.ts +15 -89
- package/dist/run-listing.d.ts +34 -0
- package/dist/run-listing.js +128 -0
- package/dist/run-model-key.js +1 -1
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-trace.d.ts +97 -0
- package/dist/run-trace.js +253 -0
- package/dist/run-view.d.ts +15 -0
- package/dist/run-view.js +9 -0
- package/dist/runnable.js +2 -1
- package/dist/runner/adapter-loop.d.ts +8 -6
- package/dist/runner/adapter-loop.js +16 -12
- package/dist/runner/adapter-run-spec.d.ts +16 -4
- package/dist/runner/adapter-run-spec.js +64 -58
- package/dist/runner/adapters/index.js +22 -0
- package/dist/runner/adapters/pi.d.ts +4 -12
- package/dist/runner/adapters/pi.js +2 -2
- package/dist/runner/audit.d.ts +1 -1
- package/dist/runner/audit.js +30 -13
- package/dist/runner/beside.d.ts +6 -2
- package/dist/runner/beside.js +38 -9
- package/dist/runner/claim-secrets.d.ts +18 -2
- package/dist/runner/claim-secrets.js +42 -18
- package/dist/runner/cli-run-spec.js +55 -51
- package/dist/runner/conformance/harness.d.ts +6 -0
- package/dist/runner/conformance/harness.js +35 -13
- package/dist/runner/conformance/subject.d.ts +6 -0
- package/dist/runner/dispatch.d.ts +2 -2
- package/dist/runner/end-of-run.d.ts +6 -14
- package/dist/runner/end-of-run.js +8 -33
- package/dist/runner/feedback-round.d.ts +2 -2
- package/dist/runner/feedback-round.js +7 -7
- package/dist/runner/github-app.js +3 -1
- package/dist/runner/harness-loops.d.ts +0 -8
- package/dist/runner/harness-loops.js +11 -59
- package/dist/runner/held.d.ts +170 -0
- package/dist/runner/held.js +57 -0
- package/dist/runner/journal-kinds.d.ts +2 -3
- package/dist/runner/journal-kinds.js +2 -3
- package/dist/runner/learned-first.d.ts +40 -0
- package/dist/runner/learned-first.js +32 -0
- package/dist/runner/learning-end.d.ts +77 -69
- package/dist/runner/learning-end.js +250 -303
- package/dist/runner/learning-seed.d.ts +15 -33
- package/dist/runner/learning-seed.js +24 -45
- package/dist/runner/loop-contract.d.ts +2 -3
- package/dist/runner/main.d.ts +17 -9
- package/dist/runner/main.js +82 -20
- package/dist/runner/mcp-run.d.ts +11 -0
- package/dist/runner/mcp-run.js +67 -0
- package/dist/runner/memory-claim.d.ts +10 -5
- package/dist/runner/memory-claim.js +12 -6
- package/dist/runner/model-route.d.ts +7 -4
- package/dist/runner/model-route.js +22 -10
- package/dist/runner/native-loop.d.ts +0 -7
- package/dist/runner/native-loop.js +9 -101
- package/dist/runner/promotion.d.ts +12 -8
- package/dist/runner/promotion.js +37 -28
- package/dist/runner/reflect-hook.d.ts +64 -95
- package/dist/runner/reflect-hook.js +112 -225
- package/dist/runner/run-channel.d.ts +43 -0
- package/dist/runner/run-channel.js +467 -0
- package/dist/runner/run-child-host.d.ts +169 -0
- package/dist/runner/run-child-host.js +1230 -0
- package/dist/runner/run-child.d.ts +1 -0
- package/dist/runner/run-child.js +254 -0
- package/dist/runner/run-errors.d.ts +2 -0
- package/dist/runner/run-errors.js +20 -0
- package/dist/runner/runner.js +1 -5
- package/dist/runner/sdk-ask.d.ts +78 -0
- package/dist/runner/sdk-ask.js +158 -0
- package/dist/runner/sdk-loop.d.ts +2 -4
- package/dist/runner/sdk-loop.js +29 -49
- package/dist/runner/store-secrets.d.ts +5 -3
- package/dist/runner/store-secrets.js +5 -1
- package/dist/runner/workflow-first.d.ts +5 -0
- package/dist/runner/workflow-first.js +4 -0
- package/dist/runner/workflow-spec.js +7 -2
- package/dist/runs-over-store.d.ts +16 -28
- package/dist/runs-over-store.js +31 -38
- package/dist/sdk/runs.d.ts +6 -11
- package/dist/sdk/runs.js +20 -41
- package/dist/sdk/schema.js +3 -4
- package/dist/seal-key.d.ts +5 -0
- package/dist/seal-key.js +7 -0
- package/dist/secrets.d.ts +3 -0
- package/dist/secrets.js +16 -3
- package/dist/server.d.ts +55 -33
- package/dist/server.js +689 -322
- package/dist/sign-ins-store.d.ts +8 -0
- package/dist/sign-ins-store.js +36 -1
- package/dist/skills.js +1 -1
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +3 -0
- package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
- package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
- package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
- package/dist/store/schema.d.ts +53 -4
- package/dist/store/schema.js +137 -6
- package/dist/store/sqlite/connection.d.ts +2 -0
- package/dist/store/sqlite/connection.js +3 -1
- package/dist/store/sqlite/run-patch.d.ts +0 -17
- package/dist/store/sqlite/run-patch.js +4 -33
- package/dist/store/sqlite/store.js +246 -63
- package/dist/store/sqlite/worker.js +25 -0
- package/dist/store/store.d.ts +193 -36
- package/dist/store/store.js +25 -3
- package/dist/store-reads/learning.d.ts +102 -204
- package/dist/store-reads/learning.js +159 -321
- package/dist/store-reads/loop.d.ts +0 -1
- package/dist/store-reads/loop.js +1 -1
- package/dist/store-view.d.ts +29 -1
- package/dist/store-view.js +97 -31
- package/dist/template-eval.d.ts +3 -6
- package/dist/template-eval.js +22 -36
- package/dist/templates.d.ts +8 -4
- package/dist/templates.js +44 -6
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -1
- package/dist/timeline/timeline.js +16 -0
- package/dist/tool-gate.d.ts +0 -7
- package/dist/tool-gate.js +1 -15
- package/dist/tool-keys-store.d.ts +1 -1
- package/dist/tool-keys.d.ts +6 -4
- package/dist/tool-keys.js +12 -6
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +11 -4
- package/dist/triggers.d.ts +65 -6
- package/dist/triggers.js +125 -19
- package/dist/validate.js +1 -1
- package/dist/webhooks.d.ts +7 -2
- package/dist/webhooks.js +12 -5
- package/dist/workspace/agent-computer.d.ts +2 -0
- package/dist/workspace/agent-computer.js +2 -0
- package/dist/workspace/archil-claim.d.ts +7 -0
- package/dist/workspace/archil-claim.js +29 -0
- package/dist/workspace/archil.d.ts +9 -1
- package/dist/workspace/archil.js +165 -3
- package/dist/workspace/attach.d.ts +3 -1
- package/dist/workspace/attach.js +2 -0
- package/dist/workspace/attached-computers.d.ts +16 -5
- package/dist/workspace/attached-computers.js +25 -9
- package/dist/workspace/computer-deps.js +1 -1
- package/dist/workspace/computer-for-claim.d.ts +7 -3
- package/dist/workspace/computer-for-claim.js +119 -22
- package/dist/workspace/computer-hold.js +2 -1
- package/dist/workspace/computer-kept.d.ts +11 -1
- package/dist/workspace/computer-kept.js +24 -3
- package/dist/workspace/resolve-computer.d.ts +33 -19
- package/dist/workspace/resolve-computer.js +172 -64
- package/dist/workspace/revision-skills.d.ts +1 -2
- package/dist/workspace/revision-skills.js +3 -4
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +5 -0
- package/dist/workspace/synced-folder.d.ts +85 -0
- package/dist/workspace/synced-folder.js +230 -0
- package/dist/workspace/workspace.d.ts +4 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -10
- package/templates/README.md +8 -8
- package/templates/inbound-lead/agent.md +5 -4
- package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
- package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
- package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
- package/templates/inbound-lead/lead.schema.json +6 -5
- package/templates/inbound-lead/rules/RUBRIC.md +4 -4
- package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
- package/templates/kyb/agent.md +2 -1
- package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
- package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
- package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
- package/templates/release-notes/evals/learned-style/case.yaml +4 -4
- package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
- package/templates/release-notes/evals/learned-style/prompt.md +1 -1
- package/dist/console/assets/index-BUktRvS-.css +0 -1
- package/dist/console/assets/index-nB9kTfIN.js +0 -711
- package/dist/learn/grade.d.ts +0 -138
- package/dist/learn/grade.js +0 -682
- package/dist/learn/notes.d.ts +0 -81
- package/dist/learn/notes.js +0 -178
- package/dist/learn/reflect.d.ts +0 -77
- package/dist/learn/reflect.js +0 -228
- package/dist/learn/relevance.d.ts +0 -24
- package/dist/learn/relevance.js +0 -91
- package/dist/learn/seed-check.d.ts +0 -74
- package/dist/learn/seed-check.js +0 -103
- package/dist/learning-batch.d.ts +0 -291
- package/dist/learning-batch.js +0 -600
- package/dist/learning-evals.d.ts +0 -35
- package/dist/learning-evals.js +0 -99
- package/dist/native/context.d.ts +0 -6
- package/dist/native/context.js +0 -22
- package/dist/propose.d.ts +0 -52
- package/dist/propose.js +0 -224
- package/dist/runner/learning-ask.d.ts +0 -47
- package/dist/runner/learning-ask.js +0 -128
- package/dist/runner/learning-dispatch.d.ts +0 -45
- package/dist/runner/learning-dispatch.js +0 -99
- package/dist/runner/learning-factory.d.ts +0 -16
- package/dist/runner/learning-factory.js +0 -50
- package/dist/runner/learning-loop.d.ts +0 -273
- package/dist/runner/learning-loop.js +0 -521
- package/dist/usage.d.ts +0 -11
- package/dist/usage.js +0 -11
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
package/dist/learning-batch.js
DELETED
|
@@ -1,600 +0,0 @@
|
|
|
1
|
-
// Learn from a CSV: a learning batch (POST /agents/{id}/learning/batches). A person gives rows, which columns are the input
|
|
2
|
-
// and which the answer, and a cap; the server runs the agent on each row in order with learning on, and after each run tells
|
|
3
|
-
// it the reference answer next to its own, the hindsight review the learning bench sends (learn-bench's follow-up: a message
|
|
4
|
-
// to the finished run, which looks back again). The batch's progress is the store's, never the browser's: a header per batch
|
|
5
|
-
// and one key per row in the server's settings (no table). The batch and each row are one machine (BATCH_MOVES, ROW_MOVES):
|
|
6
|
-
// every move is one write, in an order where a stop between any two writes leaves a state the next start takes up, and every
|
|
7
|
-
// side effect (a run's start, its review) is keyed so a move taken again finds it done. One row at a time, since what a row
|
|
8
|
-
// teaches is what the next one is given.
|
|
9
|
-
// Nothing here knows a job: the input is the chosen columns as {column: value}, the match is structural equality (a display,
|
|
10
|
-
// not a judge: the learning grade is the judge), and the words of the review are generic.
|
|
11
|
-
import { randomBytes } from "node:crypto";
|
|
12
|
-
import { ApiError, invalid } from "./errors.js";
|
|
13
|
-
import { EFFORTS } from "./model.js";
|
|
14
|
-
import { isObject, unknownFields } from "./validate.js";
|
|
15
|
-
/** The most rows a batch holds, and the longest a cell, in characters (the whole body is under the server's body limit). */
|
|
16
|
-
export const BATCH_ROWS_MAX = 500;
|
|
17
|
-
export const BATCH_CELL_MAX = 8_000;
|
|
18
|
-
const COLUMNS_MAX = 40;
|
|
19
|
-
/** The row machine. pending -> started: its run started under the row's key (a start the server stopped before this write
|
|
20
|
-
* is found again by the key); started -> answered: the run's first end, its answer, right or wrong and the review's words
|
|
21
|
-
* written once; answered -> reviewed: the review sent (a resume finds it in the run's commands and sends none); reviewed ->
|
|
22
|
-
* done: the review's turn completed, its learning settled and its all-in known (its audit's shadow run ended). Every other ending is failed, and a live row (started,
|
|
23
|
-
* answered, reviewed) moves to failed only once its run has stopped (cancelled, waited for with its grade, then booked). */
|
|
24
|
-
export const ROW_MOVES = { pending: ["started", "failed"], started: ["answered", "failed"], answered: ["reviewed", "failed"], reviewed: ["done", "failed"], done: [], failed: [] };
|
|
25
|
-
const LIVE = new Set(["started", "answered", "reviewed"]);
|
|
26
|
-
export const stageOf = (row) => (row.state !== "running" ? row.state : row.reviewed ? "reviewed" : row.right !== undefined ? "answered" : "started");
|
|
27
|
-
/** The batch machine, in its header: made (the agent's index, then the rows, then the header, so a header is never saved
|
|
28
|
-
* where a read can't find it) -> running -> ending (one write: `ending`) -> completed, cancelled or stopped (one write, once
|
|
29
|
-
* no row is live). A start takes up every header still running: a running one at its first unfinished row, an ending one
|
|
30
|
-
* where its ending stands. */
|
|
31
|
-
export const BATCH_MOVES = { running: ["ending"], ending: ["completed", "cancelled", "stopped"], completed: [], cancelled: [], stopped: [] };
|
|
32
|
-
/** A run's figures from its cost (costRunOf) and the end of each round its learning kept, in order (the job's, then each
|
|
33
|
-
* follow-up's, a review's): what every round learned, each name once; the last merge's commit; and each round that merged
|
|
34
|
-
* workflows as a revision of its own, with its own commit (a round dropped is none, and moves no other round's commit). */
|
|
35
|
-
export function figuresOf(cost, ends, unsettled = false) {
|
|
36
|
-
const names = (pick) => [...new Set(ends.flatMap((e) => (e ? (pick(e) ?? []).map((x) => x.name) : [])))];
|
|
37
|
-
const revisions = ends.flatMap((e) => (e?.workflows?.length ? [{ commit: e.merged ?? null, workflows: [...new Set(e.workflows.map((w) => w.name))] }] : []));
|
|
38
|
-
const merged = [...ends].reverse().find((e) => e?.merged)?.merged ?? null;
|
|
39
|
-
return { path: cost.path, cost_usd: cost.cost_usd, learning_usd: cost.learning_usd, total_usd: cost.total_usd, merged, revisions, learned: { notes: names((e) => e.learned), skills: names((e) => e.skills), workflows: names((e) => e.workflows) }, ...(unsettled ? { unsettled: true } : {}) };
|
|
40
|
-
}
|
|
41
|
-
const ANSWER_SHOWN = 2_000;
|
|
42
|
-
/** The least cap a run can take a step under (cap.ts: the next step needs at least a cent). */
|
|
43
|
-
export const RUN_CAP_MIN_USD = 0.01;
|
|
44
|
-
const HEAD = (id) => `learning_batch/${id}`;
|
|
45
|
-
const ROW = (id, n) => `learning_batch/${id}/row/${n}`;
|
|
46
|
-
const INDEX = (agentId) => `learning_batches/${agentId}`;
|
|
47
|
-
/** The run origin a row's run starts under: one run a row, whatever stops between its start and its row's write. */
|
|
48
|
-
export const ROW_KEY = (id, n) => `learning_batch:${id}:row:${n}`;
|
|
49
|
-
export const BATCH_ID = /^lb_[0-9a-f]{16}$/;
|
|
50
|
-
const text = (value) => (value ?? "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
51
|
-
/** A decimal number's text in one form (no sign on zero, no leading or trailing zeros), never through a float: two numbers
|
|
52
|
-
* are the same when every digit is. Null for text that is no decimal number. */
|
|
53
|
-
const num = (value) => {
|
|
54
|
-
const m = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(value);
|
|
55
|
-
if (!m)
|
|
56
|
-
return null;
|
|
57
|
-
const whole = m[2].replace(/^0+(?=\d)/, ""), part = (m[3] ?? "").replace(/0+$/, "");
|
|
58
|
-
const sign = m[1] === "-" && !(whole === "0" && part === "") ? "-" : "";
|
|
59
|
-
return `${sign}${whole}${part ? `.${part}` : ""}`;
|
|
60
|
-
};
|
|
61
|
-
/** The answer's field at a dotted path, from the answer text when it is JSON (or holds a fenced json block); the answer as it
|
|
62
|
-
* is when no field is named. A value that is not a scalar, or a path that is not there, is no answer (null). */
|
|
63
|
-
export function answerValue(answer, field) {
|
|
64
|
-
if (answer === null)
|
|
65
|
-
return null;
|
|
66
|
-
if (field === null)
|
|
67
|
-
return answer;
|
|
68
|
-
for (const candidate of [answer, /```(?:json)?\s*\n([\s\S]*?)\n```/.exec(answer)?.[1]]) {
|
|
69
|
-
try {
|
|
70
|
-
let at = JSON.parse(candidate ?? "");
|
|
71
|
-
for (const key of field.split("."))
|
|
72
|
-
at = at !== null && typeof at === "object" ? at[key] : undefined;
|
|
73
|
-
if (typeof at === "string" || typeof at === "number" || typeof at === "boolean")
|
|
74
|
-
return String(at);
|
|
75
|
-
}
|
|
76
|
-
catch { }
|
|
77
|
-
}
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
/** Whether an answer is the reference: equal once trimmed, case-folded and whitespace-collapsed, two numbers by value (by
|
|
81
|
-
* every digit: num). */
|
|
82
|
-
export function matches(answer, reference) {
|
|
83
|
-
if (answer === null)
|
|
84
|
-
return false;
|
|
85
|
-
const a = num(answer.trim()), r = num(reference.trim());
|
|
86
|
-
return a !== null && r !== null ? a === r : text(answer) === text(reference);
|
|
87
|
-
}
|
|
88
|
-
/** What a run is given for a row: its one input column's text as it is, or each chosen column on a line, `column: value`, in
|
|
89
|
-
* the order the batch names them (an agent's input is its `content`, a person's words). */
|
|
90
|
-
export const contentOf = (inputs, row) => (inputs.length === 1 ? row[inputs[0]] : inputs.map((column) => `${column}: ${row[column]}`).join("\n"));
|
|
91
|
-
/** The review a run is sent, from its whole answer: the same words right or wrong. An answer past ANSWER_SHOWN characters is
|
|
92
|
-
* quoted to there, and the review says it was cut and where the whole one is (never a prefix passed off as the answer). */
|
|
93
|
-
export const reviewText = (reference, answer) => answer !== null && answer.length > ANSWER_SHOWN
|
|
94
|
-
? `Review: the reference answer is "${reference}"; you answered "${answer.slice(0, ANSWER_SHOWN)}…" (cut here: your answer runs to ${answer.length} characters, and the whole of it is your last answer in this run).`
|
|
95
|
-
: `Review: the reference answer is "${reference}"; you answered "${answer ?? "nothing"}".`;
|
|
96
|
-
/** A create's body, checked: its issues, or the parsed batch. */
|
|
97
|
-
export function checkBatchBody(body) {
|
|
98
|
-
const issues = unknownFields(body, ["inputs", "answer", "rows", "max_cost_usd", "answer_field", "effort"]);
|
|
99
|
-
const columns = (key) => {
|
|
100
|
-
const v = body[key];
|
|
101
|
-
if (!Array.isArray(v) || !v.length || v.length > COLUMNS_MAX || !v.every((c) => typeof c === "string" && c.length > 0 && c.length <= 200) || new Set(v).size !== v.length) {
|
|
102
|
-
issues.push({ field: key, reason: v === undefined ? "missing" : "wrong_type", message: `${key} is the columns the agent is given: 1 to ${COLUMNS_MAX} distinct column names` });
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
return v;
|
|
106
|
-
};
|
|
107
|
-
const inputs = columns("inputs");
|
|
108
|
-
const answer = body.answer;
|
|
109
|
-
if (typeof answer !== "string" || !answer || answer.length > 200)
|
|
110
|
-
issues.push({ field: "answer", reason: answer === undefined ? "missing" : "wrong_type", message: "answer is the column that holds the reference answer" });
|
|
111
|
-
else if (inputs?.includes(answer))
|
|
112
|
-
issues.push({ field: "answer", reason: "not_allowed", message: "the answer column is no input column: the agent is never given the answer", fix: `Remove ${answer} from inputs.` });
|
|
113
|
-
const field = body.answer_field;
|
|
114
|
-
if (field !== undefined && (typeof field !== "string" || !/^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/.test(field)))
|
|
115
|
-
issues.push({ field: "answer_field", reason: "wrong_type", message: "answer_field is a dotted path into a JSON answer, such as result.code" });
|
|
116
|
-
const cap = body.max_cost_usd;
|
|
117
|
-
if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
|
|
118
|
-
issues.push({ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd caps what the batch's runs spend (their jobs, look-backs and review turns), a number above 0" });
|
|
119
|
-
// A run's effort as POST /agents/{id}/runs checks it (server.ts runBodyIssues), in its words: a typo is refused here, never
|
|
120
|
-
// a batch whose every row fails.
|
|
121
|
-
if (body.effort !== undefined && !EFFORTS.includes(body.effort))
|
|
122
|
-
issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
|
|
123
|
-
const rows = body.rows;
|
|
124
|
-
const parsed = [];
|
|
125
|
-
if (!Array.isArray(rows) || !rows.length)
|
|
126
|
-
issues.push({ field: "rows", reason: rows === undefined ? "missing" : "wrong_type", message: "rows is a list of rows, each {column: text}" });
|
|
127
|
-
else if (rows.length > BATCH_ROWS_MAX)
|
|
128
|
-
issues.push({ field: "rows", reason: "too_long", message: `a batch holds at most ${BATCH_ROWS_MAX} rows` });
|
|
129
|
-
else if (inputs && typeof answer === "string") {
|
|
130
|
-
rows.forEach((row, i) => {
|
|
131
|
-
const cell = (key) => (isObject(row) && typeof row[key] === "string" && row[key].length <= BATCH_CELL_MAX ? row[key] : null);
|
|
132
|
-
const cells = [];
|
|
133
|
-
for (const key of inputs) {
|
|
134
|
-
const v = cell(key);
|
|
135
|
-
if (v === null)
|
|
136
|
-
return void issues.push({ field: `rows[${i}].${key}`, reason: "wrong_type", message: `row ${i + 1} has no text at ${key} (at most ${BATCH_CELL_MAX} characters)` });
|
|
137
|
-
cells.push([key, v]);
|
|
138
|
-
}
|
|
139
|
-
// Own keys only (a column may be named __proto__: an assignment on {} would drop its text).
|
|
140
|
-
const input = Object.fromEntries(cells);
|
|
141
|
-
const reference = cell(answer);
|
|
142
|
-
if (reference === null || !reference.trim())
|
|
143
|
-
return void issues.push({ field: `rows[${i}].${answer}`, reason: "missing", message: `row ${i + 1} has no reference answer at ${answer}` });
|
|
144
|
-
parsed.push({ input, reference });
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
if (issues.length || !inputs || typeof answer !== "string")
|
|
148
|
-
return issues;
|
|
149
|
-
return { inputs, answer, answer_field: typeof field === "string" ? field : null, effort: typeof body.effort === "string" ? body.effort : null, max_cost_usd: cap, rows: parsed };
|
|
150
|
-
}
|
|
151
|
-
const usd = (v) => Math.round(v * 1e6) / 1e6;
|
|
152
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
153
|
-
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
154
|
-
/** A run and its learning have stopped: ended, and its learning over (merged, dropped, none), or never begun on a run that
|
|
155
|
-
* did not complete (one stopped before its end-of-run turn keeps `seeded`: nothing more runs for it). */
|
|
156
|
-
const settled = (s) => TERMINAL.has(s.status) && s.ended_at !== null && (s.learning_state === null || s.learning_state === "merged" || s.learning_state === "dropped" || (s.status !== "completed" && s.learning_state === "seeded"));
|
|
157
|
-
/** How many times in a row a batch's loop may fail on the store (or a run's stop) and be taken up again from what the store
|
|
158
|
-
* holds, before the batch ends stopped on the error's words. */
|
|
159
|
-
const LOOP_TRIES = 5;
|
|
160
|
-
const words = (error) => String(error?.message ?? error).slice(0, 400);
|
|
161
|
-
/** A row as a read shows it: no input (its run holds it), no review words, no revisions (the header's), and every text
|
|
162
|
-
* that can hold a value through `cut` (a lesson's name as the learning routes show one: notesView). */
|
|
163
|
-
const shownLessons = (l, cut) => ({ notes: l.notes.map(cut.text), skills: l.skills.map(cut.name), workflows: l.workflows.map(cut.name) });
|
|
164
|
-
function shownRow({ input: _input, review: _review, revisions: _revisions, ...r }, cut) {
|
|
165
|
-
return {
|
|
166
|
-
...r,
|
|
167
|
-
reference: cut.text(r.reference),
|
|
168
|
-
...(typeof r.answer === "string" ? { answer: cut.text(r.answer) } : {}),
|
|
169
|
-
...(r.learned ? { learned: shownLessons(r.learned, cut) } : {}),
|
|
170
|
-
...(r.error === undefined ? {} : { error: cut.text(r.error) }),
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
const batchStage = (h) => (h.status !== "running" ? h.status : h.ending ? "ending" : "running");
|
|
174
|
-
/** The batches of one server: its running loops, and the store reads and writes. */
|
|
175
|
-
export class LearningBatches {
|
|
176
|
-
host;
|
|
177
|
-
loops = new Map();
|
|
178
|
-
index = Promise.resolve();
|
|
179
|
-
halting = false;
|
|
180
|
-
constructor(host) {
|
|
181
|
-
this.host = host;
|
|
182
|
-
}
|
|
183
|
-
get settings() { return this.host.settings; }
|
|
184
|
-
get clock() { return this.host.now ?? Date.now; }
|
|
185
|
-
get pollMs() { return this.host.pollMs ?? 1_000; }
|
|
186
|
-
async header(id) { return (await this.settings.get(HEAD(id))); }
|
|
187
|
-
async row(id, n) { return (await this.settings.get(ROW(id, n))); }
|
|
188
|
-
async save(h) { await this.settings.put(HEAD(h.id), h); }
|
|
189
|
-
async saveRow(id, row) { await this.settings.put(ROW(id, row.n), row); }
|
|
190
|
-
ids = async (agentId) => (await this.settings.get(INDEX(agentId))) ?? [];
|
|
191
|
-
/** Makes a batch of agent `agentId` and starts its loop. 409 when the agent does not learn or has a batch running. */
|
|
192
|
-
async create(agentId, body) {
|
|
193
|
-
const checked = checkBatchBody(body);
|
|
194
|
-
if (Array.isArray(checked))
|
|
195
|
-
throw invalid(checked);
|
|
196
|
-
const learns = await this.host.learning(agentId);
|
|
197
|
-
if (!learns.learns)
|
|
198
|
-
throw new ApiError("agent_not_runnable", `The agent ${agentId} does not learn here: ${learns.why}`, { details: { learning: false } });
|
|
199
|
-
// A batch whose progress would be withheld is never started.
|
|
200
|
-
await this.host.shown(agentId);
|
|
201
|
-
let made;
|
|
202
|
-
// The index and the running check are one step, so two creates never both start (one process: a queue, not a lock).
|
|
203
|
-
const step = this.index.then(async () => {
|
|
204
|
-
const ids = await this.ids(agentId);
|
|
205
|
-
for (const other of ids.slice(-5))
|
|
206
|
-
if ((await this.header(other))?.status === "running")
|
|
207
|
-
throw new ApiError("agent_not_runnable", `The agent ${agentId} has a learning batch running (${other}): learning is ordered, so one batch runs at a time. Cancel it, or wait for it.`, { details: { batch_id: other } });
|
|
208
|
-
const id = `lb_${randomBytes(8).toString("hex")}`;
|
|
209
|
-
const now = new Date(this.clock()).toISOString();
|
|
210
|
-
made = { id, agent_id: agentId, created_at: now, ended_at: null, status: "running", stopped: null, inputs: checked.inputs, answer: checked.answer, answer_field: checked.answer_field, effort: checked.effort, max_cost_usd: checked.max_cost_usd, total: checked.rows.length, finished: 0, right: 0, wrong: 0, failed: 0, spent_usd: 0, unknown_cost_rows: 0, paths: { agent: 0, handed_back: 0, workflow: 0 }, lessons: { notes: [], skills: [], workflows: [] }, revisions: [] };
|
|
211
|
-
// The index first, the header last: a batch is made (and runs, and a start takes it up) only once its header is
|
|
212
|
-
// saved, and by then the list and the running check find it. A stop before that leaves an id with no header, which
|
|
213
|
-
// nothing shows, runs or counts.
|
|
214
|
-
await this.settings.put(INDEX(agentId), [...ids, id]);
|
|
215
|
-
for (const [i, r] of checked.rows.entries())
|
|
216
|
-
await this.saveRow(id, { n: i + 1, state: "pending", input: r.input, reference: r.reference });
|
|
217
|
-
await this.save(made);
|
|
218
|
-
});
|
|
219
|
-
this.index = step.catch(() => undefined);
|
|
220
|
-
await step;
|
|
221
|
-
this.arm(made.id);
|
|
222
|
-
return made;
|
|
223
|
-
}
|
|
224
|
-
/** The server started: every batch still running takes up where it stopped (an ending one, where its ending stands). */
|
|
225
|
-
async resume() {
|
|
226
|
-
let n = 0;
|
|
227
|
-
for (const { key, value } of await this.settings.all()) {
|
|
228
|
-
if (!/^learning_batch\/lb_[0-9a-f]{16}$/.test(key))
|
|
229
|
-
continue;
|
|
230
|
-
if (value.status === "running") {
|
|
231
|
-
this.arm(value.id);
|
|
232
|
-
n++;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
return n;
|
|
236
|
-
}
|
|
237
|
-
/** A batch whole as progress: its header, what is under way and what it costs now, and its rows (no input: the run holds
|
|
238
|
-
* it), every text through the agent's cut now (host.shown). The cost now is the finished rows' and the live row's figures
|
|
239
|
-
* so far, by the function that books it (figures). */
|
|
240
|
-
async read(agentId, id) {
|
|
241
|
-
const h = await this.need(agentId, id);
|
|
242
|
-
const cut = await this.host.shown(agentId);
|
|
243
|
-
const rows = [];
|
|
244
|
-
for (let n = 1; n <= h.total; n++)
|
|
245
|
-
rows.push(await this.row(id, n));
|
|
246
|
-
const live = rows.find((r) => LIVE.has(stageOf(r)) && r.run_id);
|
|
247
|
-
const inflight = live?.run_id ? ((await this.host.figures(live.run_id).catch(() => undefined))?.total_usd ?? null) : 0;
|
|
248
|
-
return { ...this.shown(h, cut), current: live?.n ?? null, cost_usd: inflight === null || h.unknown_cost_rows ? null : usd(h.spent_usd + inflight), rows: rows.map((r) => shownRow(r, cut)) };
|
|
249
|
-
}
|
|
250
|
-
/** A batch as the header says it, for a list (no rows), its text through `cut`. A finished row whose cost is not known
|
|
251
|
-
* makes the cost, and what is left of the cap, unknown (null): the known part is never shown as the whole. */
|
|
252
|
-
shown(h, cut) {
|
|
253
|
-
const { ending: _ending, error, ...shown } = h;
|
|
254
|
-
const known = h.unknown_cost_rows === 0;
|
|
255
|
-
return {
|
|
256
|
-
...shown,
|
|
257
|
-
inputs: h.inputs.map(cut.name),
|
|
258
|
-
answer: cut.name(h.answer),
|
|
259
|
-
answer_field: h.answer_field === null ? null : cut.name(h.answer_field),
|
|
260
|
-
lessons: shownLessons(h.lessons, cut),
|
|
261
|
-
revisions: h.revisions.map((r) => ({ ...r, workflows: r.workflows.map(cut.name) })),
|
|
262
|
-
...(error === undefined ? {} : { error: cut.text(error) }),
|
|
263
|
-
cost_usd: known ? h.spent_usd : null,
|
|
264
|
-
remaining_usd: known ? usd(Math.max(0, h.max_cost_usd - h.spent_usd)) : null,
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
async list(agentId) {
|
|
268
|
-
const cut = await this.host.shown(agentId);
|
|
269
|
-
const out = [];
|
|
270
|
-
for (const id of (await this.ids(agentId)).slice(-20).reverse()) {
|
|
271
|
-
const h = await this.header(id);
|
|
272
|
-
if (h)
|
|
273
|
-
out.push(this.shown(h, cut));
|
|
274
|
-
}
|
|
275
|
-
return { batches: out };
|
|
276
|
-
}
|
|
277
|
-
/** A person's cancel: the batch's loop ends it cancelled, its live row's run stopped and booked first; answers once it has,
|
|
278
|
-
* as a read does. The cancel stands even when its answer is withheld (a 403 from the cut): stopping spend never waits on
|
|
279
|
-
* a sign-in. */
|
|
280
|
-
async cancel(agentId, id) {
|
|
281
|
-
const h = await this.need(agentId, id);
|
|
282
|
-
if (h.status === "running" && !this.halting) {
|
|
283
|
-
const loop = this.arm(id);
|
|
284
|
-
loop.cancelled = true;
|
|
285
|
-
await loop.done;
|
|
286
|
-
}
|
|
287
|
-
return this.read(agentId, id);
|
|
288
|
-
}
|
|
289
|
-
/** The server is stopping: every loop lets go where it stands, its batch still running (resume takes it up). */
|
|
290
|
-
async halt() {
|
|
291
|
-
this.halting = true;
|
|
292
|
-
const all = [...this.loops.values()];
|
|
293
|
-
for (const loop of all)
|
|
294
|
-
loop.halted = true;
|
|
295
|
-
await Promise.all(all.map((loop) => loop.done));
|
|
296
|
-
}
|
|
297
|
-
/** Waits for a batch's loop to end (a test's and a shutdown's). */
|
|
298
|
-
async idle(id) { await this.loops.get(id)?.done; }
|
|
299
|
-
async need(agentId, id) {
|
|
300
|
-
const h = BATCH_ID.test(id) ? await this.header(id) : undefined;
|
|
301
|
-
if (!h || h.agent_id !== agentId)
|
|
302
|
-
throw new ApiError("not_found", `no learning batch ${id} of agent ${agentId}`);
|
|
303
|
-
return h;
|
|
304
|
-
}
|
|
305
|
-
/** The batch's loop in this process, started if it has none. A loop that fails (the store, a run's stop) is taken up again
|
|
306
|
-
* from what the store holds, LOOP_TRIES times, then ends its batch stopped on the error's words: never by letting the
|
|
307
|
-
* batch go with its row's run still going (the batch stays running, and owned, until its ending has stopped that run). */
|
|
308
|
-
arm(id) {
|
|
309
|
-
const had = this.loops.get(id);
|
|
310
|
-
if (had)
|
|
311
|
-
return had;
|
|
312
|
-
const loop = { cancelled: false, halted: this.halting, failed: null, done: Promise.resolve() };
|
|
313
|
-
this.loops.set(id, loop);
|
|
314
|
-
loop.done = (async () => {
|
|
315
|
-
for (let tries = 1;; tries++) {
|
|
316
|
-
try {
|
|
317
|
-
return await this.loop(id, loop);
|
|
318
|
-
}
|
|
319
|
-
catch (error) {
|
|
320
|
-
if (loop.halted)
|
|
321
|
-
return;
|
|
322
|
-
if (tries >= LOOP_TRIES)
|
|
323
|
-
loop.failed ??= words(error);
|
|
324
|
-
await sleep(Math.min(30_000, this.pollMs * 2 ** tries));
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
})().finally(() => void this.loops.delete(id));
|
|
328
|
-
return loop;
|
|
329
|
-
}
|
|
330
|
-
/** The batch machine from where the store has it: a running batch takes its rows in order until one of them, or the cap,
|
|
331
|
-
* the agent's learning, a cancel or a failure, ends it (`ending`); an ending batch stops its live row and ends. */
|
|
332
|
-
async loop(id, loop) {
|
|
333
|
-
// The header's figures folded from the rows as saved (a server that stopped between a row's write and its header's
|
|
334
|
-
// books it here, once).
|
|
335
|
-
let h = await this.tally((await this.header(id)));
|
|
336
|
-
if (batchStage(h) !== "running" && batchStage(h) !== "ending")
|
|
337
|
-
return;
|
|
338
|
-
if (loop.failed && !h.ending)
|
|
339
|
-
h = await this.ending(h, { status: "stopped", stopped: null, error: loop.failed });
|
|
340
|
-
// A row booked with its cost unknown stops the batch, read from the rows: a stop between that row's write and the
|
|
341
|
-
// batch's ending is no batch that runs on, or completes.
|
|
342
|
-
if (h.unknown_cost_rows && !h.ending)
|
|
343
|
-
h = await this.ending(h, { status: "stopped", stopped: "cost_unknown" });
|
|
344
|
-
for (let n = 1; n <= h.total && !h.ending; n++) {
|
|
345
|
-
if (loop.halted)
|
|
346
|
-
return;
|
|
347
|
-
if (loop.cancelled)
|
|
348
|
-
break;
|
|
349
|
-
let row = await this.row(id, n);
|
|
350
|
-
const stage = stageOf(row);
|
|
351
|
-
if (stage === "done" || stage === "failed")
|
|
352
|
-
continue;
|
|
353
|
-
if (stage === "pending") {
|
|
354
|
-
// A run started under the row's key before its row kept the id is that row's run: never a second.
|
|
355
|
-
const found = await this.host.find(ROW_KEY(id, n));
|
|
356
|
-
if (found)
|
|
357
|
-
row = await this.move(id, row, "started", { run_id: found });
|
|
358
|
-
else {
|
|
359
|
-
const room = this.room(h);
|
|
360
|
-
if (room !== true) {
|
|
361
|
-
h = await this.ending(h, { status: "stopped", stopped: room });
|
|
362
|
-
break;
|
|
363
|
-
}
|
|
364
|
-
// Learning is checked again before every row: an agent (or a server) that stopped learning runs no row unlearned.
|
|
365
|
-
const learns = await this.host.learning(h.agent_id);
|
|
366
|
-
if (!learns.learns) {
|
|
367
|
-
h = await this.ending(h, { status: "stopped", stopped: "learning_off", error: `The agent does not learn here: ${learns.why}` });
|
|
368
|
-
break;
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
h = await this.runRow(h, row, loop);
|
|
373
|
-
if (loop.halted)
|
|
374
|
-
return;
|
|
375
|
-
if (h.unknown_cost_rows && !loop.cancelled) {
|
|
376
|
-
h = await this.ending(h, { status: "stopped", stopped: "cost_unknown" });
|
|
377
|
-
break;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
if (loop.halted)
|
|
381
|
-
return;
|
|
382
|
-
if (!h.ending)
|
|
383
|
-
h = await this.ending(h, loop.cancelled ? { status: "cancelled", stopped: null } : { status: "completed", stopped: null });
|
|
384
|
-
await this.finish(h, loop);
|
|
385
|
-
}
|
|
386
|
-
/** Whether another row may start: the cap's room covers the mean total of the rows done, and a run's own smallest cap (a
|
|
387
|
-
* run capped under a cent cannot take a step: cap.ts), so a row's run is never started to pause at its cap. */
|
|
388
|
-
room(h) {
|
|
389
|
-
if (h.unknown_cost_rows)
|
|
390
|
-
return "cost_unknown";
|
|
391
|
-
const left = usd(h.max_cost_usd - h.spent_usd);
|
|
392
|
-
const done = h.finished - h.unknown_cost_rows;
|
|
393
|
-
const typical = done > 0 ? usd(h.spent_usd / done) : 0;
|
|
394
|
-
return left >= Math.max(typical, RUN_CAP_MIN_USD) ? true : "cap";
|
|
395
|
-
}
|
|
396
|
-
/** running -> ending: how the batch ends, one write, before its live row is stopped. */
|
|
397
|
-
async ending(h, ending) {
|
|
398
|
-
if (batchStage(h) !== "running")
|
|
399
|
-
throw new Error(`batch ${h.id} cannot end from ${batchStage(h)}`);
|
|
400
|
-
const next = { ...h, ending };
|
|
401
|
-
await this.save(next);
|
|
402
|
-
return next;
|
|
403
|
-
}
|
|
404
|
-
/** ending -> completed, cancelled or stopped: every live row's run stopped and booked failed (on the ending's words), then
|
|
405
|
-
* the header's one write. A server stopping meanwhile leaves the batch ending, for the next start to finish. */
|
|
406
|
-
async finish(h, loop) {
|
|
407
|
-
const ending = h.ending;
|
|
408
|
-
const why = ending.error ?? (ending.status === "cancelled" ? "the batch was cancelled" : "the batch stopped before this row ended");
|
|
409
|
-
for (let n = 1; n <= h.total; n++) {
|
|
410
|
-
const row = await this.row(h.id, n);
|
|
411
|
-
if (!LIVE.has(stageOf(row)))
|
|
412
|
-
continue;
|
|
413
|
-
h = await this.fail(h, row, why, loop);
|
|
414
|
-
if (loop.halted)
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
const { ending: _ending, ...rest } = await this.tally(h);
|
|
418
|
-
if (!BATCH_MOVES.ending.includes(ending.status))
|
|
419
|
-
throw new Error(`batch ${h.id} cannot end ${ending.status}`);
|
|
420
|
-
await this.save({ ...rest, status: ending.status, stopped: ending.stopped, ...(ending.error ? { error: ending.error } : {}), ended_at: new Date(this.clock()).toISOString() });
|
|
421
|
-
}
|
|
422
|
-
/** One row's move: allowed by ROW_MOVES, one write of its record. */
|
|
423
|
-
async move(id, row, to, patch) {
|
|
424
|
-
const from = stageOf(row);
|
|
425
|
-
if (!ROW_MOVES[from].includes(to))
|
|
426
|
-
throw new Error(`row ${row.n} of batch ${id} cannot go from ${from} to ${to}`);
|
|
427
|
-
const next = { ...row, ...patch, state: to === "done" || to === "failed" ? to : "running" };
|
|
428
|
-
if (stageOf(next) !== to)
|
|
429
|
-
throw new Error(`row ${row.n} of batch ${id} wrote ${stageOf(next)} for ${to}`);
|
|
430
|
-
await this.saveRow(id, next);
|
|
431
|
-
return next;
|
|
432
|
-
}
|
|
433
|
-
/** Waits until `until` holds of the run's view. A view that fails is looked at again (a read is no ending); a cancel or a
|
|
434
|
-
* halt ends the wait ("stop": the row stays live, for the batch's ending or the next start), and so does the row's time. */
|
|
435
|
-
async wait(runId, until, loop) {
|
|
436
|
-
const started = this.clock();
|
|
437
|
-
for (;;) {
|
|
438
|
-
if (loop.cancelled || loop.halted)
|
|
439
|
-
return "stop";
|
|
440
|
-
const s = await this.host.view(runId).catch(() => undefined);
|
|
441
|
-
if (s && until(s))
|
|
442
|
-
return s;
|
|
443
|
-
if (this.clock() - started > (this.host.rowTimeoutMs ?? 30 * 60_000))
|
|
444
|
-
return "timeout";
|
|
445
|
-
await sleep(this.pollMs);
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
/** A row's every move from where its record stands: its run (started under the row's key), its answer (written once), the
|
|
449
|
-
* review (sent once), the review's turn and look-back, the booking. Returns the header folded once the row ended; a cancel
|
|
450
|
-
* or a halt leaves it live (the batch's ending stops it, or the next start takes it up). */
|
|
451
|
-
async runRow(h, row, loop) {
|
|
452
|
-
if (stageOf(row) === "pending") {
|
|
453
|
-
const key = ROW_KEY(h.id, row.n);
|
|
454
|
-
let runId;
|
|
455
|
-
try {
|
|
456
|
-
// Capped at what the batch has left: no request of the run, a cache miss included, passes it, so the batch's cap
|
|
457
|
-
// holds its runs.
|
|
458
|
-
runId = await this.host.start(h.agent_id, { input: { content: contentOf(h.inputs, row.input) }, max_cost_usd: usd(h.max_cost_usd - h.spent_usd), ...(h.effort ? { effort: h.effort } : {}) }, key);
|
|
459
|
-
}
|
|
460
|
-
catch (error) {
|
|
461
|
-
// A start that failed after its run was made is that run's start: found by the key, the row is its.
|
|
462
|
-
runId = await this.host.find(key);
|
|
463
|
-
if (!runId)
|
|
464
|
-
return this.fail(h, row, `the run did not start: ${words(error)}`, loop);
|
|
465
|
-
}
|
|
466
|
-
row = await this.move(h.id, row, "started", { run_id: runId });
|
|
467
|
-
}
|
|
468
|
-
const runId = row.run_id;
|
|
469
|
-
if (loop.cancelled || loop.halted)
|
|
470
|
-
return h;
|
|
471
|
-
// Its answer: its end, and its learning's. A person's wait (a question, a paused cap) is a failed row.
|
|
472
|
-
if (stageOf(row) === "started") {
|
|
473
|
-
const snap = await this.wait(runId, (s) => s.status === "input_required" || settled(s), loop);
|
|
474
|
-
if (snap === "stop")
|
|
475
|
-
return h;
|
|
476
|
-
if (snap === "timeout")
|
|
477
|
-
return this.fail(h, row, "the run did not end in time", loop);
|
|
478
|
-
if (snap.status === "input_required")
|
|
479
|
-
return this.fail(h, row, "the run waits on a person: a batch's runs ask no one", loop);
|
|
480
|
-
if (snap.status !== "completed")
|
|
481
|
-
return this.fail(h, row, snap.error ?? `the run ${snap.status}`, loop);
|
|
482
|
-
const whole = answerValue(snap.answer, h.answer_field);
|
|
483
|
-
// The path is the job's, read now, before the review's message is in the run (the run's answer is the job's).
|
|
484
|
-
const job = await this.host.figures(runId);
|
|
485
|
-
row = await this.move(h.id, row, "answered", { answer: whole === null ? null : whole.slice(0, ANSWER_SHOWN), right: matches(whole, row.reference), review_after: snap.ended_at, review: reviewText(row.reference, whole), ...(job ? { path: job.path } : {}) });
|
|
486
|
-
}
|
|
487
|
-
// The review: once (a resume finds it in the run's commands), to a completed run whose learning has settled.
|
|
488
|
-
if (stageOf(row) === "answered") {
|
|
489
|
-
const review = row.review;
|
|
490
|
-
try {
|
|
491
|
-
if (!(await this.host.sent(runId, review)))
|
|
492
|
-
await this.host.message(runId, review);
|
|
493
|
-
}
|
|
494
|
-
catch (error) {
|
|
495
|
-
return this.fail(h, row, `the review was not sent: ${words(error)}`, loop);
|
|
496
|
-
}
|
|
497
|
-
row = await this.move(h.id, row, "reviewed", { reviewed: true });
|
|
498
|
-
}
|
|
499
|
-
// The review's turn, its new end and the look-back it makes: a row is done only once that turn completed and its run
|
|
500
|
-
// learned from the reference.
|
|
501
|
-
const after = row.review_after ?? null;
|
|
502
|
-
const back = await this.wait(runId, (s) => s.status === "input_required" || (settled(s) && s.ended_at !== after), loop);
|
|
503
|
-
if (back === "stop")
|
|
504
|
-
return h;
|
|
505
|
-
if (back === "timeout")
|
|
506
|
-
return this.fail(h, row, "the review's turn did not end in time", loop);
|
|
507
|
-
if (back.status === "input_required")
|
|
508
|
-
return this.fail(h, row, "the run waits on a person after its review: a batch's runs ask no one", loop);
|
|
509
|
-
if (back.status !== "completed")
|
|
510
|
-
return this.fail(h, row, `the review's turn ${back.status === "cancelled" ? "was cancelled" : "failed"}${back.error ? `: ${back.error}` : ""}`, loop);
|
|
511
|
-
// Closed, and its cost saved, only once its all-in is known (its audit's shadow run ended): the next row's room reads it.
|
|
512
|
-
const f = await this.allIn(runId, loop, true, this.host.rowTimeoutMs ?? 30 * 60_000);
|
|
513
|
-
if (f === "stop")
|
|
514
|
-
return h;
|
|
515
|
-
if (f === "timeout")
|
|
516
|
-
return this.fail(h, row, "its audit's shadow run did not end in time", loop);
|
|
517
|
-
await this.move(h.id, row, "done", f ? { cost_usd: f.cost_usd, learning_usd: f.learning_usd, total_usd: f.total_usd, learned: f.learned, merged: f.merged, revisions: f.revisions } : {});
|
|
518
|
-
return this.tally(h);
|
|
519
|
-
}
|
|
520
|
-
/** The run's figures once its all-in is known (Figures.unsettled: its audit's shadow run still queued or running, whose
|
|
521
|
-
* cost is never read as $0), read again until then: "stop" on a halt (and a cancel, when `cancels`), "timeout" past
|
|
522
|
-
* `ms`. */
|
|
523
|
-
async allIn(runId, loop, cancels, ms) {
|
|
524
|
-
const started = this.clock();
|
|
525
|
-
for (;;) {
|
|
526
|
-
if (loop.halted || (cancels && loop.cancelled))
|
|
527
|
-
return "stop";
|
|
528
|
-
const f = await this.host.figures(runId);
|
|
529
|
-
if (!f?.unsettled)
|
|
530
|
-
return f;
|
|
531
|
-
if (this.clock() - started > ms)
|
|
532
|
-
return "timeout";
|
|
533
|
-
await sleep(this.pollMs);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
/** A row ends failed: a live row's run is asked to stop (nothing to one that ended; a stop that fails is the loop's
|
|
537
|
-
* failure, so the row stays live and owned) and waited for, with its grade, before its figures are read; one that does not
|
|
538
|
-
* stop within settleMs leaves the row's cost unknown. A halt meanwhile leaves the row as it is, for the next start. */
|
|
539
|
-
async fail(h, row, error, loop) {
|
|
540
|
-
const runId = row.run_id;
|
|
541
|
-
let known = true;
|
|
542
|
-
const started = this.clock();
|
|
543
|
-
const settleMs = this.host.settleMs ?? 10 * 60_000;
|
|
544
|
-
if (runId) {
|
|
545
|
-
const now = await this.host.view(runId).catch(() => undefined);
|
|
546
|
-
if (!now || !settled(now))
|
|
547
|
-
await this.host.cancel(runId);
|
|
548
|
-
for (let s = now; !(s && settled(s));) {
|
|
549
|
-
if (loop.halted)
|
|
550
|
-
return h;
|
|
551
|
-
if (this.clock() - started > settleMs) {
|
|
552
|
-
known = false;
|
|
553
|
-
break;
|
|
554
|
-
}
|
|
555
|
-
await sleep(this.pollMs);
|
|
556
|
-
s = await this.host.view(runId).catch(() => undefined);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
// And its audit's shadow run, within the same time: an all-in not known by then is booked unknown, never short.
|
|
560
|
-
const all = runId && known ? await this.allIn(runId, loop, false, Math.max(0, settleMs - (this.clock() - started))).catch(() => undefined) : undefined;
|
|
561
|
-
if (all === "stop")
|
|
562
|
-
return h;
|
|
563
|
-
const f = all === "timeout" ? undefined : all;
|
|
564
|
-
await this.move(h.id, row, "failed", { error: error.slice(0, 400), total_usd: runId ? (f?.total_usd ?? null) : 0, ...(f ? { path: row.path ?? f.path, cost_usd: f.cost_usd, learning_usd: f.learning_usd, learned: f.learned, merged: f.merged, revisions: f.revisions } : {}) });
|
|
565
|
-
return this.tally(h);
|
|
566
|
-
}
|
|
567
|
-
/** The header's figures folded from its rows as saved, then saved: counts, $, paths, lessons and the merges that touched
|
|
568
|
-
* workflows, each row once. Never added to, so a stop between a row's write and this one loses nothing. */
|
|
569
|
-
async tally(h) {
|
|
570
|
-
const next = { ...h, finished: 0, right: 0, wrong: 0, failed: 0, spent_usd: 0, unknown_cost_rows: 0, paths: { agent: 0, handed_back: 0, workflow: 0 }, lessons: { notes: [], skills: [], workflows: [] }, revisions: [] };
|
|
571
|
-
let spent = 0;
|
|
572
|
-
for (let n = 1; n <= h.total; n++) {
|
|
573
|
-
const row = await this.row(h.id, n);
|
|
574
|
-
if (row.state !== "done" && row.state !== "failed")
|
|
575
|
-
continue;
|
|
576
|
-
next.finished++;
|
|
577
|
-
if (row.state === "failed")
|
|
578
|
-
next.failed++;
|
|
579
|
-
else if (row.right)
|
|
580
|
-
next.right++;
|
|
581
|
-
else if (row.right === false)
|
|
582
|
-
next.wrong++;
|
|
583
|
-
if (row.run_id && (row.total_usd === null || row.total_usd === undefined))
|
|
584
|
-
next.unknown_cost_rows++;
|
|
585
|
-
spent += row.total_usd ?? 0;
|
|
586
|
-
if (row.path && row.path !== "replay" && row.path !== "audit")
|
|
587
|
-
next.paths[row.path]++;
|
|
588
|
-
for (const kind of ["notes", "skills", "workflows"])
|
|
589
|
-
for (const name of row.learned?.[kind] ?? [])
|
|
590
|
-
if (!next.lessons[kind].includes(name))
|
|
591
|
-
next.lessons[kind].push(name);
|
|
592
|
-
for (const r of row.revisions ?? [])
|
|
593
|
-
next.revisions.push({ row: row.n, commit: r.commit, workflows: r.workflows });
|
|
594
|
-
}
|
|
595
|
-
next.spent_usd = usd(spent);
|
|
596
|
-
if (h.status === "running")
|
|
597
|
-
await this.save(next);
|
|
598
|
-
return next;
|
|
599
|
-
}
|
|
600
|
-
}
|
package/dist/learning-evals.d.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import type { Store } from "./store/store.js";
|
|
2
|
-
/** How many records an agent keeps, newest first. */
|
|
3
|
-
export declare const EVALS_KEPT = 20;
|
|
4
|
-
/** The most jobs one test may count. */
|
|
5
|
-
export declare const EVAL_JOBS_MAX = 10000000;
|
|
6
|
-
/** The longest `name` and `label_source`. */
|
|
7
|
-
export declare const EVAL_TEXT_MAX = 200;
|
|
8
|
-
/** One record: what was posted (`name`, `label_source`, the counts, each side's cost a task, the learned revision), the
|
|
9
|
-
* server's `accuracy` (correct / n) and `ci` (its 95% Wilson interval), each to four places, and when it was recorded. */
|
|
10
|
-
export type LearningEval = {
|
|
11
|
-
id: string;
|
|
12
|
-
name: string;
|
|
13
|
-
label_source: string | null;
|
|
14
|
-
n: number;
|
|
15
|
-
correct: number;
|
|
16
|
-
accuracy: number;
|
|
17
|
-
ci: [number, number];
|
|
18
|
-
cost_per_task_usd: number | null;
|
|
19
|
-
baseline_cost_per_task_usd: number | null;
|
|
20
|
-
learned_revision: string | null;
|
|
21
|
-
recorded_at: string;
|
|
22
|
-
};
|
|
23
|
-
/** The 95% Wilson score interval of `correct` right of `n`, [low, high], each from 0 to 1, to four places: unlike the
|
|
24
|
-
* normal approximation it holds at 0 and at n right and with few jobs. */
|
|
25
|
-
export declare function wilsonOf(n: number, correct: number): [number, number];
|
|
26
|
-
/** A posted record, checked for its shape only: each field that is missing or wrong is 422 input_invalid by field, and
|
|
27
|
-
* nothing is kept. */
|
|
28
|
-
export declare function evalOf(body: unknown, now: Date): LearningEval;
|
|
29
|
-
/** Where agent `agentId`'s eval records are kept (a setting of the store). */
|
|
30
|
-
export declare const evalsKey: (agentId: string) => string;
|
|
31
|
-
/** Agent `agentId`'s records, newest recorded first. */
|
|
32
|
-
export declare function evalsOf(store: Store, agentId: string): Promise<LearningEval[]>;
|
|
33
|
-
/** Appends `record` first in agent `agentId`'s records, the latest EVALS_KEPT kept: a compare-and-set, so of two posts at
|
|
34
|
-
* once neither is lost. */
|
|
35
|
-
export declare function recordEval(store: Store, agentId: string, record: LearningEval): Promise<void>;
|