Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca7388743b | ||
|
|
59af86a5ee | ||
|
|
d6d3271808 | ||
|
|
4a7815d29e | ||
|
|
af8c2f9777 | ||
|
|
b156727c00 | ||
|
|
29daa4c4bf | ||
|
|
c8db3665cf | ||
|
|
f2c262cf40 | ||
|
|
ebfbdb13a0 | ||
|
|
4d378fc38b | ||
|
|
ab8633ede8 | ||
|
|
6ad11e6993 | ||
|
|
e52a6b714f | ||
|
|
2d065b936e | ||
|
|
098b3771c0 | ||
|
|
eac42663ba | ||
|
|
b41bc00b26 | ||
|
|
749d6d98f5 | ||
|
|
fa5ce3ae65 | ||
|
|
d009ccaec4 | ||
|
|
2613fb1c4c | ||
|
|
df26085303 | ||
|
|
7c1b87d154 | ||
|
|
8908df113e | ||
|
|
b8354e4304 | ||
|
|
f62b1b9518 | ||
|
|
7355b233a8 | ||
|
|
88d08c8437 | ||
|
|
4377941bd4 | ||
|
|
de39750ebb | ||
|
|
3b17326b74 | ||
|
|
d03ae494e8 | ||
|
|
e1b56d9ea7 | ||
|
|
e6f6f5445b | ||
|
|
55f9652f6a | ||
|
|
9e434c0e9c | ||
|
|
e732ae7450 | ||
|
|
66255c9bf2 | ||
|
|
cecc901854 | ||
|
|
81ca8399a2 | ||
|
|
37c3854849 | ||
|
|
db2dc96aa2 | ||
|
|
f666590d54 | ||
|
|
2f20346719 | ||
|
|
524132b42b | ||
|
|
ae53b1988a | ||
|
|
940ac53b65 | ||
|
|
799df9cb9f | ||
|
|
23964b1224 | ||
|
|
d692ca9b81 | ||
|
|
57e86d9867 | ||
|
|
d502a75e57 | ||
|
|
15801ccb07 | ||
|
|
50ca7f0341 | ||
|
|
b9b3e56821 | ||
|
|
32b56b8351 | ||
|
|
78d1ef7705 | ||
|
|
af1bbf7859 | ||
|
|
a7362a8fc5 | ||
|
|
5a07f9e1f9 | ||
|
|
07eca4a670 | ||
|
|
fc9e4dfca8 | ||
|
|
10a35ce65a | ||
|
|
3b9cac5452 | ||
|
|
bc6d3565b0 | ||
|
|
72ea7272ec | ||
|
|
27a359590e | ||
|
|
6c5ec23b47 | ||
|
|
dd0a8612c8 | ||
|
|
9276277970 | ||
|
|
517a3fe467 | ||
|
|
149712816b | ||
|
|
4f63176676 | ||
|
|
1e0aba8b37 | ||
|
|
680bb90af3 | ||
|
|
6a24cf743d | ||
|
|
06ee172a9d | ||
|
|
66676804eb | ||
|
|
a3ad6578c4 | ||
|
|
77a951cfe7 | ||
|
|
cd58ac23cd | ||
|
|
fbaae25d06 | ||
|
|
c9d64a341e | ||
|
|
4cbf3f07b0 | ||
|
|
48a2ed675c | ||
|
|
e70b6bd684 | ||
|
|
2db4f24fd8 | ||
|
|
9bfe101176 | ||
|
|
869d259036 | ||
|
|
8200ea238c | ||
|
|
196505e6ef | ||
|
|
f7c0e4f46c | ||
|
|
5c975faddd | ||
|
|
462215b4bd | ||
|
|
d0293d6602 | ||
|
|
912138ff61 | ||
|
|
4a8d310cd5 | ||
|
|
c28ca57af6 | ||
|
|
255c1575bb | ||
|
|
0ba50111f6 | ||
|
|
dab07f0ff5 | ||
|
|
561ff77e48 | ||
|
|
e1642be760 | ||
|
|
b23ccdfc12 | ||
|
|
57af33630d | ||
|
|
17b972b92d | ||
|
|
d531d7181d | ||
|
|
67e1ff193d | ||
|
|
9a3004cba4 | ||
|
|
4b833d23e9 | ||
|
|
05be6c62bd | ||
|
|
c9fad00d25 | ||
|
|
4c8527fcd3 | ||
|
|
2d44750b96 | ||
|
|
9343baffff | ||
|
|
38ea639d70 | ||
|
|
fc558df31a | ||
|
|
56cc7b59dd | ||
|
|
c641dbfbc9 | ||
|
|
eb1146ebad | ||
|
|
4b5d027361 | ||
|
|
80ce06851d | ||
|
|
b39d5e2ff3 | ||
|
|
c85c768a4a | ||
|
|
b7649ecd73 | ||
|
|
0354452971 | ||
|
|
bbbefb3f28 | ||
|
|
2f91ff5bea | ||
|
|
1ca3a38f86 | ||
|
|
cb80b2b8a8 | ||
|
|
fd300b4fe3 | ||
|
|
a88302d6eb | ||
|
|
820f45e474 | ||
|
|
2e9a2068bd | ||
|
|
fe6c22e0f2 | ||
|
|
9eed814d3c | ||
|
|
7ee606cda2 | ||
|
|
b2d52b57c1 | ||
|
|
cbf1836bd7 | ||
|
|
6fe3625fae | ||
|
|
24551c9eea | ||
|
|
cad9cd057f | ||
|
|
4f24501801 | ||
|
|
02e053866a | ||
|
|
ff096afa27 | ||
|
|
70af20e29d | ||
|
|
d92cdefc1d | ||
|
|
9994f89790 | ||
|
|
4a9c7a931c | ||
|
|
5c7194e05b | ||
|
|
f0bf85befe | ||
|
|
c26879637a | ||
|
|
2fc97a3edb | ||
|
|
68df55130e | ||
|
|
6ad1d33dd1 | ||
|
|
5fba4726dc | ||
|
|
69ce460f91 | ||
|
|
307f88be3e | ||
|
|
bfd3ed6811 | ||
|
|
5b6b39f080 | ||
|
|
2d7d7be5ca | ||
|
|
f73c761ad3 | ||
|
|
8b4a26dd2b | ||
|
|
11d2b43b3a | ||
|
|
8aefc0f7a9 | ||
|
|
9cff3255e6 | ||
|
|
d50d79cddd | ||
|
|
fb3bd16052 | ||
|
|
13615e12b9 | ||
|
|
bd29e756a5 | ||
|
|
6bd9be78ac | ||
|
|
3a84f46b6e | ||
|
|
208439814a | ||
|
|
7c6571768f | ||
|
|
3597e0daf6 | ||
|
|
3116f43e65 | ||
|
|
c66f1ec00c | ||
|
|
9400e0d94d | ||
|
|
a9912983e6 | ||
|
|
626321608f | ||
|
|
5f965cdb30 | ||
|
|
8296d33100 | ||
|
|
69ac78b97e | ||
|
|
a2a7df73df | ||
|
|
789e2bcdd4 | ||
|
|
02df2a3a25 | ||
|
|
b982404963 | ||
|
|
5dd940165d |
No files matched your search
@@ -6347,3 +6347,9 @@ R5 quote fallback room (#797 D3, 2026-11-06, MVP3 lead): r4 review P2 found that
|
||||
2026-11-09 UTC, PRD 1.20 and defect l (#1873, #1886; PRs #1887 03fe321b1 and #1888 7a97cfc4f). PRD 1.20: Jason approved draft 2 at 22:57Z ("The file looks fine other than that"; the Montage module name stays deferred). The PRD now has 118 requirements, with REQ-WS-1..8, REQ-AGENT-1..3, REQ-SYS-1..2, REQ-ACCT-1..2 and REQ-SETUP-1..2 added and REQ-ASSIST-1, REQ-USER-1, REQ-TASK-1 and REQ-WEB-3 amended. Builder Codex Terra xhigh declined to commit because stack-copy failed 20/1 (node-gyp missing from the test Node's npm); that failure is pre-existing on 483eccb3d, so the lead committed. Sol review APPROVE 0 (word-for-word diff against draft 2, catalog order, both requirements tests). Defect l: before, an agent that declared a store credential made the next bus start refuse, because Credentials refuses a missing store root and only issue() created it. After: start creates the root 0700 when any reference names the store; a root that exists with loose modes or as a symlink still refuses. Two new credential-verbs tests fail on the parent. Bus suite 171 files one at a time, 1713/0 (Node 26.12.1, env -i). Sol review APPROVE 0. uiorg redeployed at 7a97cfc4f, 23:15Z. Follow-up: the stack-copy node-gyp test environment. Reports: /mnt/storage/scratch/mosaic-lead/reports/{prd120-land,prd120-review,defectl-review}.md.
|
||||
|
||||
2026-11-10 UTC, unified workspace U1 and SYS1 (#1873; PRs #1889 d35447005 and #1890 2c6556ab1). U1, before: each org page read only its own bus and nothing read every org at once. After: /api/workspace returns projects, sessions, inbox, tasks and metrics from every org the owner holds, each row tagged with its org and each org with a state (ok, starting, down, timeout, invalid); `mosaic console restart` and `mosaic org reload <org>` send the F3 routes. Sol review CHANGES 0/2 on 2109458b3: malformed data from one org turned the whole read into a 503, and the per-org deadline left sockets and transport children running. Terra fix 0672d5fe8 validates each org's result inside its boundary and carries an absolute deadline and AbortSignal through the status check and transport; the new workspace-failures test is 0/10 on the parent and 10/0 on the fix. The lead re-pinned the webui bus.mjs hash in bus channel-proof (the deliberate signal/deadline change; nonces, argv and limits unchanged) and amended as d35447005. SYS1, before: no system-type kind. After: a system-type plug-in kind with five modules (business-management, coding, creative-writing, marketing, montage), an org enable list under plugins.system-type, owner-only project selection with an append-only project_system_types table (migration 3t-3u) and CLI verbs; the modules grant no tools yet (REQ-SYS-2 deferred). Sol review CHANGES 1/2 on a9629f332: the restore guard did not count project_system_types, the CLI channel did not admit the two project verbs, and the #811 migration-reader pin still expected 18 steps. Lead fix 2c6556ab1 (rebased on d35447005) adds the table to COUNTED and LISTED with refusal and in-run recount tests, admits both verbs with a run()-level channel test (red on the unfixed channel), and moves the pin to 19 steps ending 3t-3u; fix files 323/0 and rebase overlap files 63/0 (Node 26.12.1, one file at a time, env -i). Full gate on a9629f332 4040/5: the two stack-release pins above, and tester-reads 3/3, which also fails on 1616d1dd6 (project.mjs:95 refuses an org --tester init; follow-up). Correction to the uiorg deploy at 00:50Z: the deploy script switched the tree without the offline schema migration, so all five buses refused to start (normal startup refuses an older schema by design). The lead ran migrate-schema.mjs for the five org stores (3t to 3u, all ready), restarted the buses (201 each) and added the migration to the deploy script with stop-on-refusal. test3 refused writer-locked and stays down, as before. Reports: /mnt/storage/scratch/mosaic-lead/reports/{u1-review,u1-fix,org-sys1-build,sys1-review}.md.
|
||||
|
||||
2026-11-13 UTC, starter packs replace system types (#1873; PRs #1949 c0a60ed3a, #1950 1e65ff3f8, #1951 755ba3fa8, #1952 1ced0e392, #1953 dfef78834, #1955 9a649abf8, #1956 991eb8c33, #1957 34dd33101, #1959 0251acdad and #1960 e6ab8bc1f; final e6ab8bc1f). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git; the Lead wrote no entry at the time. Before: SYS1 (PR #1890, 2c6556ab1) made system types a plug-in kind with five modules, an org enable list under plugins.system-type and an append-only project_system_types table (migration 3t-3u); the modules granted no tools. After: the design docs/plans/2026-11-12_starter-packs-design.md landed as PR #1949 (doc only) after three fix rounds; Jason's FULL SEND at 21:06Z on 11-12 answered Q1 to Q3: system-type removed outright with no legacy, SP10 dropped, SP9 deletes the kind and drops project_system_types. Slices in landing order: SP3 the org keys packs, board and workflows and the applyPack writer op; SP1 the starter-pack plug-in kind and its checker; SP7 workflow guidance in the harness prompt; SP2 the five shipped packs; SP4 pack, board and workflow verbs, routes and CLI words; SP6 board labels, pack picker and workflow editor on the WebUI organization page; SP5 the chief applies a pack's non-definition half and raises hires from its proposals; SP8 the owner saves an organization's shape as a template; SP9 system types removed outright and bus schema 3v-3w dropping project_system_types. Test counts, Lead check then lane gate: SP3 98 files 1294/0, 1828/1; SP1 51 files 708/0, 2854/1; SP7 1281/0, 2537/1; SP2 150/0, 1556/1 at 18add86cb before its rebase onto SP7; SP4 4848/2, 6049/1; SP6 371 files 4233/1, 8262/23; SP5 229 files 2721/0, 8061/2; SP8 415 files 4650/1, 8125/2; SP9 497 files 5542/1, 8655/28. Each single Lead check red is CHAT-01 (host Python lacks jsonschema), red on base too; SP4's second red was the fixture federation-host.mjs wrongly in the run list, and Lead check lists are filtered to *.test.mjs since. The lane gate reds the log names are base or environment reds: CHAT-01, 19 agents/*/work probes, budget-supervisor 3v, ui-browser SSO, six v1 .woodpecker files and one claude-session timing test. Every slice was deployed to uiorg 7350 and verified; at e6ab8bc1f (03:46Z on 11-13) the offline 3v-3w migration ran on all five live stores, 5 stop 200, 5 bus schema 3w ready, 5 setup 201, the system-types route and its js returned 404, and no org file named system-type, so no wipe was needed. Corrections: the Lead's 21:38Z carry that SP2 pack steps must drop id was reversed at 21:46Z: pack steps keep id (SP1 checker) and SP4 drops id when it copies a step into the org file. The Lead's SP7 brief misstated the workflow shape; the lane built to the SP3 loader, which was correct. SP5's last commit before landing changed the broker canonical string builder after its re-check with no suite test; the Lead compared it with organization canonicalJson (7/7 same) and accepted it, and the integer-key pin test is deferred. SP9's first gate, before its rebase, ran packages/cli/live/ui-browser.test.mjs, which binds its own fixture on 17443, a lane rule breach; nothing was listening before or after, and the file was left out of later gates. The 'bus recover' deploy step refuses rc=3 in the agent shell on every deploy since D1; it is harmless while bus stop succeeds. Reports: /mnt/storage/scratch/mosaic-lead/reports/{starter-pack-design-build,starter-pack-design-recheck2,sp1-build-1112-starter-packs,sp2-build-1112-starter-packs,sp3-build-1112-starter-packs,sp4-build,sp5-build,sp6-build,sp7-build,sp8-build,sp9-build,sp9-rebase-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, applying a starter pack is the hire decision, with the route fallback (#1873; PR #1963, b913f0f4c; commits 359b3299b and 3e53af394 lane pd, bfd2cc5e7 and b913f0f4c lane pr2). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: section 3 of the starter packs design said apply never hires; a person's apply left the pack's hires as proposals for the chief to raise or for a person with org.hire to start. On 7350 at 65f7288ce Jason applied packs and saw no agents. His ruling at 20:48Z on 11-14, verbatim: "Damnit. If I choose a starter pack and apply it, that is a decision!" After, lane pd: a person's apply (pack.apply.console from the WebUI, pack.apply from the CLI) raises one hire decision per proposal after the pack's commit and resolves it, with the evidence an inbox approval leaves. The owner's apply approves flagged and credential lines; a member with org.hire hires only proposals with neither, and the rest wait for the owner as awaiting-owner. An agent apply hires nothing. Hires are written with no credential material, so services show unbound until someone binds them. The design's section 3 carries a 2026-11-14 change note. Route fallback: at 22:03Z the Lead found every 7350 chief had model null, so pack hires would refuse pack-hire-route-missing on Jason's orgs. Ruling at 22:13Z: the hire route is the chief's, else the org assistant's harness and model, else refuse; lane pr2 stacked on pd. Tests: pd gate 3957/0 at its first commit, review changes 6 (2 P2) fixed or deferred, re-check APPROVE; Lead check of pd with pr2 333 files 3813/1, the red a control-board scan.test mtime-tie flake in a file neither lane touched, 70/0 three times alone. Lead ruling on the re-check's P2 1: a member pack hire surface is a follow-up row, because a new transport for a member hire cap is a security boundary and the owner path covers apply; Jason said "proceed". Deployed b913f0f4c at 01:03Z on 11-15: stop 5, schema 3w 5, setup 5. The Lead ran pack hire on faceless (montage ideas-1 and research-1, coding pm-1, coder-1 and reviewer-1, all on fixture-deterministic) and acme (business-management pm-1 and research-1 on opus), each with routeFrom assistant. Related fix the same night: Jason reported "adapter exited 127" in Messages. Lane r127 found the Lead's deploy-uiorg.sh (a scratch script, not in the repository) started the Console without MOSAIC_CLAUDE_BIN, so claude-code sessions ran the /usr/bin/claude wrapper whose target under /opt the sandbox does not bind. The Lead patched the script and landed PR #1964 387f73a7a, which makes exit 127 name the missing program; Lead check 16 files 285/0. Both assistant kinds replied on 7350 at 387f73a7a by 03:33Z. Reports: /mnt/storage/scratch/mosaic-lead/reports/{pd-build,pd-review,pd-recheck,pr2-build,pr2-review,r127-build,r127-review,r127-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, single pane slices sp1 to sp14 (#1873; PRs #1965 to #1978; final c26879637). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: a Side by side page sat in the sidebar beside the organization pages, and Jason's walkthrough on 65f7288ce (20:48Z on 11-14) found agents from an applied pack not visible. His direction: #/dashboard system-wide, no organization URL base, side-by-side Assistant threads in place of Side by side, and the 3-click rule. The Lead ruled at 03:33Z on 11-15 that #/orgs/<id>/... stays the address of an org page but is a route inside one global shell, with no reload and no mode switch. After, slice by slice (PR, tip, Lead check, lane gate): sp1 shell, #/dashboard system page, org drill-in without reload, a down org says so (#1965, c7aecbffa, 128/0, 1031/0, two reviews, nine findings fixed); sp2 dashboard polish, bare org route, theme, one down banner (#1966, d1b01329b, 132/0); sp3 system Inbox (#1967, 3885f4628, 111/0, 892/0; a theme fix and a render-order fix were read by the Lead, not a reviewer); sp5 system Agents, landed before sp4 (#1968, f97e0d3ae, 89/0 plus unified-workspace 18/0, 745/0); sp4 system Tasks, which the Lead rebased onto f97e0d3ae with three one-line union conflicts (#1969, ed4f45ed2, 131/0, 937/0 before the rebase); sp6 system Assistant with up to three threads from any org side by side, the open set in the hash, Side by side removed from the sidebar and #/side-by-side landing on Assistant (#1970, 789e2bcdd, 95/0, 1472/0, four review rounds); sp7 seven small fixes (#1971, a9912983e, 141/0, 1483/0, three review rounds); sp8 KPI tiles from real reads only and the 3-clicks table (#1972, c66f1ec00, 119/0 plus org-live-edit-browser 4/0 alone, 1490/2 with two load flakes that each passed alone twice, three small fixes not re-reviewed); sp9 read-only workflow list and graph per org (#1973, 7c6571768, 143/0, 1504/0); sp10 workflow edit in the graph (#1974, bd29e756a, 146/0, 1515/0); sp11 eight fixes including agent counts that disagreed and Done this week (#1975, 5b6b39f08, 164/0, 1527/0, three review rounds); sp12 agent drawer from #/agents and org session rows (#1976, 69ce460f9, 196/0, 191 files 1538/0); sp13 organization page fits its width, #/orgs/<id>?query parses, drawer state pending until the instances read answers (#1977, 68df55130, 205/0, 192 files 1547/0); sp14 Queue card off the organization page, running not read where an answer carries no runs, kept Assistant pane messages keyed by an opaque viewer, drawer repaint without new page reads (#1978, commits 2fc97a3ed and c26879637, 218/0, 192 files 1549/0, review changes 1 with the P2 fixed, re-check approve). sp14 adds `viewer` to /api/config (32 hex of sha256 over provider, iss and sub; `local` without sign-in) and adds no route. The Lead ruled at landing of sp13 that the Queue card leaves the organization page; #/queue stays. State at c26879637: system pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant; org pages at #/orgs/<id>/... inside the same shell. Each slice was deployed to uiorg 7350 with five buses up (deploy log per tip under reports/deploy-<sha>.log); sp1 and sp8 to sp14 record 5 stop, 5 schema 3w and 5 setup. An acme assistant reply was checked live after sp1 and sp6 to sp14; after sp4, #/agents showed the acme assistant running mid-reply; the log records no reply check for sp2, sp3 and sp5. Corrections: sp15 was launched at 19:23Z on a wrong premise. The Lead had told Jason, from reading code only, that the broker's async instances path was the real cause of the sp12 drawer saying not running. The lane stopped at BASE with no diff: the shipped runtime answers instances synchronously (runtime.mjs:1263), and a probe on a real startBroker showed the running and alive arrays present. The sp12 live shot had a 9000 ms screenshot budget that caught the paint before the read; the sp13 shot at 30000 ms shows State running. sp15 closed at 19:26Z with no change and no bus row; sp14's running not read item now only guards a failed or odd read. The Lead's lesson: prove a fault live before naming it a cause. The sp14 live shots read 0 running because they were taken right after the bus restart, before any session started. Follow-ups after sp14: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, and the Dashboard org table scrolling sideways at 390. Reports: /mnt/storage/scratch/mosaic-lead/reports/{sp1-build,sp2-build,sp3-build,sp4tasks-build,sp5agents-build,sp6threads-build,sp7polish-build,sp8kpis-build,sp9workflows-build,sp10workflowedit-build,sp11fixes-build,sp12agentdrawer-build,sp13orgpagefit-build,sp14orgpagetruth-build,sp15businstancesruns-build}.md.
|
||||
@@ -106,6 +106,23 @@ keeps its existing channel; the CLI does not inherit the completion pipe. No ext
|
||||
writable mount or completion file is needed. Pi retains print mode and signals
|
||||
activity through its existing extension. Mock remains a test-only echo.
|
||||
|
||||
### A worker's skills (M17, #1873)
|
||||
|
||||
`MOSAIC_SKILLS` is a comma list of skill directories. Today only the
|
||||
interactive container launch (`scripts/agent.sh`) sets it; task launches
|
||||
refuse skill directories and set it empty
|
||||
(`packages/processing-control/src/containers.mjs`). The pi adapter passes `--no-skills` and then
|
||||
`--skill <dir>` for each one. On pi 0.85.1 `--skill` adds to discovery and
|
||||
does not replace it. With `--skill` alone, a probe with a scratch HOME also
|
||||
loaded the user's skills, the skills a `settings.json` or a listed package
|
||||
names, and `~/.agents/skills` (and the project's, without `--no-approve`).
|
||||
With `--no-skills` first, only the given directories load. A directory that
|
||||
doesn't exist stops the adapter with exit 2. The fit check runs the
|
||||
headless form of this argv, with two skill directories, one `-e` file, no
|
||||
tools and no session, as its last `-p` run (`workerShape`,
|
||||
`packages/harness/README.md`); the TUI shape the launch uses is not run. The fit check runs
|
||||
before bus sessions only; worker containers run the pi pinned in the image.
|
||||
|
||||
### A role's skills (row 64)
|
||||
|
||||
A managed session's skills reach both adapters as text in the bundle's
|
||||
|
||||
+21
-8
@@ -1,6 +1,6 @@
|
||||
#!/bin/sh
|
||||
# Pi adapter: implements the Mosaic adapter contract for the pinned
|
||||
# @earendil-works/pi-coding-agent CLI.
|
||||
# Pi adapter: implements the Mosaic adapter contract for the
|
||||
# @earendil-works/pi-coding-agent CLI. Its behaviour notes are read from 0.85.1.
|
||||
#
|
||||
# Contract: see /opt/mosaic/adapters/README.md.
|
||||
# Headless (default): stdout = response only; stderr = diagnostics; exit 0.
|
||||
@@ -57,14 +57,18 @@ fi
|
||||
TOOLS_FLAG="--no-tools"
|
||||
[ -n "${MOSAIC_TOOLS:-}" ] && TOOLS_FLAG="--tools $MOSAIC_TOOLS"
|
||||
|
||||
# Skills (M17): explicitly provided skill dirs replace discovery. When none
|
||||
# are provided the agent runs with --no-skills (nothing ambient to find).
|
||||
# Skills (M17, #1873 pi-skills): --no-skills always, then one --skill per
|
||||
# given dir. On pi 0.85.1 --skill adds to discovery and does not replace it:
|
||||
# with --skill alone pi also loads the user's skills, settings and package
|
||||
# skills and ~/.agents/skills (a planted-skill probe showed it, offline, with a
|
||||
# scratch HOME). With --no-skills first only the given dirs load. The fit check
|
||||
# (packages/harness/src/pi-fit.mjs) runs its -p form as its last run (workerShape).
|
||||
# Only the interactive launch (scripts/agent.sh) sets MOSAIC_SKILLS today.
|
||||
# Role sessions never get MOSAIC_SKILLS (ENV_ALLOW in packages/seat/src/
|
||||
# session.mjs leaves it out), so they run with --no-skills; their skills
|
||||
# session.mjs leaves it out), so they run with --no-skills alone; their skills
|
||||
# are text in the system prompt (row 64).
|
||||
SKILLS_FLAG="--no-skills"
|
||||
if [ -n "${MOSAIC_SKILLS:-}" ]; then
|
||||
SKILLS_FLAG=""
|
||||
OLDIFS=$IFS; IFS=','
|
||||
for s in $MOSAIC_SKILLS; do
|
||||
[ -d "$s" ] || { echo "pi adapter: skill dir missing: $s" >&2; exit 2; }
|
||||
@@ -92,6 +96,11 @@ fi
|
||||
THINKING_FLAG=""
|
||||
[ -n "${MOSAIC_THINKING:-}" ] && THINKING_FLAG="--thinking $MOSAIC_THINKING"
|
||||
|
||||
# MCP (#1873 S3): the harness module sets MOSAIC_PI_NO_MCP=1 when the binary's --help lists
|
||||
# --no-mcp, so MCP stays off by its own flag and not only as a side effect of --no-extensions.
|
||||
NO_MCP_FLAG=""
|
||||
[ "${MOSAIC_PI_NO_MCP:-}" = "1" ] && NO_MCP_FLAG="--no-mcp"
|
||||
|
||||
# Mode (M13): interactive TUI or one-shot print.
|
||||
PRINT_MODE="-p"
|
||||
REQUEST_ARG=""
|
||||
@@ -107,6 +116,8 @@ fi
|
||||
# --system-prompt replace the default prompt with the generated one, given
|
||||
# as the file's absolute path (checked above), never its text
|
||||
# --no-* no ambient context/skills/extensions/templates/themes
|
||||
# SKILLS_FLAG --no-skills, then --skill <dir> for each MOSAIC_SKILLS dir
|
||||
# NO_MCP_FLAG --no-mcp when the binary lists it, else nothing
|
||||
# EXT_FLAGS the explicitly provided extensions only (-e)
|
||||
# SESSION_FLAGS ephemeral | persistent | forked (per env)
|
||||
# TOOLS_FLAG per capabilities
|
||||
@@ -118,6 +129,7 @@ set -- \
|
||||
--offline \
|
||||
--no-approve \
|
||||
--no-extensions \
|
||||
$NO_MCP_FLAG \
|
||||
$EXT_FLAGS \
|
||||
$SKILLS_FLAG \
|
||||
--no-prompt-templates \
|
||||
@@ -134,6 +146,7 @@ set -- \
|
||||
[ "$INTERACTIVE" = "1" ] || set -- "$@" -p "$MOSAIC_REQUEST"
|
||||
if [ -n "${MOSAIC_MODEL_EVENT_MONITOR:-}" ] && [ "$INTERACTIVE" != "1" ]; then
|
||||
STREAM="$(dirname "$0")/../../packages/plugins/harness/pi/model-stream.mjs"
|
||||
exec node "$STREAM" pi "$MOSAIC_FIRST_OUTPUT_DIR" pi "$@" --mode json
|
||||
exec node "$STREAM" pi "$MOSAIC_FIRST_OUTPUT_DIR" "${MOSAIC_PI_BIN:-pi}" "$@" --mode json
|
||||
fi
|
||||
exec pi "$@"
|
||||
# #1873 S2: the binary the harness module found (MOSAIC_PI_BIN, its path inside the sandbox).
|
||||
exec "${MOSAIC_PI_BIN:-pi}" "$@"
|
||||
@@ -2124,3 +2124,9 @@ are never rewritten or removed; corrections are new entries.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | Organizations F3 fix round and landing (#1873) | PR #1884 merged a8f9f0957; review P3 fixed, P1 README corrected with follow-up #1883; 195/0 focused suite; uiorg redeployed 22:45Z.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | PRD 1.20 landing and defect l (#1873, #1886) | PR #1887 merged 03fe321b1, PR #1888 merged 7a97cfc4f; both Sol reviews APPROVE 0; bus suite 1713/0; uiorg redeployed 23:15Z; U1, U2 and U4a builds dispatched.
|
||||
2026-11-10 UTC | Mos (lead, Claude Opus 5.5) | U1 and SYS1 landings (#1873) | PR #1889 merged d35447005, PR #1890 merged 2c6556ab1; both Sol reviews CHANGES, fixed (U1 by Terra, SYS1 by the lead); uiorg at 2c6556ab1 after the missed 3t-3u store migration was run; deploy script now migrates.
|
||||
2026-11-10 UTC | Sage (Lead) | redact3 landing (#1873) | PR #1912 merged 96c900d21 at 23:56Z, gate 268 files 3412/0, Opus review changes 2 fixed; uiorg deploy started. Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git.
|
||||
2026-11-11 UTC | Sage (Lead) | Organizations, redaction, accounts, dev readiness and credential binding landings (#1873) | PRs #1913 to #1944 merged, a4eed1e21 to 6d0e9f89b: A2, golden1, TI, redact4, A3, M3 with M3-recon, acct-anchor, org-names, polish2, run sheet doc, cred-bind design, PL1, base-reds, redact5, T1, timing2, cleanup-time, A4, supcost, defscan, redact6, AU, D4, D3, harness-scan, D2, D1, CB01, bus-stop, agent-guard, proxy-ui, CB2. Jason approved CB0 to CB5 at 17:55Z. Per-landing check counts are in uidev/LEAD-1110.md. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-12 UTC | Sage (Lead) | E1, E2, CB3, E3, CB4 and starter packs design, SP3, SP1, SP7, SP2, SP4 landings (#1873) | PRs #1945 8827905ba (E1), #1946 666f4d686 (E2), #1947 0b8fe202b (CB3), #1948 2ad4b30eb (E3), #1949 c0a60ed3a (design), #1950 1e65ff3f8 (SP3), #1951 755ba3fa8 (SP1), #1952 1ced0e392 (SP7), #1953 dfef78834 (SP2), #1954 95c2ce143 (CB4), #1955 9a649abf8 (SP4). Jason's FULL SEND on starter packs at 21:06Z: system types removed outright, SP10 dropped. The log first dated the E1 landing 11-11; its own correction and git put it at 02:48Z on 11-12. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-13 UTC | Sage (Lead) | Starter packs SP6, SP5, SP8, SP9 and CB5 landings; E2E round 6 started (#1873) | PRs #1956 991eb8c33 (SP6), #1957 34dd33101 (SP5), #1958 a9d72b3cd (CB5, credential binding CB0 to CB5 complete), #1959 0251acdad (SP8), #1960 e6ab8bc1f (SP9). uiorg 7350 at e6ab8bc1f: bus schema 3w on all five stores, system-types route 404. E2E R6 CLI and WebUI lanes started 23:59Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-14 UTC | Sage (Lead) | E2E round 6 fixes and the pack apply ruling (#1873) | E2E R6 CLI 0/0/7, WebUI 0/3/15. PR #1961 23b5e24eb (f6w) and PR #1962 65f7288ce (f6c) merged; uiorg verified at 65f7288ce 02:40Z. Jason's walkthrough at 20:48Z: applying a starter pack is a decision, plus the single pane direction. Route fallback ruled 22:13Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-15 UTC | Sage (Lead) | Pack decision, exit 127 fix and single pane slices sp1 to sp14 (#1873) | PR #1963 b913f0f4c (pd with pr2), PR #1964 387f73a7a (r127), PRs #1965 to #1978 (sp1 to sp14), final c26879637 at 20:19Z; each deployed to uiorg 7350. sp15 launched 19:23Z on a wrong premise (a bus instances fault that did not exist) and closed 19:26Z with no change. Backfilled 2026-11-16 by lane docs-1116.
|
||||
@@ -586,3 +586,4 @@ git history + Gitea issues.
|
||||
|
||||
- 2026-09-26 (sage, lead): Jason's ruling: Sage leads the project, Darkwing is a collaborating seat, more seats to follow, development stays in T3 for now. The fleet Sage seat that took Invoice Ninja coordination outside Jason's instructions is being decommissioned; moving work onto the new stack is the fix. Suites all green. Rows 24 and 25 pushed (1685deb4..43d7574d). Open: about 11 days of uncommitted agent work in the tree (row 16 launch files, row 22, #1512, WUI evidence), 23 untracked aws-* skill directories in skills/ from 2026-09-21, and Jason's target for the next phase.
|
||||
- 2026-10-13 (sage, lead): Jason's PM re-test on 664199f7 is finished (Mos; PM run rcc0f72be8b17; Vikunja #228). Paging, the Board's held roles, the Messages page and the #229 loop (coder push 010d30cb, review, approve, PM close) all worked; #230 and #231 are done, #232 stays open for the secrets-path probe. Two faults checked and dropped: the reviewer did run the tests before its verdict, and the PM's clone did hold the row 95 Board code. Two filed: row 104 (#1598) seat git identity, row 105 (#1599) a review request says whether a reviewer is running. Rows 96, 101-105 briefed; row 85 released to build. Row 85's live steps, any bus restart and row 102's public/ change each need Mos's go. Row 100 waits on Jason (Vikunja #257). Formatting, Jason's direction: no formatting row now. Chat output will be formatted in the TUI and WebUI the way chat interfaces usually do it, made our own; T3 Code's chat is his example. Carry it into the TUI and WebUI chat work.
|
||||
- 2026-11-15 (sage, lead; written 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git): single pane state at c26879637 (#1873, PRs #1965 to #1978). One WebUI shell. System pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant cover every organization; #/queue stays its own page. Organization pages are #/orgs/<id>/... routes inside the same shell, with no reload and no mode switch (Lead ruling 03:33Z 11-15). Side by side is gone from the sidebar; the Assistant page holds up to three threads from any organization side by side, and #/side-by-side lands there. The organization page has KPI tiles from real reads, a workflow list and graph with edit, an agent drawer (?agent=<org>:<name>), and no Queue card. Where an instances answer carries no runs the page says running was not read, never 0. /api/config names an opaque `viewer` that keys kept Assistant pane messages. Applying a starter pack is the hire decision (PR #1963 b913f0f4c). Follow-ups: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, the Dashboard org table scrolling sideways at 390. Detail: BUILD-LOG.md 2026-11-15 entries.
|
||||
+148
-4
@@ -11,7 +11,7 @@ import { initializeControl, processingStatus } from '../../processing-control/sr
|
||||
import { NAME as HARNESS_NAME } from '../../plugins/src/kinds.mjs';
|
||||
import { loadRequirements } from '../../tasks/src/requirements.mjs';
|
||||
import { MERGE, LandingRefusal, readLanding } from './landing.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
// Kept closed while S1 lands; its vocabulary is the integration authority.
|
||||
export const ACTIONS = Object.freeze([
|
||||
@@ -280,6 +280,11 @@ const canonical = (x) =>
|
||||
typeof x === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(x) &&
|
||||
Number.isFinite(Date.parse(x)) &&
|
||||
new Date(x).toISOString() === x;
|
||||
// proxy-pickup (#1873): the one plain line a bus without a proxy client gives for not-configured.
|
||||
// The runtime writes it from static text and a refusal code; only that line passes, and never
|
||||
// into refusal evidence.
|
||||
const proxyCause = error => error instanceof BusError && error.code === 'not-configured' && typeof error.reason === 'string' && error.reason.length <= 300 ? error.reason : undefined;
|
||||
|
||||
export class BusError extends Error {
|
||||
// Guidance is static policy text; never quote arguments or file bytes here.
|
||||
constructor(code, reason) {
|
||||
@@ -549,6 +554,62 @@ const INSTALLER_COMMENT = 'mosaic-installer-';
|
||||
// business ID_PATTERN, which starts with [a-z0-9], so no instance can be named this.
|
||||
const NOTICE_ROLE = '_bus';
|
||||
const NOTICE_RUN = 'bus';
|
||||
// #1873 chat-fail F2: the one plain line a refused thread start, or a run the model proxy stopped
|
||||
// for silence (proxy-stall), leaves in the conversation for each message it left unanswered
|
||||
// (failureNotice below). It is here, not in a file of its own, because the runner imports this
|
||||
// file in the session sandbox, which mounts only RUNNER_FILES (packages/seat/src/sandbox.mjs).
|
||||
//
|
||||
// The line has the form a failed turn's reply has (packages/harness/src/failure-notice.mjs), so the
|
||||
// chat renders it the same way: "The turn failed: <cause and next step>\nDetails: <code>". The
|
||||
// text is fixed per code. A refusal's own reason is never put in it: it can name paths, models
|
||||
// and accounts. Codes are the launcher's existing refusal codes and the existing proxy-stall stop
|
||||
// reason; none is added here.
|
||||
const MODEL = "the model this agent uses isn't available from the model service now. Pick another model, or check Settings > Model setup.";
|
||||
const PROXY = "the model proxy isn't ready. Check Settings > Model setup.";
|
||||
const ACCOUNT = "the agent's model account isn't signed in or set up. Sign in again, or check the account in Settings > Model setup.";
|
||||
const LIMIT = "the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.";
|
||||
const SETUP = "the agent's setup can't start now. Check the agent in Agents.";
|
||||
const OTHER = "the assistant couldn't start. Try again later, or check the agent in Agents.";
|
||||
|
||||
const LINES = new Map([
|
||||
['proxy-stall', "the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup."],
|
||||
['model-provider-unavailable', MODEL],
|
||||
['model-catalogue-unavailable', MODEL],
|
||||
['model-harness-incompatible', MODEL],
|
||||
['proxy-uncertain', PROXY],
|
||||
['no-session-credential', PROXY],
|
||||
['account-credential-missing', ACCOUNT],
|
||||
['account-credential-ambiguous', ACCOUNT],
|
||||
['account-is-credential', ACCOUNT],
|
||||
['credential-unavailable', ACCOUNT],
|
||||
['limit-reached', LIMIT],
|
||||
['limit-check-failed', LIMIT],
|
||||
['harness-off', SETUP],
|
||||
['harness-refused', SETUP],
|
||||
['harness-failed', SETUP],
|
||||
['unsupported-harness', SETUP],
|
||||
['thinking-unsupported', SETUP],
|
||||
['plugin-disabled', SETUP],
|
||||
['skill-not-enabled', SETUP],
|
||||
['skill-refused', SETUP],
|
||||
['no-role-contract', SETUP],
|
||||
['definition-holds-credential', SETUP],
|
||||
['project-archived', "this project is archived, so the assistant can't reply here."],
|
||||
]);
|
||||
|
||||
// A start that waits for a free place, a run that is still ending, a held lock, a lost race, a
|
||||
// project still being set up or an operator's pause starts by itself once that clears: no line.
|
||||
const WAITS = new Set(['capacity-full', 'instance-running', 'legacy-run-live', 'session-workspace-busy',
|
||||
'processing-generation-changed', 'proxy-lock-busy', 'project-pending', 'processing-halted']);
|
||||
|
||||
const NOTICE_CODE = /^[a-z][a-z-]{0,63}$/;
|
||||
|
||||
// The body for a code, or null when the code leaves no line.
|
||||
function failureNoticeBody(code) {
|
||||
if (typeof code !== 'string' || !NOTICE_CODE.test(code) || WAITS.has(code)) return null;
|
||||
const line = LINES.get(code) ?? (code.startsWith('proxy-') ? PROXY : OTHER);
|
||||
return `The turn failed: ${line}\nDetails: ${code === 'proxy-stall' ? 'stopped' : 'start refused'}: ${code}`;
|
||||
}
|
||||
// Row 143 (#1637, REQ-PROJ-4): a human save of this file through project.file.save sends one notice to each
|
||||
// instance of these definitions. Their answer goes to the instance of SPEC_ANSWER_TO, the chief of staff,
|
||||
// because only the user and the chief of staff may send to the assistant (REQ-ASSIST-2).
|
||||
@@ -647,6 +708,7 @@ export class Broker {
|
||||
#credentialVerbs;
|
||||
#proxyInit;
|
||||
#proxyFenceClear;
|
||||
#proxyTriageKey;
|
||||
#proxyPage;
|
||||
#project;
|
||||
#library;
|
||||
@@ -711,7 +773,7 @@ export class Broker {
|
||||
#processing;
|
||||
#taskTracker;
|
||||
// credentialStatus is the runtime's metadata-only Credentials.status(); the broker never gets use().
|
||||
constructor({ store, businesses, pluginService = null, secretCheck = () => {}, credentialStatus = () => [], organization = null, hires = null, autonomy = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyFenceClear = null, proxyPage = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, copyGrant = null, copyLaunch = null, copyRevoker = null, giteaKeys = null, access = null, accessStamp = null, compactions = null, requestLifecycle = null, requirementsHost = null, workspaceRead = null, taskTracker = null }) {
|
||||
constructor({ store, businesses, pluginService = null, secretCheck = () => {}, credentialStatus = () => [], organization = null, hires = null, autonomy = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyFenceClear = null, proxyTriageKey = null, proxyPage = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, copyGrant = null, copyLaunch = null, copyRevoker = null, giteaKeys = null, access = null, accessStamp = null, compactions = null, requestLifecycle = null, requirementsHost = null, workspaceRead = null, taskTracker = null }) {
|
||||
if (!object(businesses) || !Object.keys(businesses).length) fail('invalid-business');
|
||||
// Row 194 b15 (sage-2501): the function-argument checks come before anything reads the store.
|
||||
if (harnessOn !== null && typeof harnessOn !== 'function') throw new TypeError('harnessOn must be a function');
|
||||
@@ -741,6 +803,7 @@ export class Broker {
|
||||
this.#credentialVerbs = credentialVerbs;
|
||||
this.#proxyInit = proxyInit;
|
||||
this.#proxyFenceClear = proxyFenceClear;
|
||||
this.#proxyTriageKey = proxyTriageKey;
|
||||
this.#proxyPage = proxyPage;
|
||||
this.#hostGrant = hostGrant;
|
||||
this.#hostKeys = hostKeys;
|
||||
@@ -2001,6 +2064,61 @@ export class Broker {
|
||||
this.#launcherReleased.add(key);
|
||||
return { released: true };
|
||||
}
|
||||
// #1873 chat-fail F2: a thread start the launcher refused, or a run the model proxy stopped for
|
||||
// silence (proxy-stall), leaves the person who wrote no answer. This puts one plain line in the
|
||||
// conversation for each message from the human, a user or the tester it left unanswered, as a
|
||||
// RESULT in reply to it, the way #landMessage reports a refused landing. A message in a thread is
|
||||
// to or from the thread's instance (trigger message_threads_match), so the line is from the
|
||||
// instance, with from_run NOTICE_RUN: no run sent it, the bus did, and a failed turn's own line is
|
||||
// the instance's too. With { thread, session } the messages are the session's pending ones, for a
|
||||
// refused start; with { run } they are the ones delivered to that run and never read, for a
|
||||
// stopped run. A message the instance has already answered gets no line, so a refusal the
|
||||
// launcher meets on every tick leaves one line per message. The text is fixed per code
|
||||
// (failureNoticeBody above). Trusted launcher API, deliberately NOT a socket verb.
|
||||
failureNotice(record) {
|
||||
keys(record, ['business', 'code', 'thread', 'session', 'run'], ['business', 'code']);
|
||||
this.#business(identifier(record.business));
|
||||
if (typeof record.code !== 'string' || !NOTICE_CODE.test(record.code)) fail('invalid-request');
|
||||
const byRun = record.run !== undefined;
|
||||
if (byRun === (record.thread !== undefined || record.session !== undefined)) fail('invalid-request');
|
||||
let session = null, instance, where, param;
|
||||
if (byRun) {
|
||||
const run = this.#runs.get(record.business + ':' + identifier(record.run)) ?? fail('unknown-run');
|
||||
session = run.session ?? null;
|
||||
instance = run.role;
|
||||
where = `EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op='delivered' AND d.holder_run=?)
|
||||
AND NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op='read')`;
|
||||
param = run.run;
|
||||
} else {
|
||||
session = identifier(record.session);
|
||||
const se = this.#store.get('SELECT instance FROM sessions WHERE id=? AND thread=? AND business=?', session, identifier(record.thread), record.business) ?? fail('session-not-found');
|
||||
instance = se.instance;
|
||||
where = `NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op IN ('delivered','read'))`;
|
||||
param = null;
|
||||
}
|
||||
const body = failureNoticeBody(record.code);
|
||||
if (body === null) return { posted: 0 };
|
||||
const scope = session ? 'm.id IN (SELECT message FROM message_threads WHERE session=?)' : 'NOT EXISTS(SELECT 1 FROM message_threads mt WHERE mt.message=m.id)';
|
||||
return this.#store.transaction(() => {
|
||||
const open = this.#store.all(
|
||||
`SELECT m.id, m.from_role FROM messages m WHERE m.business=? AND m.to_role=? AND ${scope}
|
||||
AND m.from_role IN ('human','user','tester') AND ${where}
|
||||
AND NOT EXISTS(SELECT 1 FROM message_cancels x WHERE x.message=m.id)
|
||||
AND NOT EXISTS(SELECT 1 FROM messages n WHERE n.in_reply_to=m.id AND n.from_role=m.to_role)
|
||||
ORDER BY m.seq`,
|
||||
...[record.business, instance, ...(session ? [session] : []), ...(param === null ? [] : [param])],
|
||||
);
|
||||
for (const m of open) {
|
||||
const mid = randomUUID();
|
||||
this.#store.run(
|
||||
'INSERT INTO messages(id,at,business,from_role,from_run,to_role,class,in_reply_to,decision,corrects,body) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
||||
mid, this.#now(), record.business, instance, NOTICE_RUN, m.from_role, 'RESULT', m.id, null, null, body,
|
||||
);
|
||||
this.#route(record.business, mid, m.from_role, session);
|
||||
}
|
||||
return { posted: open.length };
|
||||
});
|
||||
}
|
||||
// Row 271 (264d, #1776, D7 steps 3-5): the business's clears still in the launcher's hands, as of
|
||||
// each op's latest row. An open op waits for its drained run's stop and exit proof, then its
|
||||
// retirement. A retired op whose successor hasn't started, and wasn't cancelled, waits for its
|
||||
@@ -6089,7 +6207,7 @@ export class Broker {
|
||||
const args = request.args ?? {};
|
||||
if (!object(args)) fail('invalid-request');
|
||||
return Promise.resolve().then(() => this.#proxyPage(request.verb, args, { business: s.business, human: s.human }))
|
||||
.catch(error => { throw this.#refused(s, new BusError(PROXY_PAGE_CODES.includes(error.code) ? error.code : 'proxy-down'), { verb: request.verb }); });
|
||||
.catch(error => { throw this.#refused(s, new BusError(PROXY_PAGE_CODES.includes(error.code) ? error.code : 'proxy-down', proxyCause(error)), { verb: request.verb }); });
|
||||
}
|
||||
// #1873: the fence clear takes restart evidence, which the runtime re-proves on the host
|
||||
// before the lock clears. Owner only, before every other gate, like the proxy page verbs.
|
||||
@@ -6104,6 +6222,27 @@ export class Broker {
|
||||
return result;
|
||||
}).catch(error => { throw this.#refused(s, new BusError(/^proxy-[a-z-]+$/.test(error.code ?? '') ? error.code : 'proxy-down'), { verb: request.verb }); });
|
||||
}
|
||||
// proxy-scope slice 4 (Jason 2026-11-19): ensure or revoke the instance's Triage key through the
|
||||
// proxy this bus rides. Owner only, before every other gate, like proxy.fence.clear. The
|
||||
// answer, the event and the refusal carry key ids and codes only, never a key.
|
||||
if (request.verb === 'proxy.triage.key') {
|
||||
this.#human(s);
|
||||
if (!this.#proxyTriageKey) fail('not-configured');
|
||||
const args = request.args ?? {};
|
||||
keys(args, ['op'], ['op']);
|
||||
if (args.op !== 'ensure' && args.op !== 'revoke') fail('invalid-request');
|
||||
const ID = /^[0-9a-f]{12}$/;
|
||||
const idList = v => Array.isArray(v) && v.every(id => typeof id === 'string' && ID.test(id));
|
||||
return Promise.resolve().then(() => this.#proxyTriageKey(args.op)).then(result => {
|
||||
const ACTIONS = args.op === 'ensure' ? ['issued', 'held', 'replaced'] : ['revoked', 'none'];
|
||||
if (!object(result) || !ACTIONS.includes(result.action) || !idList(result.addedKeyIds) || !idList(result.removedKeyIds)
|
||||
|| (args.op === 'ensure' && !(typeof result.keyId === 'string' && ID.test(result.keyId)))) fail('proxy-client-response');
|
||||
const answer = { op: args.op, action: result.action, addedKeyIds: [...result.addedKeyIds], removedKeyIds: [...result.removedKeyIds],
|
||||
...(args.op === 'ensure' ? { keyId: result.keyId, rotateBy: /^\d{4}-\d{2}-\d{2}$/.test(result.rotateBy ?? '') ? result.rotateBy : null } : {}) };
|
||||
this.#store.transaction(() => this.#event(s, 'action.allowed', { call: 'proxy.triage.key', ...answer }, null));
|
||||
return answer;
|
||||
}).catch(error => { throw this.#refused(s, error instanceof BusError ? error : new BusError('storage-unavailable', 'triage-key-failed'), { verb: request.verb }); });
|
||||
}
|
||||
// FED R3 (design 3.5, 3.7 trigger 1): a user reaches the collaborator list only, and each
|
||||
// request reads the access file again, so a removed or expired grant refuses the next one.
|
||||
let grants = null;
|
||||
@@ -6791,6 +6930,9 @@ export class Broker {
|
||||
#pinRole(noHire, hire) {
|
||||
const pin = hire?.pin;
|
||||
if (!object(pin)) fail('invalid-request');
|
||||
// #1873 triage-fence: a recorded pin never hires a system-only template, by reference or as the
|
||||
// inline copy of one (the inline composition below drops from).
|
||||
if (systemOnly(pin.template) || systemOnly(hire.entry?.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
if (!Object.hasOwn(pin, 'inline')) return structuredClone(pin);
|
||||
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
|
||||
// The broker's sandbox import closure is fixed, so the digest and the composition are local
|
||||
@@ -7202,7 +7344,7 @@ export class Broker {
|
||||
// name; a file check (BusinessError) is invalid-request, anything else outcome-unknown.
|
||||
#packFail(e) {
|
||||
const code = e?.code ?? '';
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured'].includes(code)
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured', SYSTEM_ONLY_REFUSAL].includes(code)
|
||||
|| /^(starter-pack|definition|organization)-[a-z-]+$/.test(code)) fail(code);
|
||||
if (e?.name === 'BusinessError') fail('invalid-request');
|
||||
throw new BusError('outcome-unknown');
|
||||
@@ -7234,6 +7376,8 @@ export class Broker {
|
||||
if ((verb === "instance.hire" || verb === "instance.fire") && e.code === "definition-not-hireable") fail(e.code);
|
||||
// Row 194 (B7, webby-0094 N3): the limits writer's keep check, against the file, as well.
|
||||
if (e.code === "instance-kept") fail(e.code);
|
||||
// #1873 triage-fence: a system-only template refuses by its one code on every write.
|
||||
if (e.code === SYSTEM_ONLY_REFUSAL) fail(e.code);
|
||||
// #1873 T1: the definition writer's refusals pass by code; a composition refusal stays invalid-request.
|
||||
if (Object.hasOwn(DEFINITION_BUS_KEYS, verb) && /^definition-[a-z-]+$/.test(e.code ?? "")) fail(e.code);
|
||||
// Row 194 (brief item 8): a fire's or a delete's revoke failed, and nothing was written.
|
||||
|
||||
@@ -6,6 +6,8 @@ import { isDeepStrictEqual } from 'node:util';
|
||||
import { BusError } from './broker.mjs';
|
||||
export const REVOKE_TIMEOUT_MS = 5000;
|
||||
export const REVOKE_POLL_MS = 25;
|
||||
export const ISSUE_PROBE_TIMEOUT_MS = 2000;
|
||||
export const ISSUE_REPROBE_MIN_MS = 250;
|
||||
export const MODEL_STOP_TIMEOUT_MS = 5000;
|
||||
const keyId = key => createHash('sha256').update(key).digest('hex').slice(0, 12);
|
||||
const fail = code => { throw new BusError(code); };
|
||||
@@ -223,9 +225,21 @@ export class ModelKeys {
|
||||
this.#sentinel(keys);
|
||||
return this.#issue(instance, false, keys);
|
||||
});
|
||||
let status;
|
||||
try { status = await this.#client.probeKey(proxy.key); }
|
||||
catch { fail('proxy-down'); }
|
||||
// Every v8 CLIProxyAPI applies a key-list PUT by an async reload after it answers, so a
|
||||
// just-issued key can answer 401 for a moment. On 8.0.79 that moment outlasts the confirming
|
||||
// GET (measured, #1873). Only 401 is probed again, until a short deadline; a re-probe waits
|
||||
// about the time left, at least ISSUE_REPROBE_MIN_MS. Any other non-2xx refuses on the first
|
||||
// answer, as before.
|
||||
const deadline = performance.now() + ISSUE_PROBE_TIMEOUT_MS;
|
||||
let status, first = true;
|
||||
for (;;) {
|
||||
const options = first ? undefined : { timeout: Math.max(ISSUE_REPROBE_MIN_MS, Math.ceil(deadline - performance.now())) };
|
||||
first = false;
|
||||
try { status = await this.#client.probeKey(proxy.key, options); }
|
||||
catch { fail('proxy-down'); }
|
||||
if (status !== 401 || performance.now() >= deadline) break;
|
||||
await new Promise(resolve => setTimeout(resolve, REVOKE_POLL_MS));
|
||||
}
|
||||
if (status < 200 || status >= 300) fail('proxy-key-refused');
|
||||
return proxy;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ const LAUNCH_OPS = new Set([
|
||||
'landHeld',
|
||||
'threadsState',
|
||||
'threadIdle',
|
||||
'failureNotice',
|
||||
'mayLaunch',
|
||||
'landHolders',
|
||||
'landRelease',
|
||||
@@ -67,6 +68,8 @@ function launchOp(m) {
|
||||
// Row 121 (#1615): the launcher's view of the business's threads, and its idle release.
|
||||
if (m.op === 'threadsState') return runtime.threadsState(m.business);
|
||||
if (m.op === 'threadIdle') return runtime.threadIdle(m.record);
|
||||
// #1873 chat-fail F2: one plain line per message a refused thread start or a proxy-stall stop left unanswered.
|
||||
if (m.op === 'failureNotice') return runtime.failureNotice(m.record);
|
||||
// Row 125 (#1619, REQ-LIMIT-4): the limit checks' answer before a launch (async).
|
||||
if (m.op === 'mayLaunch') return runtime.mayLaunch(m);
|
||||
// Row 156 (#1651): the launcher's landing pass: who holds a merge decision, and the stop of a
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { sha256, refuse } from '../../model-proxy/src/common.mjs';
|
||||
import { PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
|
||||
import { ZAI_URL, MODEL_ID } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
import { MODEL_ID, PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
export { PROXY_PAGE_VERBS, PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
|
||||
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
function fields(args, names) {
|
||||
@@ -13,19 +13,61 @@ const priorityOk = n => Number.isInteger(n) && n >= -1000 && n <= 1000;
|
||||
const identifier = x => typeof x === 'string' && x.length > 0 && x.length <= 512;
|
||||
const stateOk = x => typeof x === 'string' && /^[a-zA-Z0-9_-]{1,512}$/.test(x);
|
||||
const keyId = value => sha256(value).slice(0, 12);
|
||||
const providerName = provider => ({ claude: 'Claude', codex: 'Codex', 'z.ai': 'z.ai', other: 'Other' })[provider];
|
||||
// #1873 settings-backend-a3: provider names, the login allow list and the key allow list all come
|
||||
// from the plugin's PROVIDERS. An account the list does not name reads Other.
|
||||
// An entry counts only with what its door needs: a sign-in host, or a key base URL.
|
||||
const usable = p => p.signIn === 'oauth' ? typeof p.signInHost === 'string' : p.signIn === 'apikey' && typeof p.baseUrl === 'string';
|
||||
const listed = (providers, id, signIn) => providers.find(p => p.id === id && p.signIn === signIn && usable(p)) ?? null;
|
||||
const providerName = (providers, provider) => providers.find(p => p.id === provider)?.label ?? 'Other';
|
||||
// Credential labels/emails and group names are arbitrary upstream strings. A stable
|
||||
// generated display name provides identification without reflecting a misplaced token.
|
||||
function view(id, provider, status, priority) {
|
||||
return { accountId: keyId(id), provider, displayName: `${providerName(provider)} account ${keyId(id)}`,
|
||||
function view(providers, id, provider, status, priority) {
|
||||
return { accountId: keyId(id), provider, displayName: `${providerName(providers, provider)} account ${keyId(id)}`,
|
||||
status, priority: priorityOk(priority) ? priority : 0 };
|
||||
}
|
||||
// #1873 chat-fail F3: one plain line under an account the proxy reports as not working, with
|
||||
// the next step. It is built only from the structured fields of the account read this page
|
||||
// already makes. status_message is matched against fixed patterns and never shown; a label,
|
||||
// email, recovery hint or refresh error message is never read into the line.
|
||||
const SIGN_IN = 'The account needs to sign in again. Sign in again, or add another account.';
|
||||
const NO_REASON = 'The model service gave no reason. Wait and try again later, sign in again, or add another account.';
|
||||
const USAGE_TEXT = /usage limit|quota|rate.?limit|limit reached|too many requests|\b429\b|insufficient.?balance|credit balance/i;
|
||||
// A bare "expired" is not enough: a usage window expires too.
|
||||
const SIGN_IN_TEXT = /\b401\b|unauthori[sz]ed|invalid.?grant|\b(?:\w*[_-])?(?:tokens?|sessions?|credentials?|logins?|auth\w*|grants?)\s+(?:(?:has|have|is|are|was|were)\s+)?(?:been\s+)?expired|\brevoked\b|\bsign.?in\b|\b(?:re-?)?log.?in\b|\bre-?auth/i;
|
||||
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
|
||||
// A reset time the read gives, as "YYYY-MM-DD HH:MM UTC" made from the parsed date, only when
|
||||
// it is a valid RFC 3339 time still ahead of now. Anything else gives no time.
|
||||
function resetTime(value, now) {
|
||||
const m = typeof value === 'string' ? RFC3339.exec(value) : null;
|
||||
if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31 || +m[4] > 23 || +m[5] > 59 || +m[6] > 59) return null;
|
||||
// A day the month doesn't have (02-31) would roll into the next month, so it is refused.
|
||||
const day = new Date(Date.UTC(2000, +m[2] - 1, +m[3]));
|
||||
day.setUTCFullYear(+m[1]);
|
||||
if (day.getUTCMonth() !== +m[2] - 1 || day.getUTCDate() !== +m[3]) return null;
|
||||
const at = Date.parse(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${m[8]}`);
|
||||
if (!Number.isFinite(at) || at <= now) return null;
|
||||
return `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
||||
}
|
||||
function accountReason(row, now) {
|
||||
const message = typeof row.status_message === 'string' ? row.status_message.slice(0, 4096) : '';
|
||||
const time = resetTime(row.next_retry_after, now);
|
||||
const usage = time ? `The account is out of usage. It resets at ${time}. Wait until then, or add another account.`
|
||||
: 'The account is out of usage. Wait until it resets, or add another account.';
|
||||
// The structured flags come first, then the message patterns.
|
||||
if (row.requires_sign_in === true || (object(row.refresh_error) && Object.keys(row.refresh_error).length > 0)) return SIGN_IN;
|
||||
if (row.quota_blocked === true) return usage;
|
||||
if (SIGN_IN_TEXT.test(message)) return SIGN_IN;
|
||||
if (USAGE_TEXT.test(message)) return usage;
|
||||
if (time) return `The model service paused this account until ${time}. Wait until then, sign in again, or add another account.`;
|
||||
return NO_REASON;
|
||||
}
|
||||
export class ProxyPage {
|
||||
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #pending = new Map(); #writes = Promise.resolve();
|
||||
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null }) {
|
||||
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #providers; #pending = new Map(); #writes = Promise.resolve();
|
||||
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
|
||||
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null, providers = PROVIDERS }) {
|
||||
if (!client || !/^[a-zA-Z0-9_-]{1,64}$/.test(instanceTag) || typeof keyRecords !== 'function' || typeof now !== 'function'
|
||||
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0) throw new TypeError('invalid proxy page settings');
|
||||
this.#lock = lock; this.#org = org;
|
||||
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0 || !Array.isArray(providers)) throw new TypeError('invalid proxy page settings');
|
||||
this.#lock = lock; this.#org = org; this.#providers = providers;
|
||||
this.#client = client; this.#tag = instanceTag; this.#records = keyRecords; this.#now = now; this.#timeout = loginTimeoutSeconds * 1000; this.#onChange = onChange;
|
||||
}
|
||||
// Serializes read-modify-write provider config within the bus. P2 owns the
|
||||
@@ -48,28 +90,30 @@ export class ProxyPage {
|
||||
const rows = [];
|
||||
for (const row of response.files) {
|
||||
if (!identifier(row?.id) || !identifier(row?.name)) continue;
|
||||
const provider = ['claude', 'codex'].includes(row.provider) ? row.provider : 'other';
|
||||
const provider = listed(this.#providers, row.provider, 'oauth') ? row.provider : 'other';
|
||||
const status = row.disabled === true ? 'disabled' : row.unavailable === true ? 'unavailable'
|
||||
: ['ready', 'active', 'error', 'disabled', 'unavailable'].includes(row.status) ? row.status : 'unknown';
|
||||
rows.push({ ...view(row.id, provider, status, row.priority), source: 'oauth', name: row.name });
|
||||
rows.push({ ...view(this.#providers, row.id, provider, status, row.priority), source: 'oauth', name: row.name,
|
||||
...(['unavailable', 'error'].includes(status) ? { reason: accountReason(row, this.#now()) } : {}) });
|
||||
}
|
||||
for (const [groupIndex, group] of groups.entries()) {
|
||||
if (!Array.isArray(group?.keys)) continue;
|
||||
for (const [keyIndex, key] of group.keys.entries()) {
|
||||
// auth_index is generated by the proxy. Never fall back to hashing api-key.
|
||||
if (!identifier(key?.auth_index)) continue;
|
||||
const provider = group['base-url'] === ZAI_URL ? 'z.ai' : 'other';
|
||||
const provider = this.#providers.find(p => p.signIn === 'apikey' && usable(p) && p.baseUrl === group['base-url'])?.id ?? 'other';
|
||||
const status = key.disabled === true || group.disabled === true ? 'disabled' : 'active';
|
||||
const configured = group.models ?? [];
|
||||
if (!Array.isArray(configured) || configured.length > 32 || configured.some(m => !m || typeof (m.alias || m.name) !== 'string' || !MODEL_ID.test(m.alias || m.name))) refuse('proxy-down');
|
||||
rows.push({ ...view(key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
|
||||
rows.push({ ...view(this.#providers, key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
|
||||
}
|
||||
}
|
||||
return { rows, groups };
|
||||
}
|
||||
#public(row) {
|
||||
const { accountId, provider, displayName, status, priority } = row;
|
||||
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && provider === 'z.ai' ? { models: row.models } : {}) };
|
||||
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && listed(this.#providers, provider, 'apikey') ? { models: row.models } : {}),
|
||||
...(typeof row.reason === 'string' ? { reason: row.reason } : {}) };
|
||||
}
|
||||
#session(state, scope, { reportTimeout = false } = {}) {
|
||||
const entry = stateOk(state) ? this.#pending.get(state) : null;
|
||||
@@ -93,17 +137,18 @@ export class ProxyPage {
|
||||
async #request(verb, args, scope) {
|
||||
if (verb === 'proxy.accounts') {
|
||||
fields(args, []);
|
||||
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)) };
|
||||
// The provider list rides along for the page's select: id, label and sign-in kind only.
|
||||
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)), providers: publicProviders(this.#providers) };
|
||||
}
|
||||
if (verb === 'proxy.login.start') {
|
||||
fields(args, ['provider']);
|
||||
if (!['claude', 'codex'].includes(args.provider)) refuse('provider-not-allowed');
|
||||
const oauth = listed(this.#providers, args.provider, 'oauth');
|
||||
if (!oauth) refuse('provider-not-allowed');
|
||||
for (const [state, value] of this.#pending) if (value.expires <= this.#now()) this.#pending.delete(state);
|
||||
if (this.#pending.size >= 128) refuse('proxy-down');
|
||||
const answer = await (this.#lock ? this.#write(() => this.#client.oauthStart(args.provider)) : this.#client.oauthStart(args.provider));
|
||||
let url; try { url = new URL(answer.url); } catch { refuse('proxy-down'); }
|
||||
const host = args.provider === 'claude' ? 'claude.ai' : 'auth.openai.com';
|
||||
if (url.protocol !== 'https:' || url.hostname !== host || url.username || url.password || url.port
|
||||
if (url.protocol !== 'https:' || typeof oauth.signInHost !== 'string' || url.hostname !== oauth.signInHost || url.username || url.password || url.port
|
||||
|| url.href.length > 8192 || !stateOk(answer.state) || url.searchParams.getAll('state').length !== 1
|
||||
|| url.searchParams.get('state') !== answer.state || this.#pending.has(answer.state)) refuse('proxy-down');
|
||||
this.#pending.set(answer.state, { business: scope.business, human: scope.human, expires: this.#now() + this.#timeout });
|
||||
@@ -148,12 +193,13 @@ export class ProxyPage {
|
||||
}
|
||||
if (verb === 'proxy.apikey.add') {
|
||||
fields(args, ['provider', 'key']);
|
||||
if (args.provider !== 'z.ai') refuse('provider-not-allowed');
|
||||
const keyed = listed(this.#providers, args.provider, 'apikey');
|
||||
if (!keyed) refuse('provider-not-allowed');
|
||||
if (typeof args.key !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(args.key)) refuse('apikey-invalid');
|
||||
return this.#write(async () => {
|
||||
const groups = await this.#client.getUpstreamGroups();
|
||||
if (!Array.isArray(groups)) refuse('proxy-down');
|
||||
const group = { name: `mosaic-zai-${randomBytes(6).toString('hex')}`, 'base-url': ZAI_URL,
|
||||
const group = { name: `mosaic-${keyed.id.replace(/[^a-z0-9]/g, '')}-${randomBytes(6).toString('hex')}`, 'base-url': keyed.baseUrl,
|
||||
priority: 0, keys: [{ 'api-key': args.key }] };
|
||||
if (this.#lock && !isDeepStrictEqual(await this.#client.getUpstreamGroups(), groups)) refuse('proxy-down');
|
||||
this.#beforeMutation('proxy.apikey.add');
|
||||
|
||||
@@ -87,6 +87,10 @@ group("proxy-key-mismatch", "R1: a pasted management key is confirmed before ini
|
||||
group("proxy-lock-busy proxy-lock-invalid", "R4: one proxy key write at a time", "Wait for the running proxy write to finish and retry. An invalid lock file needs the owner to inspect the proxy state directory.");
|
||||
group("proxy-not-configured proxy-unit-usage proxy-unit-exists proxy-unit-dropin proxy-unit-copy proxy-unit-path proxy-unit-missing proxy-unit-unhealthy proxy-unit-failed", "R1/R4: proxy user unit is explicit creation", "Initialize the proxy first, then install the unit from the Proxy page or with mosaic proxy unit install. An existing unit or drop-in is never replaced; remove it by hand. An unhealthy unit: read its journal by unit name and restart it.");
|
||||
group("proxy-client-invalid proxy-client-refused proxy-client-response", "R1: proxy management answers", "Check the proxy unit is running and its port answers on the Proxy page, then retry. Upstream bodies are never shown.");
|
||||
// proxy-scope slice 4 (Jason 2026-11-19): the Triage key lives with a bus that rides the owner's
|
||||
// proxy, and a Triage session on a key past its retireAt ends before the key leaves the proxy.
|
||||
group("triage-no-riding-bus", "R1/R4: the Triage key is issued and rotated by a bus that rides the owner's proxy", "Triage needs one organization that uses the owner's models. Start an organization that rides the owner's model proxy, then repair Triage access from Settings, Triage.");
|
||||
group("triage-key-rotated", "R1/R6: a session ends when its Triage key's grace ends", "The Triage key was rotated and the old key's grace has ended. Send the next message; Triage starts again on the current key.");
|
||||
group(
|
||||
"block-recipient block-reply-required block-sender message-recipient-refused message-sender-refused tester-reply-required tester-thread-human user-reply-required user-thread-human",
|
||||
"Role messaging: permitted sender, recipient and reply context",
|
||||
@@ -199,6 +203,13 @@ group(
|
||||
"R10: only the caller's own saved templates",
|
||||
"List your saved templates and use one of those names. A saved template is visible only to the owner who saved it."
|
||||
);
|
||||
// #1873 triage-fence: a template on the system-only list (organization vocabulary.mjs SYSTEM_ONLY)
|
||||
// joins no organization by any path.
|
||||
group(
|
||||
"template-system-only",
|
||||
"R8/R10: a system-only role template joins no organization",
|
||||
"This role template serves the system outside every organization. Pick another template or definition; no hire, change, pack, import or instance write gives an organization one."
|
||||
);
|
||||
group(
|
||||
"starter-pack-template-changed",
|
||||
"R8: a pack's hash pin must match the current template",
|
||||
|
||||
+173
-11
@@ -32,14 +32,16 @@ import { loadManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { ProxyPage } from './proxy-page.mjs';
|
||||
import { createModelCatalogue } from './model-catalogue.mjs';
|
||||
import { sha256 } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { initializeProxy, loadProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { createProxyLock } from './proxy-lock.mjs';
|
||||
import { ensureKey, readKey as readTriageKey, revokeKeys, sweepDue, sweepKeys } from './triage-key.mjs';
|
||||
import { verifyRestart } from '../../model-proxy/src/admin.mjs';
|
||||
import { ModelKeys, modelOrganization, stopModelRuns, MODEL_STOP_TIMEOUT_MS } from './model-keys.mjs';
|
||||
import { instanceSettings } from '../../organization/src/instance-settings.mjs';
|
||||
import { organizationWriter, OrganizationError, setReplyLimits } from '../../organization/src/organization.mjs';
|
||||
import { definitionVerbs, DEFINITION_BUS_VERBS } from '../../organization/src/definition-verbs.mjs';
|
||||
import { ORG_PREFIX, orgDefinitionName, compositionOf, readTemplate, entryFromTemplate, lineDiff, PRIMITIVES } from '../../organization/src/definitions.mjs';
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
import { installedStarterPacks, readSavedTemplate } from '../../plugins/src/starter-pack.mjs';
|
||||
import { TemplateError, templateList, templatePreview, templateSave } from '../../organization/src/template-save.mjs';
|
||||
import { checkComposition } from '../../organization/src/composition.mjs';
|
||||
@@ -313,7 +315,10 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
async function loadPack(name, actor) {
|
||||
if (typeof name !== 'string' || name.length > 128) bad();
|
||||
if (name.startsWith(SAVED_PREFIX)) return readSavedTemplate({ configDir, account: actor, name: name.slice(SAVED_PREFIX.length), rolesDir });
|
||||
const found = (await installed()).find(p => p.id === name);
|
||||
const { packs, refused } = await installedStarterPacks({ dataRoot, rolesDir });
|
||||
const found = packs.find(p => p.id === name);
|
||||
// #1873 triage-fence: an installed pack refused for naming a system-only template says so.
|
||||
if (!found && refused.some(r => r.name === name && r.code === SYSTEM_ONLY_REFUSAL)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (!found) throw new BusError('starter-pack-not-found');
|
||||
return found;
|
||||
}
|
||||
@@ -332,6 +337,9 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
// The entry a pack definition writes: a template reference becomes the template's own entry, pinned
|
||||
// by its hash (a moved hash refuses), and a full entry is copied as it is. Neither carries rev.
|
||||
function entryOf(value) {
|
||||
// #1873 triage-fence: preview and apply both refuse a pack naming a system-only template, as a
|
||||
// reference or as the from of a full entry.
|
||||
if (systemOnly(value?.template) || systemOnly(value?.from?.template)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (Object.hasOwn(value, 'template') && Object.hasOwn(value, 'sha256') && Object.keys(value).length === 2) {
|
||||
const template = readTemplate(rolesDir, value.template);
|
||||
if (template.sha256 !== value.sha256) throw new BusError('starter-pack-template-changed');
|
||||
@@ -615,6 +623,10 @@ export async function startBroker({
|
||||
// P1 validated sidecar from the trusted host; never a socket request setting.
|
||||
proxy = null,
|
||||
org = null, instanceDataRoot = null, instanceConfigDir = null,
|
||||
// proxy-scope slice 4: the Triage key sweep on a riding org bus. intervalMs (default 30 s) and
|
||||
// marginMs (default 30 s past a retiring key's retireAt, so the Console stops a session on it
|
||||
// first) are in-process seams, as are now and hook (triage-key.mjs's clock and stage hook).
|
||||
triageKeys = {},
|
||||
// Host-only preparation/admission capabilities. The host builds its own from the organization writer and `trackers`
|
||||
// (request-host.mjs); anything given here replaces the host's, and a capability nothing supplies leaves a setup wait.
|
||||
requestServices = {},
|
||||
@@ -624,6 +636,7 @@ export async function startBroker({
|
||||
builtinBinding = null,
|
||||
modelCatalogue = null, // in-process fixture seam; boot JSON cannot supply a service
|
||||
makeProviderLoader = createLoader, // in-process fixture seam; boot JSON cannot supply a function
|
||||
initProxy = initializeProxy, // in-process fixture seam (a test install pin); boot JSON cannot supply a function
|
||||
// #1873 A3: the boot's root and project agent copies (cli config.mjs copiesAtBoot), plain data. Every
|
||||
// reload of the organization file below re-applies this snapshot, never the root file.
|
||||
copies = null,
|
||||
@@ -631,6 +644,7 @@ export async function startBroker({
|
||||
// In-process only, like librarySync; production passes none.
|
||||
copyTransport = null,
|
||||
}) {
|
||||
if (typeof initProxy !== 'function') throw new BusError('invalid-host-request');
|
||||
if (copies !== null && (typeof copies !== 'object' || Array.isArray(copies) || typeof copies.org !== 'string'
|
||||
|| !Object.hasOwn(businesses ?? {}, copies.org) || copies.copies === null || typeof copies.copies !== 'object' || Array.isArray(copies.copies)))
|
||||
throw new BusError('invalid-host-request');
|
||||
@@ -648,6 +662,8 @@ export async function startBroker({
|
||||
throw new BusError('invalid-host-request');
|
||||
let modelProxyClient = null, proxyPage = null, proxyUsage = null, usageTimer = null, proxyLock = null, proxyPort = null;
|
||||
let modelKeys = null, modelTimer = null, modelSweep = null, modelCatalogues = null;
|
||||
// proxy-scope slice 4: the settings of the proxy this bus rides (boot, picked up or initialized).
|
||||
let proxySettings = null, triageTimer = null, triageSweepRun = null;
|
||||
const modelRuns = new Map();
|
||||
let store, credentials, server, adapter, processing, syncTimer = null, syncPass = null, accessTimer = null, requestTimer = null, copyLaunch = null, copyRevoker = null, copyTimer = null;
|
||||
// #1873 CB4: a revoke's stop waits for the broker; a start that fails before it exists stops nothing.
|
||||
@@ -698,7 +714,7 @@ export async function startBroker({
|
||||
proxyLock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${proxy.port}` });
|
||||
}
|
||||
modelProxyClient = await loadManagementClient({ configDir: org ? instanceConfigDir : organization.dir, proxy, receipt: proxyReceipt });
|
||||
proxyPort = proxy.port;
|
||||
proxyPort = proxy.port; proxySettings = proxy;
|
||||
}
|
||||
|
||||
// Row 234 (#1740, r6 X4 third bullet): each host grant record gives its agent a store reference to
|
||||
@@ -828,7 +844,126 @@ export async function startBroker({
|
||||
// records. A daily key quota moved within one agent's lineage keeps its since and its count.
|
||||
const keyLineage=(business,keyId)=>modelKeyLineage(credentials.status(),business,keyId);
|
||||
const settings=organization?launchSettings({...organization,sessions:()=>readSessions(dataRoot),levels,keyLineage}):null;
|
||||
modelCatalogues = modelCatalogue ?? (settings ? createModelCatalogue({ pluginDataRoot:instanceRoot ?? dataRoot, client: () => modelProxyClient, settings: id => settings.current(id).plugins ?? {}, proxyLock }) : null);
|
||||
// #1873 proxy-pickup: a bus started before the instance had a shared proxy picks it up at the
|
||||
// first request that needs one, through the start path's checks, loader and lock. A client got
|
||||
// that way (or by this bus's own proxy.init) is checked again at every such request and dropped
|
||||
// when the start path would now refuse it. A bus started with a proxy keeps its boot client:
|
||||
// its ModelKeys holds that client. `proxyCause` is the one plain line the owner sees while there
|
||||
// is no client: static text and a refusal code, never a path or a key.
|
||||
let lateProxy = false, proxyCause = null, proxySync = Promise.resolve();
|
||||
const dropLateProxy = cause => {
|
||||
if (lateProxy) { modelProxyClient = null; proxyPage = null; proxyPort = null; proxyLock = null; proxySettings = null; lateProxy = false; modelCatalogues?.invalidate?.(); }
|
||||
proxyCause = cause;
|
||||
};
|
||||
// The host refuses fixture-proxy-configured at boot when a dev fixture is recorded for the
|
||||
// instance and the organization routes a launch to the fixture (cli dev-fixture.mjs
|
||||
// fixtureLauncherOptions). Anything but a plain absence of the record counts as recorded.
|
||||
const fixtureRecorded = () => { try { lstatSync(join(instanceRoot ?? dataRoot, 'dev-fixture', 'fixture.json')); return true; } catch (error) { return error.code !== 'ENOENT'; } };
|
||||
const usesFixture = id => {
|
||||
try {
|
||||
const doc = settings.current(id), providers = doc.plugins?.['model-provider'];
|
||||
return (Array.isArray(providers) && providers.includes('fixture')) || Object.values(doc.launch?.models ?? {}).some(m => m?.module === 'fixture');
|
||||
} catch { return true; }
|
||||
};
|
||||
async function pickProxy() {
|
||||
if (proxy || !organization || !settings) return;
|
||||
if (org !== null && (!org || typeof org.id !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(org.id) || typeof instanceDataRoot !== 'string' || typeof instanceConfigDir !== 'string'))
|
||||
return dropLateProxy('This bus has no valid organization binding for the shared proxy (invalid-host-request). Restart it from the host.');
|
||||
const configDir = org ? instanceConfigDir : organization.dir;
|
||||
let found;
|
||||
try { found = loadProxy(configDir, instanceRoot ?? dataRoot); }
|
||||
catch (error) { return dropLateProxy(`The model proxy settings do not load (${/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : 'proxy-config-invalid'}). This organization reads no accounts or catalogue until they do.`); }
|
||||
if (found === undefined) return dropLateProxy('The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.');
|
||||
if (modelProxyClient && found.port !== proxyPort) dropLateProxy(null);
|
||||
if (fixtureRecorded() && Object.keys(businesses).some(usesFixture))
|
||||
return dropLateProxy('This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.');
|
||||
let client;
|
||||
try { client = await loadManagementClient({ configDir, proxy: found, receipt: proxyReceipt }); }
|
||||
catch { return dropLateProxy('The model proxy management key does not load (proxy-management-key-invalid). This bus cannot reach the proxy until the key file is fixed.'); }
|
||||
let lock = null;
|
||||
if (org) {
|
||||
try { lock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${found.port}` }); }
|
||||
catch { return dropLateProxy('The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'); }
|
||||
}
|
||||
proxyCause = null;
|
||||
proxySettings = found;
|
||||
// Same port, key and lock still load: keep the client and its page, which holds login states.
|
||||
if (modelProxyClient) return;
|
||||
modelProxyClient = client; proxyPort = found.port; proxyLock = lock; lateProxy = true;
|
||||
configureProxyPage(); modelCatalogues?.invalidate?.();
|
||||
}
|
||||
// proxy-scope slice 4: what triage-key.mjs needs from a riding org bus. A key error becomes a bus
|
||||
// refusal the table already holds: proxy codes it knows pass through, the rest name the key
|
||||
// store's code in the reason only. Neither carries a key, a path or upstream text.
|
||||
// The verb checks the proxy first, as proxy.fence.clear does; the sweep uses what this bus holds
|
||||
// and never picks a proxy up on its own timer.
|
||||
const triageOptions = async ({ sync = true } = {}) => {
|
||||
if (sync) await syncProxy();
|
||||
if (org === null || !organization || !proxyLock || !modelProxyClient || !proxySettings || typeof instanceConfigDir !== 'string' || typeof instanceDataRoot !== 'string')
|
||||
throw new BusError('triage-no-riding-bus');
|
||||
return { configDir: instanceConfigDir, system: { dataRoot: instanceDataRoot, proxy: proxySettings }, client: modelProxyClient, lock: proxyLock,
|
||||
...(triageKeys.now ? { now: triageKeys.now } : {}), ...(triageKeys.hook ? { hook: triageKeys.hook } : {}) };
|
||||
};
|
||||
const TRIAGE_PASS = new Set(['proxy-lock-busy', 'proxy-lock-invalid', 'proxy-lock-uncertain', 'proxy-client-invalid', 'proxy-client-refused', 'proxy-client-response', 'proxy-management-key-invalid']);
|
||||
const TRIAGE_MAP = { 'triage-key-no-proxy': 'triage-no-riding-bus', 'triage-key-raced': 'proxy-lock-busy', 'triage-key-unconfirmed': 'proxy-lock-uncertain',
|
||||
'proxy-uncertain': 'proxy-lock-uncertain', 'proxy-client-down': 'proxy-client-response', 'proxy-client-redirect': 'proxy-client-response', 'triage-key-proxy-open': 'proxy-not-configured' };
|
||||
const triageRefusal = error => {
|
||||
if (error instanceof BusError) return error;
|
||||
const code = typeof error?.code === 'string' ? error.code : '';
|
||||
if (TRIAGE_PASS.has(code)) return new BusError(code);
|
||||
if (Object.hasOwn(TRIAGE_MAP, code)) return new BusError(TRIAGE_MAP[code], code);
|
||||
return new BusError('storage-unavailable', /^triage-key-[a-z-]+$/.test(code) ? code : 'triage-key-failed');
|
||||
};
|
||||
// The sweep: a cheap read of the file first, so the proxy is asked only when something is due;
|
||||
// sweepKeys decides again under the lock. It never issues: no file, nothing.
|
||||
const triageMarginMs = Number.isSafeInteger(triageKeys.marginMs) && triageKeys.marginMs >= 0 ? triageKeys.marginMs : 30_000;
|
||||
// A refusal that repeats on every tick is logged when it first appears or changes, and then once
|
||||
// an hour while it stays the same; any other outcome clears it.
|
||||
let triageLastRefusal = null;
|
||||
const sweepRefused = (now, entry) => {
|
||||
const sig = `${entry.code}|${entry.reason ?? ''}`;
|
||||
if (triageLastRefusal?.sig === sig && now - triageLastRefusal.at < 3_600_000) return;
|
||||
triageLastRefusal = { sig, at: now };
|
||||
proxyReceipt({ action: 'triage.key.sweep-refused', ...entry });
|
||||
};
|
||||
const sweepTriage = async () => {
|
||||
let opts;
|
||||
try { opts = await triageOptions({ sync: false }); } catch { return { action: 'none' }; }
|
||||
const now = (opts.now ?? Date.now)();
|
||||
let record;
|
||||
try { record = readTriageKey(opts.configDir); } catch { sweepRefused(now, { code: 'triage-key-unreadable' }); return { action: 'none' }; }
|
||||
if (!sweepDue(record, now, triageMarginMs)) { triageLastRefusal = null; return { action: 'none' }; }
|
||||
try {
|
||||
const result = await sweepKeys(opts, { marginMs: triageMarginMs });
|
||||
triageLastRefusal = null;
|
||||
if (result.action !== 'none') proxyReceipt({ action: `triage.key.${result.action}`, keyId: result.keyId ?? null, addedKeyIds: result.addedKeyIds, removedKeyIds: result.removedKeyIds });
|
||||
return result;
|
||||
} catch (error) {
|
||||
const refusal = triageRefusal(error);
|
||||
sweepRefused(now, { code: refusal.code, ...(typeof refusal.reason === 'string' ? { reason: refusal.reason } : {}) });
|
||||
return { action: 'refused', code: refusal.code };
|
||||
}
|
||||
};
|
||||
const triageSweepOnce = () => (triageSweepRun ??= sweepTriage().finally(() => { triageSweepRun = null; }));
|
||||
// One check at a time; an unexpected failure drops a late client, never keeps it.
|
||||
const syncProxy = () => (proxySync = proxySync.then(pickProxy).catch(() => dropLateProxy('The model proxy could not be checked (proxy-down). Try again shortly.')));
|
||||
// Unavailable with no client: the catalogue names the cause instead of a bare unavailable.
|
||||
// pickup-launch: a late client serves accounts and the catalogue, but a launch on it needs what
|
||||
// only the start path builds (ModelKeys here, the proxy in the host launcher's boot system), so
|
||||
// while this bus holds one a ready catalogue says plainly that a restart is needed. Not on an
|
||||
// unavailable one: a fence, a collision or a down proxy still refuses after a restart.
|
||||
const RESTART_TO_LAUNCH = 'Restart this organization to start agents on these models.';
|
||||
const explainCatalogue = value => {
|
||||
if (value?.status === 'unavailable' && value.reason === undefined && !modelProxyClient && proxyCause)
|
||||
return { ...value, reason: 'proxy-not-configured', notices: [proxyCause] };
|
||||
if (lateProxy && value?.status === 'ready')
|
||||
return { ...value, notices: [...(value?.notices ?? []), RESTART_TO_LAUNCH] };
|
||||
return value;
|
||||
};
|
||||
const baseCatalogue = settings ? createModelCatalogue({ pluginDataRoot:instanceRoot ?? dataRoot, client: () => modelProxyClient, settings: id => settings.current(id).plugins ?? {},
|
||||
// A view, so a lock taken by a later pickup or init counts as it does for the start path's.
|
||||
proxyLock: { assertCertain: () => proxyLock?.assertCertain(), generation: () => proxyLock?.generation() } }) : null;
|
||||
modelCatalogues = modelCatalogue ?? (baseCatalogue ? { ...baseCatalogue, read: async (id, options) => { await syncProxy(); return explainCatalogue(await baseCatalogue.read(id, options)); } } : null);
|
||||
// Resolve legacy table entries with the enabled modules' declarations. A
|
||||
// missing or ambiguous mapping never becomes an available route.
|
||||
async function catalogueFor(id, options = {}) {
|
||||
@@ -1333,24 +1468,38 @@ export async function startBroker({
|
||||
// Row 199 (#1697, design section 6): issue, rotate, revoke and delete, live with no restart; each
|
||||
// rewrites or records through the organization writer, so changes.jsonl holds the receipt.
|
||||
proxyPage: async (verb, args, scope) => {
|
||||
if (!proxyPage) throw new BusError('not-configured');
|
||||
await syncProxy();
|
||||
if (!proxyPage) throw new BusError('not-configured', proxyCause ?? undefined);
|
||||
return proxyPage.request(verb, args, scope);
|
||||
},
|
||||
proxyInit: organization ? async args => {
|
||||
const settings = await initializeProxy({ configDir: organization.dir, dataRoot: instanceRoot ?? dataRoot, ...args });
|
||||
modelProxyClient = await loadManagementClient({ configDir: organization.dir, proxy: settings, receipt: proxyReceipt });
|
||||
proxyPort = settings.port;
|
||||
const settings = await initProxy({ configDir: organization.dir, dataRoot: instanceRoot ?? dataRoot, ...args });
|
||||
const client = await loadManagementClient({ configDir: organization.dir, proxy: settings, receipt: proxyReceipt });
|
||||
// #1873: an org bus that initializes the shared proxy also holds its write lock from now on.
|
||||
if (org && !proxyLock) proxyLock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${settings.port}` });
|
||||
configureProxyPage();
|
||||
// proxy-pickup: the lock comes first, so a lock that refuses leaves no client behind.
|
||||
const lock = org && !proxyLock ? createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${settings.port}` }) : proxyLock;
|
||||
// proxy-pickup: a client this bus did not boot with is checked again like a picked-up one.
|
||||
if (!proxy) { lateProxy = true; proxyCause = null; }
|
||||
modelProxyClient = client; proxyPort = settings.port; proxyLock = lock; proxySettings = settings;
|
||||
configureProxyPage(); modelCatalogues?.invalidate?.();
|
||||
return settings;
|
||||
} : null,
|
||||
// #1873: clear the uncertain-write fence only on restart evidence this host re-proves: the
|
||||
// process on the proxy port is new, alive and started after the fence was set.
|
||||
proxyFenceClear: organization ? async ({ evidence }) => {
|
||||
if (!proxyLock || !modelProxyClient) throw new BusError('not-configured');
|
||||
await syncProxy();
|
||||
if (!proxyLock || !modelProxyClient) throw new BusError('not-configured', proxyCause ?? undefined);
|
||||
return proxyLock.clear({ restarted: true, read: () => modelProxyClient.getKeys(), verify: previous => verifyRestart(evidence, { fence: previous, port: proxyPort }) });
|
||||
} : null,
|
||||
// proxy-scope slice 4 (Jason 2026-11-19): ensure or revoke the instance's Triage key through the
|
||||
// proxy this org bus rides, under the bus's own client and instance proxy lock. The answer is
|
||||
// ids only. A no-org bus, or an org bus with no proxy client and lock, refuses
|
||||
// triage-no-riding-bus.
|
||||
proxyTriageKey: async (op) => {
|
||||
const opts = await triageOptions();
|
||||
try { return op === 'ensure' ? await ensureKey(opts) : await revokeKeys(opts); }
|
||||
catch (error) { throw triageRefusal(error); }
|
||||
},
|
||||
credentialVerbs: organization
|
||||
? credentialVerbs({ credentials, writer: organizationWriter({ dir: organization.dir, rolesDir: organization.rolesDir, dataRoot:instanceRoot ?? dataRoot }),
|
||||
organizations: () => Object.keys(businesses), boot: copies?.definitions ? { org: copies.org, definitions: copies.definitions } : null })
|
||||
@@ -1658,6 +1807,12 @@ export async function startBroker({
|
||||
}, access.intervalMs ?? ACCESS_SWEEP_MS);
|
||||
accessTimer.unref();
|
||||
}
|
||||
// proxy-scope slice 4: only an org bus sweeps the Triage key; each tick checks it still rides.
|
||||
if (org !== null && organization) {
|
||||
triageTimer = setInterval(() => { triageSweepOnce(); },
|
||||
Number.isSafeInteger(triageKeys.intervalMs) && triageKeys.intervalMs > 0 ? triageKeys.intervalMs : 30_000);
|
||||
triageTimer.unref();
|
||||
}
|
||||
if (modelKeys) {
|
||||
modelTimer = setInterval(() => {
|
||||
if (modelSweep) return;
|
||||
@@ -1785,6 +1940,8 @@ export async function startBroker({
|
||||
},
|
||||
threadsState: (business) => broker.threadsState(business),
|
||||
threadIdle: (r) => broker.threadIdle(r),
|
||||
// #1873 chat-fail F2: the plain line a refused thread start or a proxy-stall stop leaves.
|
||||
failureNotice: (r) => broker.failureNotice(r),
|
||||
// Row 125 (#1619, REQ-LIMIT-4): the launcher asks the limit checks before every launch.
|
||||
mayLaunch: async ({ business, instance, provider, model, account = null }) => {
|
||||
processingWork();
|
||||
@@ -1824,6 +1981,8 @@ export async function startBroker({
|
||||
definitionScan,
|
||||
launches: bound,
|
||||
readers: readCaps,
|
||||
// proxy-scope slice 4: one Triage key sweep now, as the timer runs it (tests).
|
||||
triageKeySweep: () => triageSweepOnce(),
|
||||
async close() {
|
||||
clearInterval(copyTimer);
|
||||
brokerUp(null);
|
||||
@@ -1832,6 +1991,8 @@ export async function startBroker({
|
||||
await proxyUsage.close();
|
||||
clearInterval(modelTimer);
|
||||
await modelSweep;
|
||||
clearInterval(triageTimer);
|
||||
await triageSweepRun;
|
||||
clearInterval(accessTimer);
|
||||
await stopSync();
|
||||
await server.close();
|
||||
@@ -1849,6 +2010,7 @@ export async function startBroker({
|
||||
clearInterval(usageTimer);
|
||||
await proxyUsage?.close();
|
||||
clearInterval(modelTimer);
|
||||
clearInterval(triageTimer);
|
||||
clearInterval(accessTimer);
|
||||
await server?.close();
|
||||
await adapter?.close?.();
|
||||
|
||||
@@ -155,6 +155,8 @@ export async function serve({ broker, path, authenticateHuman = null, authentica
|
||||
// Row 236 (#1742): the grants verbs may call Gitea several times, 15 s each at most.
|
||||
GRANTS_VERBS.includes(r.verb) ||
|
||||
r.verb === 'proxy.init' ||
|
||||
// proxy-scope slice 4: the Triage key verb waits on the proxy lock and the proxy.
|
||||
r.verb === 'proxy.triage.key' ||
|
||||
(r.verb === 'decision.raise' && (Object.hasOwn(r.args ?? {}, 'spec_path') || Object.hasOwn(r.args ?? {}, 'spec_commit') ||
|
||||
Object.hasOwn(r.args ?? {}, 'grant')))) {
|
||||
const own = transient;
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// #1873 triage-wiring: the Triage key file's reader, moved out of triage-key.mjs so the Console can
|
||||
// read the key at each Triage spawn without loading the proxy management client or the proxy lock.
|
||||
// It imports node built-ins only; packages/webui/tests/triage-wiring.test.mjs fails if the Console's
|
||||
// Triage modules load model-proxy/src/client.mjs. triage-key.mjs (the owner's key verbs) imports
|
||||
// these and re-exports what it exported before, so its callers are unchanged.
|
||||
//
|
||||
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
|
||||
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
|
||||
//
|
||||
// Messages name files, never values.
|
||||
import { closeSync, constants, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const KEY_VERSION = 1;
|
||||
const FIELDS = Object.freeze(["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
const RETIRING_FIELDS = Object.freeze(["key", "keyId", "issuedAt", "retireAt"]);
|
||||
const MAX_BYTES = 64 * 1024;
|
||||
export const MAX_RETIRING = 16;
|
||||
export const SECRET = /^[A-Za-z0-9_-]{43}$/;
|
||||
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export class TriageKeyError extends Error {
|
||||
constructor(code, message, exitCode = 3) {
|
||||
super(message);
|
||||
this.name = "TriageKeyError";
|
||||
this.code = code;
|
||||
this.exitCode = exitCode;
|
||||
}
|
||||
}
|
||||
export const unreadable = (why) => new TriageKeyError("triage-key-unreadable", `the Triage key store is unreadable: ${why}`);
|
||||
|
||||
export const keyIdOf = (key) => createHash("sha256").update(key).digest("hex").slice(0, 12);
|
||||
export const instanceTag = (configDir) => createHash("sha256").update(configDir).digest("hex").slice(0, 12);
|
||||
export const keyPrefix = (configDir) => `mst-${instanceTag(configDir)}-triage-`;
|
||||
const ownKey = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir)) && SECRET.test(k.slice(keyPrefix(configDir).length));
|
||||
|
||||
export function keyPaths(configDir) {
|
||||
const secrets = join(configDir, "secrets");
|
||||
const dir = join(secrets, "triage");
|
||||
return { secrets, dir, file: join(dir, "model") };
|
||||
}
|
||||
|
||||
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
|
||||
const exactKeys = (v, keys) => plain(v) && Object.keys(v).length === keys.length && keys.every((k) => Object.hasOwn(v, k));
|
||||
const canonicalTime = (s) => typeof s === "string" && ISO.test(s) && !Number.isNaN(Date.parse(s)) && new Date(s).toISOString() === s;
|
||||
const canonicalDay = (s) => typeof s === "string" && DAY.test(s) && !Number.isNaN(Date.parse(`${s}T00:00:00Z`)) && new Date(`${s}T00:00:00Z`).toISOString().slice(0, 10) === s;
|
||||
|
||||
export function validRecord(doc, configDir) {
|
||||
const own = ownKey(configDir);
|
||||
return exactKeys(doc, FIELDS)
|
||||
&& doc.version === KEY_VERSION
|
||||
&& own(doc.key) && doc.keyId === keyIdOf(doc.key)
|
||||
&& canonicalTime(doc.issuedAt) && canonicalDay(doc.rotateBy)
|
||||
&& Array.isArray(doc.retiring) && doc.retiring.length <= MAX_RETIRING
|
||||
&& doc.retiring.every((r) => exactKeys(r, RETIRING_FIELDS) && own(r.key) && r.key !== doc.key && r.keyId === keyIdOf(r.key)
|
||||
&& canonicalTime(r.issuedAt) && canonicalTime(r.retireAt))
|
||||
&& new Set(doc.retiring.map((r) => r.key)).size === doc.retiring.length;
|
||||
}
|
||||
|
||||
const uidOf = (opts) => opts.uid ?? process.getuid();
|
||||
|
||||
// A real directory, the running user's, mode 0700. Missing: false, or made when `create` is on.
|
||||
export function checkDir(dir, uid, what, { create }) {
|
||||
let st;
|
||||
try { st = lstatSync(dir); }
|
||||
catch (e) {
|
||||
if (e.code !== "ENOENT") throw unreadable(`${what} cannot be read`);
|
||||
if (!create) return false;
|
||||
try { mkdirSync(dir, { mode: 0o700 }); } catch { throw unreadable(`${what} cannot be made`); }
|
||||
try {
|
||||
const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
try { fchmodSync(fd, 0o700); } finally { closeSync(fd); }
|
||||
} catch { throw unreadable(`${what} cannot be made`); }
|
||||
st = lstatSync(dir);
|
||||
}
|
||||
if (st.isSymbolicLink()) throw unreadable(`${what} is a link`);
|
||||
if (!st.isDirectory()) throw unreadable(`${what} is not a directory`);
|
||||
if (st.uid !== uid) throw unreadable(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o700) throw unreadable(`${what} mode is not 0700`);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function checkFile(fd, uid, what, fail = unreadable) {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile()) throw fail(`${what} is not a regular file`);
|
||||
if (st.nlink !== 1) throw fail(`${what} has more than one link`);
|
||||
if (st.uid !== uid) throw fail(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o600) throw fail(`${what} mode is not 0600`);
|
||||
return st;
|
||||
}
|
||||
|
||||
// The stored record, or null when no key is issued. Throws triage-key-unreadable on anything unsafe.
|
||||
// opts.uid (both directories and the file) and opts.fileUid (the file only) are test seams for the
|
||||
// owner checks.
|
||||
export function readKey(configDir, opts = {}) {
|
||||
const { secrets, dir, file } = keyPaths(configDir);
|
||||
const uid = uidOf(opts);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) return null;
|
||||
if (!checkDir(dir, uid, "the triage secrets directory", { create: false })) return null;
|
||||
let fd;
|
||||
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
||||
catch (e) {
|
||||
if (e.code === "ENOENT") return null;
|
||||
if (e.code === "ELOOP") throw unreadable("the key file is a link");
|
||||
throw unreadable("the key file cannot be opened");
|
||||
}
|
||||
try {
|
||||
const st = checkFile(fd, opts.fileUid ?? uid, "the key file");
|
||||
if (st.size > MAX_BYTES) throw unreadable("the key file is too large");
|
||||
let doc;
|
||||
try { doc = JSON.parse(readFileSync(fd, "utf8")); } catch { throw unreadable("the key file is not JSON"); }
|
||||
if (!validRecord(doc, configDir)) throw unreadable("the key file does not match the key shape");
|
||||
return doc;
|
||||
} finally { closeSync(fd); }
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// #1873 triage-key: Triage's own model proxy client key, issued from the owner's terminal
|
||||
// (design report reports/triage-route-design.md slice 3, Jason's ruling 2026-11-18), and since
|
||||
// proxy-scope slice 4 (Jason's ruling 2026-11-19) by the bus too: the verb proxy.triage.key
|
||||
// (ensure, revoke) and a riding org bus's sweep call this module with the bus's own management
|
||||
// client and instance proxy lock. It moved here from packages/cli/src so the bus can import it; the
|
||||
// terminal verbs (packages/cli/src/triage.mjs) call it unchanged.
|
||||
//
|
||||
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
|
||||
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
|
||||
//
|
||||
// The key is `mst-<instance tag>-triage-<43 base64url>`, where the tag is the first 12 hex of
|
||||
// sha256(configDir), the tag the instance's own `msk-` sentinel carries. An org bus reconciles only
|
||||
// its own `mso-<tag>-<org>-key-` names and a no-org bus only `msk-<tag>-`, so neither touches it.
|
||||
//
|
||||
// Every proxy write runs under the instance proxy lock (packages/bus/src/proxy-lock.mjs), the lock
|
||||
// org buses take: read the list, check this instance's sentinel, fence, PUT, read back, confirm.
|
||||
// The proxy changes first and the file second, as the bus does for an agent key. A crash between
|
||||
// leaves a key in the Triage namespace that the file does not hold; the next issue, rotate or retire
|
||||
// removes it, and status names it. A crash after the PUT and before the read-back leaves the lock's
|
||||
// uncertain fence, which every proxy writer on the instance refuses until a human clears it
|
||||
// (`mosaic proxy fence clear --proxy-restarted`).
|
||||
//
|
||||
// rotate records when the old key's grace ends; the key stays in the proxy until a later retire,
|
||||
// rotate, issue or sweep removes it, and status says when that is due. A riding org bus runs
|
||||
// sweepKeys on a timer: under the lock it reads the file again and rotates when rotateBy is due, or
|
||||
// retires keys whose grace (plus a margin, so the Console stops a session on the key first) has
|
||||
// passed. The sweep only replaces a key that exists; it never issues the first one.
|
||||
//
|
||||
// Nothing here prints, logs or records a key. Receipts and output carry key ids only (the first 12
|
||||
// hex of sha256(key), the id the bus uses). Messages name files and options, never values.
|
||||
// The Console reads the key at each Triage spawn through triage-key-file.mjs, never this module.
|
||||
import { closeSync, constants, fchmodSync, fsyncSync, lstatSync, openSync, readdirSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { createProxyLock } from "./proxy-lock.mjs";
|
||||
import { loadManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
|
||||
// #1873 triage-wiring: the key file's reader lives in triage-key-file.mjs (node built-ins only), so
|
||||
// the Console reads the key without this module's proxy client. Re-exported here unchanged.
|
||||
import { KEY_VERSION, MAX_RETIRING, SECRET, TriageKeyError, checkDir, checkFile, instanceTag, keyIdOf, keyPaths, keyPrefix, readKey, unreadable, validRecord } from "./triage-key-file.mjs";
|
||||
export { KEY_VERSION, TriageKeyError, instanceTag, keyIdOf, keyPaths, keyPrefix, readKey, validRecord };
|
||||
|
||||
// The org key lifetime and the rotate grace default. The bus holds both as literals
|
||||
// (packages/bus/src/model-keys.mjs #issue: 30 days to rotateBy; packages/bus/src/runtime.mjs:
|
||||
// `proxy.rotateGraceMinutes ?? 120`) and exports neither, and this lane may not change the bus.
|
||||
// packages/cli/tests/triage-key.test.mjs drives the bus's own ModelKeys with the same clock and
|
||||
// proves these give the same rotateBy and retireAt, so a change on either side goes red there.
|
||||
// The grace itself is read from proxy.json first, where the bus reads it.
|
||||
export const KEY_LIFETIME_DAYS = 30;
|
||||
export const DEFAULT_ROTATE_GRACE_MINUTES = 120;
|
||||
const sentinelPrefix = (configDir) => `msk-${instanceTag(configDir)}-sentinel-`;
|
||||
// Any name under the prefix is Triage's to remove, well formed or not, as the bus treats its own
|
||||
// `msk-<tag>-` names. Only a well-formed key may be stored in the file.
|
||||
const inNamespace = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir));
|
||||
|
||||
// Both directories, checked (and the triage one made) before any proxy write, so a store that cannot
|
||||
// be written refuses while the proxy is still untouched.
|
||||
function prepareDirs(configDir, uid) {
|
||||
const { secrets, dir } = keyPaths(configDir);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) throw unreadable("the secrets directory is missing");
|
||||
checkDir(dir, uid, "the triage secrets directory", { create: true });
|
||||
}
|
||||
|
||||
// A temp file writeKey left when it was killed before its rename. It may hold a key.
|
||||
const TEMP = /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/;
|
||||
const tempsIn = (dir) => { try { return readdirSync(dir).filter((n) => TEMP.test(n)); } catch { return []; } };
|
||||
// Under the lock no other Triage writer runs, so every temp file left in the directory is dead.
|
||||
function removeTemps(configDir) {
|
||||
const { dir } = keyPaths(configDir);
|
||||
for (const name of tempsIn(dir)) {
|
||||
try { if (!lstatSync(join(dir, name)).isDirectory()) unlinkSync(join(dir, name)); }
|
||||
catch { throw unreadable("a leftover temp file in the triage secrets directory cannot be removed"); }
|
||||
}
|
||||
}
|
||||
|
||||
// A directory sync that failed after the rename: the file is in place but may not be durable.
|
||||
class NotSynced extends Error {}
|
||||
|
||||
// Atomic: a 0600 temp file in the same directory, fsync, rename, fsync of the directory.
|
||||
function writeKey(configDir, record, uid, hook = () => {}) {
|
||||
const { dir, file } = keyPaths(configDir);
|
||||
prepareDirs(configDir, uid);
|
||||
const temp = join(dir, `.model.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
||||
let fd;
|
||||
try { fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
||||
catch { throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
try { fchmodSync(fd, 0o600); writeSync(fd, `${JSON.stringify(record, null, 2)}\n`); fsyncSync(fd); }
|
||||
finally { closeSync(fd); }
|
||||
hook("rename");
|
||||
renameSync(temp, file);
|
||||
} catch { try { unlinkSync(temp); } catch {} throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
hook("sync");
|
||||
const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try { fsyncSync(dfd); } finally { closeSync(dfd); }
|
||||
} catch { throw new NotSynced(); }
|
||||
}
|
||||
|
||||
// One line per write in the proxy lock's receipts file, ids only. `receiptsReady` runs under the
|
||||
// lock before any change, so an unsafe receipts file refuses while nothing has changed yet.
|
||||
const RECEIPTS_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
||||
const receiptsUnsafe = (why) => new TriageKeyError("triage-key-receipts-unsafe", `${why}; nothing was changed`);
|
||||
function receiptsReady(stateDir, uid) {
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); }
|
||||
catch { throw receiptsUnsafe("the proxy receipts file cannot be opened"); }
|
||||
try { checkFile(fd, uid, "the proxy receipts file", receiptsUnsafe); } finally { closeSync(fd); }
|
||||
}
|
||||
function receipt(stateDir, uid, entry) {
|
||||
const unrecorded = new TriageKeyError("triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status");
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); } catch { throw unrecorded; }
|
||||
try {
|
||||
checkFile(fd, uid, "the proxy receipts file", () => unrecorded);
|
||||
writeSync(fd, `${JSON.stringify(entry)}\n`);
|
||||
fsyncSync(fd);
|
||||
} catch { throw unrecorded; }
|
||||
finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
// The grace the bus uses: proxy.json's rotateGraceMinutes, or the bus default.
|
||||
export const graceMinutes = (proxy) => proxy?.rotateGraceMinutes ?? DEFAULT_ROTATE_GRACE_MINUTES;
|
||||
export const rotateByFor = (nowMs) => new Date(nowMs + KEY_LIFETIME_DAYS * 86400_000).toISOString().slice(0, 10);
|
||||
export const retireAtFor = (nowMs, proxy) => new Date(nowMs + graceMinutes(proxy) * 60_000).toISOString();
|
||||
|
||||
const proxyFailure = (code) => {
|
||||
const words = {
|
||||
"proxy-lock-busy": "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status",
|
||||
"proxy-lock-uncertain": "the instance proxy lock is in a state this verb will not guess about; check <dataRoot>/proxy by hand",
|
||||
"proxy-lock-invalid": "the instance proxy lock directory is missing or unsafe, or names another proxy",
|
||||
"proxy-uncertain": "an earlier proxy write has an uncertain outcome; see mosaic proxy fence status",
|
||||
"proxy-management-key-invalid": "the proxy management key file is missing or unsafe",
|
||||
"proxy-client-invalid": "the proxy settings are not usable",
|
||||
"proxy-client-down": "the proxy did not answer",
|
||||
"proxy-client-refused": "the proxy refused the management request",
|
||||
"proxy-client-redirect": "the proxy answered with a redirect",
|
||||
"proxy-client-response": "the proxy gave an answer this verb cannot use",
|
||||
};
|
||||
return new TriageKeyError(code, words[code] ?? "the proxy write failed");
|
||||
};
|
||||
|
||||
// opts.uid, opts.now and opts.hook(stage) are test seams; a stage hook may throw or kill the process.
|
||||
// opts.client and opts.lock: the bus passes its own management client and instance proxy lock, so a
|
||||
// bus change runs under the lock object its model key sweep uses and reads no key file of its own.
|
||||
function context({ configDir, system, uid, fileUid, now, hook, client, lock }) {
|
||||
if (!system?.proxy || !Number.isInteger(system.proxy.port)) throw new TriageKeyError("triage-key-no-proxy", "the instance has no model proxy set up (proxy.json)");
|
||||
return {
|
||||
configDir, dataRoot: system.dataRoot, proxy: system.proxy, stateDir: join(system.dataRoot, "proxy"),
|
||||
uid: uid ?? process.getuid(), fileUid, now: now ?? Date.now, hook: hook ?? (() => {}), client, lock,
|
||||
};
|
||||
}
|
||||
|
||||
function lockFor(c) {
|
||||
if (c.lock) return c.lock;
|
||||
try { return createProxyLock({ stateDir: c.stateDir, identity: `${c.configDir}:${c.proxy.port}` }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-lock-invalid"); }
|
||||
}
|
||||
|
||||
async function clientFor(c) {
|
||||
if (c.client) return c.client;
|
||||
try { return await loadManagementClient({ configDir: c.configDir, proxy: c.proxy }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-management-key-invalid"); }
|
||||
}
|
||||
|
||||
function checkSentinel(c, keys) {
|
||||
const prefix = sentinelPrefix(c.configDir);
|
||||
if (!keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length)))) {
|
||||
throw new TriageKeyError("triage-key-proxy-open", "the proxy's key list has no sentinel for this instance, so it may be another proxy");
|
||||
}
|
||||
}
|
||||
|
||||
// Under the instance proxy lock: read the list, check the sentinel, run `plan`, write the result.
|
||||
// `plan(keys, record)` returns { after, record, remove, op, done }; `record` null leaves the file
|
||||
// alone, `remove` true unlinks it (revoke), `op` names the change when the plan picks it (sweep).
|
||||
// The proxy changes first, then the file, then one receipt line.
|
||||
async function change(c, opName, plan) {
|
||||
const lock = lockFor(c);
|
||||
const client = await clientFor(c);
|
||||
try {
|
||||
return await lock.run(async () => {
|
||||
const before = await client.getKeys();
|
||||
checkSentinel(c, before);
|
||||
const current = readKey(c.configDir, { uid: c.uid, fileUid: c.fileUid });
|
||||
const result = plan(before, current);
|
||||
const op = result.op ?? opName;
|
||||
const remove = result.remove === true && current !== null;
|
||||
if (result.record) prepareDirs(c.configDir, c.uid);
|
||||
removeTemps(c.configDir);
|
||||
receiptsReady(c.stateDir, c.uid);
|
||||
const after = result.after;
|
||||
const removed = before.filter((k) => !after.includes(k));
|
||||
const added = after.filter((k) => !before.includes(k));
|
||||
// A key in another namespace never leaves the list.
|
||||
if (removed.some((k) => !inNamespace(c.configDir)(k))) throw new TriageKeyError("triage-key-failed", "the change would remove a key outside the Triage namespace");
|
||||
if (added.length || removed.length) {
|
||||
// As the bus does: a list that moved since the first read is not overwritten.
|
||||
if (!isDeepStrictEqual(await client.getKeys(), before)) throw new TriageKeyError("triage-key-raced", "the proxy's key list changed while this verb ran; run it again");
|
||||
lock.fence({ org: null, op: `triage.${op}` });
|
||||
await client.putKeys(after);
|
||||
c.hook("put");
|
||||
const confirmed = await client.getKeys();
|
||||
if (!confirmed.some((k) => k.startsWith(sentinelPrefix(c.configDir))) || added.some((k) => !confirmed.includes(k)) || removed.some((k) => confirmed.includes(k))) {
|
||||
throw new TriageKeyError("triage-key-unconfirmed", "the proxy did not confirm the change; the instance proxy fence stays set, see mosaic proxy fence status");
|
||||
}
|
||||
lock.confirm();
|
||||
}
|
||||
c.hook("write");
|
||||
let unsynced = false;
|
||||
if (result.record || remove) {
|
||||
try { if (remove) unlinkKey(c.configDir, c.hook); else writeKey(c.configDir, result.record, c.uid, c.hook); }
|
||||
catch (e) {
|
||||
if (e instanceof NotSynced) unsynced = true;
|
||||
else throw new TriageKeyError("triage-key-unwritten", `the proxy list changed but ${keyPaths(c.configDir).file} was not written (${e.message}); fix the file's directory, then run mosaic triage key ${op} again, which clears what this run left`);
|
||||
}
|
||||
}
|
||||
c.hook("receipt");
|
||||
// A run that changed neither the proxy nor the file leaves no receipt.
|
||||
if (added.length || removed.length || result.record || remove) receipt(c.stateDir, c.uid, { op: `triage.key.${op}`, time: new Date(c.now()).toISOString(), addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) });
|
||||
// The file is in place and the receipt written; only its durability is in doubt.
|
||||
if (unsynced) throw new TriageKeyError("triage-key-unsynced", `${keyPaths(c.configDir).file} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status`);
|
||||
return { ...result.done, addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) };
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof TriageKeyError) throw e;
|
||||
throw proxyFailure(typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "triage-key-failed");
|
||||
}
|
||||
}
|
||||
|
||||
// Revoke's file step: unlink, then sync the directory, with writeKey's stages and failures.
|
||||
function unlinkKey(configDir, hook = () => {}) {
|
||||
const { dir, file } = keyPaths(configDir);
|
||||
try { hook("rename"); unlinkSync(file); }
|
||||
catch (e) { if (e?.code !== "ENOENT") throw unreadable("the key file cannot be removed"); }
|
||||
try {
|
||||
hook("sync");
|
||||
const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try { fsyncSync(dfd); } finally { closeSync(dfd); }
|
||||
} catch { throw new NotSynced(); }
|
||||
}
|
||||
|
||||
const newKey = (configDir) => keyPrefix(configDir) + randomBytes(32).toString("base64url");
|
||||
|
||||
// Keys in the Triage namespace that the file does not hold: left by a crash between the PUT and the
|
||||
// file write, or by a file that was removed by hand.
|
||||
const orphansOf = (configDir, keys, record) => {
|
||||
const held = record ? [record.key, ...record.retiring.map((r) => r.key)] : [];
|
||||
return keys.filter((k) => inNamespace(configDir)(k) && !held.includes(k));
|
||||
};
|
||||
|
||||
export async function issueKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "issue", (before, current) => {
|
||||
if (current) throw new TriageKeyError("triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate");
|
||||
const orphans = orphansOf(c.configDir, before, null);
|
||||
const key = newKey(c.configDir), nowMs = c.now();
|
||||
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring: [] };
|
||||
return { after: [...before.filter((k) => !orphans.includes(k)), key], record, done: { keyId: record.keyId, rotateBy: record.rotateBy } };
|
||||
});
|
||||
}
|
||||
|
||||
// Retiring keys whose grace (plus marginMs, 0 for the terminal verbs) has passed, or that the proxy
|
||||
// no longer holds.
|
||||
const dueOf = (record, keys, nowMs, marginMs = 0) => record.retiring.filter((r) => Date.parse(r.retireAt) + marginMs <= nowMs || !keys.includes(r.key));
|
||||
const rotateDueAt = (record) => Date.parse(`${record.rotateBy}T00:00:00Z`);
|
||||
|
||||
// The rotate plan, shared by the terminal verb and the sweep.
|
||||
function rotatePlan(c, before, current, nowMs, marginMs = 0) {
|
||||
const orphans = orphansOf(c.configDir, before, current);
|
||||
const due = dueOf(current, before, nowMs, marginMs);
|
||||
const keep = before.includes(current.key);
|
||||
const retiring = [...current.retiring.filter((r) => !due.includes(r)),
|
||||
...(keep ? [{ key: current.key, keyId: current.keyId, issuedAt: current.issuedAt, retireAt: retireAtFor(nowMs, c.proxy) }] : [])];
|
||||
if (retiring.length > MAX_RETIRING) throw new TriageKeyError("triage-key-failed", "too many keys are retiring; run mosaic triage key retire once their grace has passed");
|
||||
const key = newKey(c.configDir);
|
||||
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
|
||||
const drop = [...orphans, ...due.map((r) => r.key)];
|
||||
return {
|
||||
after: [...before.filter((k) => !drop.includes(k)), key], record,
|
||||
done: { keyId: record.keyId, rotateBy: record.rotateBy, old: keep ? { keyId: current.keyId, retireAt: retiring.at(-1).retireAt } : { keyId: current.keyId, lost: true } },
|
||||
};
|
||||
}
|
||||
|
||||
export async function rotateKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "rotate", (before, current) => {
|
||||
if (!current) throw new TriageKeyError("triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue");
|
||||
return rotatePlan(c, before, current, c.now());
|
||||
});
|
||||
}
|
||||
function retirePlan(c, before, current, nowMs, marginMs = 0) {
|
||||
const orphans = orphansOf(c.configDir, before, current);
|
||||
const due = current ? dueOf(current, before, nowMs, marginMs) : [];
|
||||
const record = current && due.length ? { ...current, retiring: current.retiring.filter((r) => !due.includes(r)) } : null;
|
||||
const drop = [...orphans, ...due.map((r) => r.key)];
|
||||
return { after: before.filter((k) => !drop.includes(k)), record, done: { droppedKeyIds: due.map((r) => r.keyId) } };
|
||||
}
|
||||
|
||||
export async function retireKeys(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "retire", (before, current) => retirePlan(c, before, current, c.now()));
|
||||
}
|
||||
|
||||
// proxy-scope slice 4: the bus verb proxy.triage.key op ensure. Leaves a held key alone, issues one
|
||||
// when none exists, replaces one the proxy lost. Never prints the key; the answer is ids only.
|
||||
// issued no file: a new key (keys in the namespace the file does not hold are removed)
|
||||
// held the proxy holds the file's key: only orphans and retiring keys the proxy lost go
|
||||
// replaced the proxy does not hold the file's key: a new key, the old one marked lost
|
||||
export async function ensureKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "ensure", (before, current) => {
|
||||
const nowMs = c.now();
|
||||
const orphans = orphansOf(c.configDir, before, current);
|
||||
const fresh = (retiring) => {
|
||||
const key = newKey(c.configDir);
|
||||
return { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
|
||||
};
|
||||
if (!current) {
|
||||
const record = fresh([]);
|
||||
return { after: [...before.filter((k) => !orphans.includes(k)), record.key], record, done: { action: "issued", keyId: record.keyId, rotateBy: record.rotateBy } };
|
||||
}
|
||||
const lost = current.retiring.filter((r) => !before.includes(r.key));
|
||||
const retiring = current.retiring.filter((r) => !lost.includes(r));
|
||||
if (before.includes(current.key)) {
|
||||
return {
|
||||
after: before.filter((k) => !orphans.includes(k)), record: lost.length ? { ...current, retiring } : null,
|
||||
done: { action: "held", keyId: current.keyId, rotateBy: current.rotateBy },
|
||||
};
|
||||
}
|
||||
const record = fresh(retiring);
|
||||
return {
|
||||
after: [...before.filter((k) => !orphans.includes(k)), record.key], record,
|
||||
done: { action: "replaced", keyId: record.keyId, rotateBy: record.rotateBy, old: { keyId: current.keyId, lost: true } },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// proxy-scope slice 4: op revoke, when the owner turns Triage off. Every name in this instance's
|
||||
// Triage namespace leaves the proxy list, then the key file goes. No file and no names: nothing.
|
||||
export async function revokeKeys(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "revoke", (before, current) => {
|
||||
const mine = before.filter(inNamespace(c.configDir));
|
||||
return { after: before.filter((k) => !mine.includes(k)), record: null, remove: true, done: { action: mine.length || current ? "revoked" : "none" } };
|
||||
});
|
||||
}
|
||||
|
||||
// What a sweep would do from the file alone: "rotate" when rotateBy has come, "retire" when a
|
||||
// retiring key's grace plus marginMs has passed, else null. A cheap check without the lock or the
|
||||
// proxy; sweepKeys decides again under the lock.
|
||||
export function sweepDue(record, nowMs, marginMs = 0) {
|
||||
if (!record) return null;
|
||||
if (rotateDueAt(record) <= nowMs) return "rotate";
|
||||
return record.retiring.some((r) => Date.parse(r.retireAt) + marginMs <= nowMs) ? "retire" : null;
|
||||
}
|
||||
|
||||
// The bus sweep. Under the instance proxy lock it reads the file again and acts only if the action
|
||||
// is still due, so two buses that wake together change the proxy once. No file: nothing, ever.
|
||||
export async function sweepKeys(opts, { marginMs = 0 } = {}) {
|
||||
const c = context(opts);
|
||||
return change(c, "sweep", (before, current) => {
|
||||
const nowMs = c.now();
|
||||
const due = sweepDue(current, nowMs, marginMs);
|
||||
if (due === "rotate") {
|
||||
const plan = rotatePlan(c, before, current, nowMs, marginMs);
|
||||
return { ...plan, op: "rotate", done: { action: "rotated", ...plan.done } };
|
||||
}
|
||||
if (due === "retire") {
|
||||
const plan = retirePlan(c, before, current, nowMs, marginMs);
|
||||
return { ...plan, op: "retire", done: { action: "retired", ...plan.done } };
|
||||
}
|
||||
return { after: before, record: null, done: { action: "none" } };
|
||||
});
|
||||
}
|
||||
|
||||
// Read only: the file, and when the proxy is set up, what its list holds. No lock, no write.
|
||||
// The fence is checked by name only, so status writes nothing, not even the lock's identity file.
|
||||
export async function keyStatus(opts) {
|
||||
const { configDir, system, uid, fileUid } = opts;
|
||||
const record = readKey(configDir, { uid, fileUid });
|
||||
const proxy = { state: "not-set-up", fence: false, leftoverTemps: tempsIn(keyPaths(configDir).dir).length };
|
||||
if (system?.proxy && Number.isInteger(system.proxy.port)) {
|
||||
try { lstatSync(join(system.dataRoot, "proxy", "mosaic-keys.uncertain")); proxy.fence = true; }
|
||||
catch (e) { if (e.code !== "ENOENT") proxy.fence = true; }
|
||||
try {
|
||||
const client = await loadManagementClient({ configDir, proxy: system.proxy });
|
||||
const keys = await client.getKeys();
|
||||
const prefix = sentinelPrefix(configDir);
|
||||
proxy.state = keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length))) ? "read" : "no-sentinel";
|
||||
proxy.holdsKey = record ? keys.includes(record.key) : null;
|
||||
proxy.retiringHeld = record ? record.retiring.map((r) => keys.includes(r.key)) : [];
|
||||
proxy.orphanKeyIds = orphansOf(configDir, keys, record).map(keyIdOf);
|
||||
} catch (e) { proxy.state = "unreadable"; proxy.code = typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "proxy-client-response"; }
|
||||
}
|
||||
return { record, proxy };
|
||||
}
|
||||
@@ -42,7 +42,8 @@ const baselines = {
|
||||
// deadline; userCall shares transport(). Nonces, argv and limits are unchanged.
|
||||
// #1873 A3: STATUS maps credential-unbound, copy-refused, project-refused and project-agent-elsewhere
|
||||
// to 409; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "d8f3e0eb5299fdb192e98a1238ca693aae7c36af9a21de72d5f5d39610589377",
|
||||
// #1873 triage-fence: STATUS maps template-system-only to 400; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "cd08e1beb49e9e881bb1b308f2ab3343a480b47dd9b17ccbd16e120d341d7511",
|
||||
};
|
||||
const repoFile = path => new URL("../../../" + path, import.meta.url);
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { checkedTransport } from '../../harness/src/bundle.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only. A stored route that puts an
|
||||
// OAuth Claude model on pi is refused at launch admission with model-harness-incompatible, even when a stale
|
||||
// catalogue row still says pi. A z.ai and a codex model are admitted on pi.
|
||||
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: { authority: { withinRole: [], crossRole: [] } } };
|
||||
|
||||
async function admission(t, entry, catalogueRow) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'harness-matrix-')); t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const rolesDir = rolesCopy(root), doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { ...doc.plugins, harness: ['pi'], 'model-provider': ['cliproxy'] };
|
||||
doc.launch.models['fixture-key'] = entry;
|
||||
doc.roles.coder.vars = { ...doc.roles.coder.vars, harness: 'pi', model: 'fixture-key', thinking: 'low' };
|
||||
writeJson(join(root, 'businesses/demo.json'), doc); mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const modelCatalogue = { invalidate() {}, read: async () => ({ status: 'ready', notices: [], models: [{ module: 'cliproxy', available: true, ...catalogueRow }] }) };
|
||||
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles } }, organization: { dir: root, rolesDir, system: systemFor(root) }, modelCatalogue });
|
||||
t.after(() => bus.close());
|
||||
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const revision = bus.broker.request(human, { verb: 'limits' }).revision;
|
||||
// The launcher's own transport check refuses first; admission is the second gate, so the request
|
||||
// carries the transport the provider would give with no harness named.
|
||||
const transport = checkedTransport(entry);
|
||||
return bus.modelAdmission({ business: 'demo', instance: 'coder', modelKey: 'fixture-key', harness: 'pi', revision, entry, provider: entry.provider, model: entry.model, account: null, route: 'primary', transport });
|
||||
}
|
||||
|
||||
test('#1873 a stored Claude route on pi is refused model-harness-incompatible at admission, even with a stale catalogue row that says pi', async t => {
|
||||
const entry = { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' };
|
||||
assert.deepEqual(await admission(t, entry, { upstream: 'claude', model: 'claude-opus-5-5', harnesses: ['claude-code', 'pi'] }), { allow: false, code: 'model-harness-incompatible' });
|
||||
});
|
||||
|
||||
test('#1873 a Claude model from an API-key group (upstream other) is admitted on pi; one whose name an OAuth account offers is refused', async t => {
|
||||
const entry = { provider: 'other', model: 'anthropic/claude-sonnet-5-5', module: 'cliproxy', upstream: 'other' };
|
||||
assert.deepEqual(await admission(t, entry, { upstream: 'other', model: 'anthropic/claude-sonnet-5-5', harnesses: ['claude-code', 'pi'] }), { allow: true });
|
||||
// The catalogue holds a group model to claude-code when an OAuth Claude account offers its name.
|
||||
assert.deepEqual(await admission(t, entry, { upstream: 'other', model: 'anthropic/claude-sonnet-5-5', harnesses: ['claude-code'] }), { allow: false, code: 'model-harness-incompatible' });
|
||||
});
|
||||
|
||||
test('#1873 a z.ai and a codex model are admitted on pi', async t => {
|
||||
for (const [provider, upstream, model] of [['zai', 'zai', 'glm-fixture'], ['codex', 'codex', 'gpt-fixture']]) {
|
||||
const entry = { provider, model, module: 'cliproxy', upstream };
|
||||
assert.deepEqual(await admission(t, entry, { upstream, model, harnesses: ['claude-code', 'pi'] }), { allow: true }, provider);
|
||||
}
|
||||
});
|
||||
@@ -27,7 +27,9 @@ export async function ownershipFixture(t,{launches=true,listed=true,keep=false,r
|
||||
// Available before any acquired resource/setup can fail; no later f/launcher TDZ.
|
||||
const launchLog=()=>{const file=launchLogFile(join(root,'data'),'acme');return fs.existsSync(file)?fs.readFileSync(file,'utf8').trim().split('\n').filter(Boolean).map(line=>JSON.parse(line)):[];};
|
||||
t.after(async()=>{const failures=[];for(const g of gates)g.release();try{await waitFor(()=>active.size===0,'owned operations did not settle',5000);}catch{failures.push('owned-operation-close');}for(const close of [...closers].reverse()){try{await close();}catch{failures.push('owned-close');}}try{server?.closeAllConnections();if(server?.listening)await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));}catch{failures.push('owned-server-close');}try{checkHistory({logs,proxyReceipts,trace});}catch{failures.push('value-free-receipts');}try{checkHistory({launch:launchLog()});}catch{failures.push('owned-launch-log-guard');}if(stderr)process.stderr.write=stderr;try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('owned-root-close');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned managed fixture cleanup failed');});
|
||||
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:['pi']};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness:'pi'};doc.roles.chief.vars.model='claude-opus-5-5';doc.roles.aide={definition:'aide',vars:{harness:'pi',model:'claude-opus-5-5',thinking:'high'}};if(listed)doc.launch.instances.push('aide');if(keep)doc.launch.keep=['aide'];if(retired)doc.retired=['alpha'];if(noHire)doc.launch.noHire=['aide'];if(!listed)delete doc.roles.aide;return doc;});
|
||||
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:['pi']};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness:'pi'};doc.roles.chief.vars.model='claude-opus-5-5';doc.roles.aide={definition:'aide',vars:{harness:'pi',model:'claude-opus-5-5',thinking:'high'}};if(listed)doc.launch.instances.push('aide');if(keep)doc.launch.keep=['aide'];if(retired)doc.retired=['alpha'];if(noHire)doc.launch.noHire=['aide'];if(!listed)delete doc.roles.aide;doc.launch.models['claude-opus-5-5']={provider:'zai',model:'fixture-aide-model'};return doc;});
|
||||
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so on pi the model key
|
||||
// claude-opus-5-5 names a non-Claude upstream model.
|
||||
// The established scratch aide pattern only; repository roles/policy stay untouched.
|
||||
for(const name of ['aide','helper']){fs.writeFileSync(join(f.roles,name+'.md'),'# Scratch aide\n\n## Authority\n');writeJson(join(f.roles,name+'.json'),{roleVersion:2,name,title:'Aide',contract:name+'.md',tools:['read'],network:'api-only',authority:{withinRole:['message.send'],crossRole:[]},credentials:[]});}
|
||||
const chiefFile=join(f.roles,'chief-of-staff.json');
|
||||
@@ -74,6 +76,7 @@ export async function ownershipFixture(t,{launches=true,listed=true,keep=false,r
|
||||
case 'landRelease':return bus.landRelease(m.record);
|
||||
case 'threadsState':return bus.threadsState(m.business);
|
||||
case 'threadIdle':return bus.threadIdle(m.record);
|
||||
case 'failureNotice':return bus.failureNotice(m.record);
|
||||
case 'lifecycleRequests':return bus.lifecycleRequests(m.business);
|
||||
case 'lifecycleTake':return bus.lifecycleTake(m.record);
|
||||
case 'lifecycleDelete':return bus.lifecycleDelete(m.record);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { join } from 'node:path';
|
||||
import { sandboxProblem } from '../../seat/src/sandbox.mjs';
|
||||
import { startTimeOf } from '../../seat/src/proc.mjs';
|
||||
import { ownershipFixture, waitFor } from './model-hire-ownership-fixture.mjs';
|
||||
import * as pi from '../../plugins/harness/pi/index.mjs';
|
||||
const unavailable=sandboxProblem()??false; // Any skip means UNVERIFIED, not green acceptance.
|
||||
const done=async box=>{await box.promise;return box;};
|
||||
const refused=async(box,code)=>{await done(box);assert.equal(box.ok,false,'real operation refuses');assert.equal(box.code,code,'real operation preserves exact refusal');};
|
||||
@@ -17,7 +18,12 @@ test('655 listed duplicate with no record refuses before any model or management
|
||||
assert.deepEqual(f.snapshot(),before,'duplicate hire makes no credential or management effects');f.assertHistoryGuard();f.valueFree();
|
||||
});
|
||||
|
||||
test('655 actual launch own preflight generation and bound consumer survive concurrent duplicate hire',{skip:unavailable,timeout:30000},async t=>{
|
||||
test('655 actual launch own preflight generation and bound consumer survive concurrent duplicate hire',{skip:unavailable,timeout:120000},async t=>{
|
||||
// #1873 pi-unpin re-check 9 and 10: the launch's preflight shares pi's fit check, which is cold in
|
||||
// a fresh process. Wait for it before the fixture starts its launcher, so the launcher's warm-up
|
||||
// and the launch's preflight hit the cache, the gate's 5 s times the launch, and the launch starts
|
||||
// at the same point in the launcher's 2 s tick as it did before the fit check existed.
|
||||
await pi.ready({env:{PATH:process.env.PATH,HOME:process.env.HOME,TMPDIR:process.env.TMPDIR}});
|
||||
const f=await ownershipFixture(t),pGet=f.hold('GET'),p=f.launchAide();await pGet.entered();
|
||||
// P's own acquisition GET is held. Its PUT confirmation GET is ordinal+1;
|
||||
// only an OLD H reuse GET can be ordinal+2. The correct early refusal removes it.
|
||||
|
||||
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { Credentials } from '../src/credentials.mjs';
|
||||
import { ManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { ModelKeys, REVOKE_TIMEOUT_MS, REVOKE_POLL_MS } from '../src/model-keys.mjs';
|
||||
import { ModelKeys, REVOKE_TIMEOUT_MS, REVOKE_POLL_MS, ISSUE_PROBE_TIMEOUT_MS, ISSUE_REPROBE_MIN_MS } from '../src/model-keys.mjs';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
@@ -42,6 +42,7 @@ async function fixture(t, { delayed = 0 } = {}) {
|
||||
const key = req.headers.authorization?.slice(7);
|
||||
const accepted = state.keys.includes(key) || (state.removed.has(key) && performance.now() - state.removed.get(key) < state.delay);
|
||||
state.onProbe?.(state.status ?? (accepted ? 200 : 401));
|
||||
if (state.stallProbe?.()) return;
|
||||
res.writeHead(state.status ?? (accepted ? 200 : 401)); res.end('{}');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
@@ -123,10 +124,33 @@ test('proxy-revoke-revision-conflict keeps local revoking record and ids-only re
|
||||
assert.equal(JSON.stringify(f.receipts).includes(key), false);
|
||||
await f.create().reconcile(); assert.equal(f.credentials.modelRecord('demo/coder') === null, true);
|
||||
});
|
||||
for (const status of [401, 503, 302]) test(`proxy-key-refused: preflight rejects HTTP ${status} with exactly one probe`, async t => {
|
||||
for (const status of [503, 302]) test(`proxy-key-refused: preflight rejects HTTP ${status} with exactly one probe`, async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = status;
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-key-refused')); assert.equal(f.state.probes, 1);
|
||||
});
|
||||
test('proxy-key-refused: a key that keeps answering 401 refuses once the short probe deadline passes', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = 401;
|
||||
const started = performance.now();
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-key-refused'));
|
||||
const took = performance.now() - started;
|
||||
assert.ok(f.state.probes > 1, 'a 401 is probed again'); assert.ok(took >= ISSUE_PROBE_TIMEOUT_MS && took < ISSUE_PROBE_TIMEOUT_MS + 2000, `bounded: ${took}`);
|
||||
});
|
||||
test('proxy-down: a re-probe that stalls ends near the probe deadline, not the client default', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = 401;
|
||||
f.state.stallProbe = () => f.state.probes >= 2;
|
||||
const started = performance.now();
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-down'));
|
||||
const took = performance.now() - started;
|
||||
assert.equal(f.state.probes, 2); assert.ok(took < ISSUE_PROBE_TIMEOUT_MS + ISSUE_REPROBE_MIN_MS + 1000, `bounded: ${took}`);
|
||||
});
|
||||
// Every v8 CLIProxyAPI applies the PUT by an async reload; on 8.0.79 a just-issued key answers 401
|
||||
// past the confirming GET (#1873).
|
||||
test('first launch passes when the proxy applies the new key a moment after the PUT answers', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); f.state.status = 401;
|
||||
f.state.onProbe = () => { if (f.state.probes === 3) f.state.status = null; };
|
||||
const answer = await f.manager.preflight('demo/coder');
|
||||
assert.equal(f.state.probes, 3); assert.equal(f.state.keys.includes(answer.key), true);
|
||||
});
|
||||
test('rotate keeps old key while its run lives, new launches use new, exit removes old', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); const first = await f.manager.ensure('demo/coder');
|
||||
f.runs.push({ instance: 'demo/coder', run: 'old', keyId: hash(first.key) });
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// #1873 pickup-launch: a bus that picked up the shared proxy late serves accounts and a ready
|
||||
// catalogue, but a launch on a proxy model still needs a restart (no ModelKeys on the bus, no proxy
|
||||
// in the host launcher's boot system). While it holds such a client, its catalogue answer says so
|
||||
// in one plain notice, and a launch refuses exactly as before. A refused or dropped client shows
|
||||
// its cause instead. Real buses, a real launcher whose model ops go to the bus, a fake loopback
|
||||
// management server; no live config.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { createProxyLock } from '../src/proxy-lock.mjs';
|
||||
import { Registry, launchLogFile } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { PIN } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy, installPaths, loadProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { createLauncher } from '../../cli/src/launcher.mjs';
|
||||
import { initializeControl } from '../../processing-control/src/state.mjs';
|
||||
import { ZAI_URL } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
import { fakeHarnesses, humanEnv, withoutHostCredentials } from '../../cli/tests/helpers.mjs';
|
||||
import { REPO_SKILLS } from '../../harness/tests/helpers.mjs';
|
||||
|
||||
const RESTART = 'Restart this organization to start agents on these models.';
|
||||
const MODEL = 'claude-claude-opus-5-5';
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
// A loopback stand-in for the proxy's management API: one ready Claude account with one model,
|
||||
// and an access key list that keeps what a PUT sends, so a boot ModelKeys reconciles against it.
|
||||
async function fakeProxy(t, key, port = 0, { groups = [] } = {}) {
|
||||
const seen = { calls: 0, wrongKey: 0 };
|
||||
let accessKeys = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
seen.calls++;
|
||||
if (req.headers.authorization !== `Bearer ${key}`) { seen.wrongKey++; res.writeHead(401); res.end('{}'); return; }
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
if (url.pathname === '/v8/management/config/access/api-keys' && req.method === 'PUT') {
|
||||
const chunks = [];
|
||||
req.on('data', c => chunks.push(c));
|
||||
req.on('end', () => { accessKeys = JSON.parse(Buffer.concat(chunks)); res.end(JSON.stringify({ status: 'ok' })); });
|
||||
return;
|
||||
}
|
||||
const answer = url.pathname === '/v8/management/credentials' ? { files: [{ id: 'acct-1', name: 'acct-1', provider: 'claude', status: 'ready', priority: 1 }] }
|
||||
: url.pathname === '/v8/management/credentials/models' ? { models: [{ id: 'claude-opus-5-5' }] }
|
||||
: url.pathname === '/v8/management/config/api-keys/claude' ? groups
|
||||
: url.pathname === '/v8/management/config/access/api-keys' ? accessKeys
|
||||
: null;
|
||||
if (answer === null) { res.writeHead(404); res.end('{}'); return; }
|
||||
res.end(JSON.stringify(answer));
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
|
||||
return { port: server.address().port, seen, server };
|
||||
}
|
||||
|
||||
// One instance (config dir + data root) and a fake proxy install whose bytes a test pin names.
|
||||
function instance(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pl-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'instance');
|
||||
fs.mkdirSync(join(configDir, 'secrets', 'agents'), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(join(configDir, 'secrets'), 0o700);
|
||||
fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const paths = installPaths(dataRoot);
|
||||
fs.mkdirSync(join(paths.dir, 'static'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(paths.binary, 'fixture proxy binary\n', { mode: 0o700 });
|
||||
fs.writeFileSync(paths.panel, '<!doctype html>\n', { mode: 0o600 });
|
||||
const pin = { ...PIN, binary: { ...PIN.binary, sha256: sha('fixture proxy binary\n') }, panel: { ...PIN.panel, sha256: sha('<!doctype html>\n') } };
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const key = `pl1873-${randomBytes(24).toString('hex')}`;
|
||||
return { root, configDir, dataRoot, paths, pin, rolesDir, system, key };
|
||||
}
|
||||
|
||||
// A real organization bus on the instance, started with no proxy unless `binding.proxy` gives one.
|
||||
async function orgBus(t, f, id, { providers = ['cliproxy'], binding = {} } = {}) {
|
||||
const doc = businessDoc(f.root, id);
|
||||
// The coder's model is a Claude model on a legacy entry, which counts as OAuth and runs on
|
||||
// claude-code only, so the organization enables claude-code.
|
||||
doc.plugins = { harness: ['claude-code'], 'model-provider': providers };
|
||||
writeJson(join(f.configDir, 'businesses', `${id}.json`), doc);
|
||||
const business = loadBusiness(id, { dir: f.configDir, rolesDir: f.rolesDir }), resolved = {};
|
||||
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system: f.system, business, instance: name });
|
||||
const dataRoot = join(f.root, `${id}-bus`); fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
|
||||
const bus = await startBroker({ dataRoot, businesses: { [id]: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir: f.rolesDir, system: f.system },
|
||||
instanceRoot: f.dataRoot, org: { id }, instanceDataRoot: f.dataRoot, instanceConfigDir: f.configDir,
|
||||
initProxy: args => initializeProxy({ ...args, pin: f.pin }), ...binding });
|
||||
t.after(() => bus.close().catch(() => {}));
|
||||
const human = bus.broker.bindHuman({ business: id, human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const ask = (verb, args) => Promise.resolve().then(() => bus.broker.request(human, { verb, args }));
|
||||
return { id, bus, ask, dataRoot };
|
||||
}
|
||||
|
||||
// Every stderr line written while `run` is in flight.
|
||||
async function capture(run) {
|
||||
const write = process.stderr.write, lines = [];
|
||||
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
|
||||
try { return { value: await run(), lines }; } finally { process.stderr.write = write; }
|
||||
}
|
||||
|
||||
async function initThroughA(t, f, a, options) {
|
||||
const settings = await a.ask('proxy.init', { key: f.key });
|
||||
const proxy = await fakeProxy(t, f.key, settings.port, options);
|
||||
return { settings, proxy };
|
||||
}
|
||||
|
||||
// The owner picks the catalogue's proxy model for the coder on the Routing page, through the bus.
|
||||
async function pickModel(o) {
|
||||
const view = await o.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.ok(view.catalogue.models.some(m => m.key === MODEL));
|
||||
await o.ask('routes.set', { revision: view.revision, routes: { coder: { harness: 'claude-code', model: MODEL, thinking: 'low', fallback: null } } });
|
||||
}
|
||||
|
||||
// The host launcher as cli.mjs builds it for a bus that booted with no proxy.json: its system has
|
||||
// no proxy. The model ops go to the bus itself; the rest are the launch-routes stub, and
|
||||
// authorizeLaunch stops a launch that passed every check before it.
|
||||
async function hostLauncher(t, f, o, { system = {} } = {}) {
|
||||
initializeControl(o.dataRoot);
|
||||
// A launch whose role names a skill that is not enabled refuses before the model gate.
|
||||
if (!fs.existsSync(join(f.dataRoot, 'skills-enabled'))) fs.cpSync(REPO_SKILLS, join(f.dataRoot, 'skills-enabled'), { recursive: true });
|
||||
// claude-code's preflight needs a session login or a proxy key, and this launcher boots with no
|
||||
// proxy, so the env carries a stand-in login (as launcher.test.mjs does). No adapter ever runs.
|
||||
const env = withoutHostCredentials(humanEnv({ MOSAIC_CONFIG: join(f.configDir, 'config.json'), MOSAIC_ROLES_DIR: f.rolesDir }));
|
||||
env.CLAUDE_CODE_OAUTH_TOKEN = 'stand-in';
|
||||
const answers = [], ops = [];
|
||||
const host = { business: o.id, beforeClose: () => {}, op: async m => {
|
||||
ops.push(m.op);
|
||||
if (m.op === 'identity') return { business: o.id, role: 'pm' };
|
||||
if (m.op === 'mayLaunch') return { allow: true };
|
||||
if (m.op === 'modelAdmission' || m.op === 'modelPreflight') { const answer = await o.bus[m.op](m); answers.push({ op: m.op, answer }); return answer; }
|
||||
if (m.op === 'authorizeLaunch') throw Object.assign(Error('fixture authorization stop'), { code: 'fixture-policy' });
|
||||
return {};
|
||||
} };
|
||||
const cliproxy = JSON.stringify(pathToFileURL(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).pathname).href);
|
||||
// The stand-in adapter path skips only the binary check; the launch stops at the model gate or
|
||||
// authorizeLaunch, before any adapter runs.
|
||||
const makeLoader = await fakeHarnesses(t, { 'claude-code': '/fixture-unused' }, write => write('model-provider', 'cliproxy', `export * from ${cliproxy};\n`));
|
||||
// The validated system config shape (mosaic-config.mjs), as cli.mjs passes it with the org root.
|
||||
const config = { configVersion: 1, environment: 'development', dataRoot: o.dataRoot, instanceRoot: f.dataRoot,
|
||||
execution: { backend: 'docker', provider: 'zai', model: 'glm-5.3-flash', adapter: 'mock' }, ...system };
|
||||
const launcher = createLauncher({ host, system: config, env, makeLoader, bwrap: '/usr/bin/true', log: () => {} });
|
||||
t.after(() => launcher.close?.().catch?.(() => {}));
|
||||
const events = () => { try { return fs.readFileSync(launchLogFile(o.dataRoot, o.id), 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)); } catch { return []; } };
|
||||
return { launch: () => launcher.fromSession('fixture-cap', 'coder'), answers, ops, events };
|
||||
}
|
||||
|
||||
const restartNotices = view => view.catalogue.notices.filter(n => n === RESTART).length;
|
||||
|
||||
test('a bus that picked up the proxy says on its ready catalogue that a restart starts agents on these models, and the launch refuses as before', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const before = await b.ask('routes');
|
||||
assert.equal(before.catalogue.status, 'unavailable');
|
||||
assert.equal(restartNotices(before), 0, 'no client yet: the not-set-up cause, not the restart notice');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.equal(restartNotices(view), 1);
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1, 'one notice at every read');
|
||||
// The bus that ran init holds a client it did not boot with too.
|
||||
const own = await a.ask('routes');
|
||||
assert.equal(own.catalogue.status, 'ready');
|
||||
assert.equal(restartNotices(own), 1);
|
||||
// The launch refuses as before, with the existing code and line, before any key or run: the
|
||||
// launcher booted with no proxy sends no proxy transport, and the bus's admission refuses that.
|
||||
const host = await hostLauncher(t, f, b);
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers, [{ op: 'modelAdmission', answer: { allow: false, code: 'model-provider-unavailable' } }]);
|
||||
assert.equal(host.ops.includes('authorizeLaunch'), false);
|
||||
assert.equal(host.ops.includes('modelPreflight'), false);
|
||||
const refused = host.events().filter(e => e.event === 'refused');
|
||||
assert.equal(refused.length, 1);
|
||||
assert.equal(refused[0].code, 'model-provider-unavailable');
|
||||
assert.equal(refused[0].why, 'model cliproxy/claude/claude-opus-5-5 unavailable (model-provider-unavailable)');
|
||||
// The bus side has no ModelKeys: a preflight issues no key.
|
||||
assert.equal(await b.bus.modelPreflight({ business: 'beta', role: 'coder' }), null);
|
||||
});
|
||||
|
||||
test('the restart notice is added after the notices the catalogue already carries', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
// A z.ai upstream group with no models: the cliproxy catalogue's own notice.
|
||||
await initThroughA(t, f, a, { groups: [{ 'base-url': ZAI_URL, keys: [{ name: 'group-1' }] }] });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.deepEqual(view.catalogue.notices, ['z.ai account has no models configured. Add them on Model proxy.', RESTART]);
|
||||
});
|
||||
|
||||
test('a bus started with the proxy shows no restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
const c = await orgBus(t, f, 'gamma', { binding: { proxy: loadProxy(f.configDir, f.dataRoot) } });
|
||||
const view = await c.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready', JSON.stringify(view.catalogue));
|
||||
assert.deepEqual(view.catalogue.notices, []);
|
||||
});
|
||||
|
||||
test('an organization with no model provider shows a disabled catalogue with no restart notice (the routes verb answers disabled itself)', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta', { providers: [] });
|
||||
await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy, 'the client is held');
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'disabled');
|
||||
assert.deepEqual(view.catalogue.notices, []);
|
||||
});
|
||||
|
||||
test('a fenced catalogue on a picked-up client reads unavailable with no restart notice, since a restart would not help', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1);
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }).fence({ org: 'alpha' });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.ok(b.bus.modelProxy);
|
||||
assert.equal(restartNotices(view), 0);
|
||||
// A bus that booted with the proxy on the same fenced instance, which is what a restart gives,
|
||||
// reads the same unavailable catalogue: the restart notice would have sent the owner nowhere.
|
||||
const c = await orgBus(t, f, 'gamma', { binding: { proxy: loadProxy(f.configDir, f.dataRoot) } });
|
||||
assert.equal((await c.ask('routes')).catalogue.status, 'unavailable');
|
||||
// Once the fence is gone, the ready catalogue says again that a restart is needed.
|
||||
fs.rmSync(join(f.dataRoot, 'proxy', 'mosaic-keys.uncertain'));
|
||||
const after = await b.ask('routes');
|
||||
assert.equal(after.catalogue.status, 'ready', JSON.stringify(after.catalogue));
|
||||
assert.equal(restartNotices(after), 1);
|
||||
});
|
||||
|
||||
test('refused settings still refuse the launch and name their cause, not the restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
// The management key file stops being private: the start path refuses it.
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(view.catalogue.notices.length, 1);
|
||||
assert.match(view.catalogue.notices[0], /management key does not load/);
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
// The bus itself refuses now: the catalogue keeps the model it saw, marked unavailable.
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers, [{ op: 'modelAdmission', answer: { allow: false, code: 'model-provider-unavailable' } }]);
|
||||
assert.match(host.events().at(-1).why, /^model cliproxy\/claude\/claude-opus-5-5 unavailable \(model-provider-unavailable\)$/);
|
||||
});
|
||||
|
||||
test('a dropped client refuses the next launch, and the catalogue names the cause instead of the restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1);
|
||||
fs.rmSync(join(f.configDir, 'proxy.json'));
|
||||
// The next launch refuses with the same code and line.
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers.map(a => a.answer), [{ allow: false, code: 'model-provider-unavailable' }, { allow: false, code: 'model-provider-unavailable' }]);
|
||||
assert.equal(host.events().filter(e => e.event === 'refused').length, 2);
|
||||
// The page's next read drops the client and names the cause.
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.deepEqual(view.catalogue.notices.length, 1);
|
||||
assert.match(view.catalogue.notices[0], /not been set up/);
|
||||
});
|
||||
|
||||
test('the management key is in no stderr line, response, refusal, launch log or file the launch path writes', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
const outputs = [];
|
||||
const { lines } = await capture(async () => {
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
outputs.push(await b.bus.modelPreflight({ business: 'beta', role: 'coder' }));
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o600);
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
});
|
||||
outputs.push(host.answers, host.events());
|
||||
assert.equal(lines.join('').includes(f.key), false, 'stderr');
|
||||
assert.equal(JSON.stringify(outputs).includes(f.key), false, 'responses, answers and launch log');
|
||||
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(dir, e.name)) : e.isFile() ? [join(dir, e.name)] : []);
|
||||
const files = [...walk(b.dataRoot), ...walk(join(f.dataRoot, 'proxy')).filter(p => !p.endsWith('/config.yaml'))];
|
||||
assert.ok(files.some(p => p === launchLogFile(b.dataRoot, 'beta')), 'the launch log is scanned');
|
||||
for (const file of files) assert.equal(fs.readFileSync(file).includes(f.key), false, file);
|
||||
});
|
||||
@@ -43,7 +43,8 @@ test('Broker keeps the sandbox client import closure: only the listed imports, n
|
||||
// Row 236 (#1742, #436b) reads giteaName and parseGiteaUrl for the Gitea grant path.
|
||||
// FED R3 r5 (row 274, #414) reads covers, a user's grant check, from it.
|
||||
// Row 219 reads THREAD_DEFINITIONS from the same vocabulary for creative thread admission.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';",
|
||||
// #1873 triage-fence reads SYSTEM_ONLY_REFUSAL and systemOnly from the same vocabulary.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';",
|
||||
]);
|
||||
assert.doesNotMatch(source, /\bimport\s*\(/);
|
||||
assert.doesNotMatch(readFileSync(new URL('../src/proxy-page-vocabulary.mjs', import.meta.url), 'utf8'), /\bimport\b/);
|
||||
|
||||
@@ -4,6 +4,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fakeManagement } from './proxy-page-fixture.mjs';
|
||||
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
const id = value => createHash('sha256').update(value).digest('hex').slice(0, 12);
|
||||
const oauth = extra => ({ id: 'oauth-one.json', name: 'oauth-one.json', provider: 'claude', label: 'p4-private-label',
|
||||
email: 'p4-private-email', token: 'p4-private-token', status: 'ready', priority: 3, ...extra });
|
||||
@@ -11,7 +12,9 @@ test('accounts have exactly the allowlisted public fields, id from credential id
|
||||
const s = await fakeManagement(t, { files: [oauth()] });
|
||||
const result = await s.call('proxy.accounts');
|
||||
assert.deepEqual(result, { accounts: [{ accountId: id('oauth-one.json'), provider: 'claude',
|
||||
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }] });
|
||||
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }],
|
||||
// settings-backend-a3: the provider list rides along, id, label and sign-in kind only.
|
||||
providers: PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })) });
|
||||
for (const value of ['p4-private-label', 'p4-private-email', 'p4-private-token']) {
|
||||
assert.equal(JSON.stringify(result).includes(value), false);
|
||||
assert.notEqual(result.accounts[0].accountId, id(value));
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// #1873 settings-backend-a3: the proxy page's provider names, login allow list, sign-in host and key
|
||||
// allow list all come from the plugin's PROVIDERS. A provider a test copy of the list leaves out is
|
||||
// refused at each door with the same code as before; one a copy adds is let through. The accounts
|
||||
// answer carries the list as id, label and sign-in kind only.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { ProxyPage } from '../src/proxy-page.mjs';
|
||||
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
const owner = { business: 'demo', human: 'owner' };
|
||||
function setup(options = {}) {
|
||||
const calls = [], state = { files: [], groups: [] };
|
||||
const client = Object.fromEntries(['getCredentials', 'oauthStart', 'oauthCallback', 'oauthStatus', 'oauthCancel', 'getUpstreamGroups', 'putUpstreamGroups'].map(name => [name, async (...args) => {
|
||||
calls.push([name, ...args]);
|
||||
if (name === 'oauthStart') return { status: 'ok', state: `s-${calls.length}`, url: `https://${options.hosts?.[args[0]] ?? 'nowhere.invalid'}/oauth/authorize?state=s-${calls.length}` };
|
||||
if (name === 'getCredentials') return { files: state.files };
|
||||
if (name === 'getUpstreamGroups') return structuredClone(state.groups);
|
||||
if (name === 'putUpstreamGroups') { state.groups = args[0].map((g, i) => ({ ...g, keys: g.keys.map((k, j) => ({ ...k, auth_index: `idx-${i}-${j}` })) })); return { status: 'ok' }; }
|
||||
return { status: 'ok' };
|
||||
}]));
|
||||
const p = new ProxyPage({ client, instanceTag: 'fixture', ...(options.providers ? { providers: options.providers } : {}) });
|
||||
return { calls, state, call: (verb, args = {}) => p.request(verb, args, owner) };
|
||||
}
|
||||
const hosts = Object.fromEntries(PROVIDERS.filter(p => p.signIn === 'oauth').map(p => [p.id, p.signInHost]));
|
||||
const door = p => p.signIn === 'oauth' ? ['proxy.login.start', { provider: p.id }] : ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }];
|
||||
const otherDoor = p => p.signIn === 'oauth' ? ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }] : ['proxy.login.start', { provider: p.id }];
|
||||
|
||||
test('a3: each provider in PROVIDERS passes its own door and is refused at the other with provider-not-allowed', async () => {
|
||||
assert.ok(PROVIDERS.some(p => p.signIn === 'oauth') && PROVIDERS.some(p => p.signIn === 'apikey'));
|
||||
for (const p of PROVIDERS) {
|
||||
const s = setup({ hosts });
|
||||
const answer = await s.call(...door(p));
|
||||
if (p.signIn === 'oauth') assert.equal(new URL(answer.url).hostname, p.signInHost, p.id);
|
||||
else { assert.deepEqual(answer, { added: true }); assert.equal(s.state.groups.at(-1)['base-url'], p.baseUrl); }
|
||||
const before = s.calls.length;
|
||||
await assert.rejects(s.call(...otherDoor(p)), { code: 'provider-not-allowed' }, p.id);
|
||||
assert.equal(s.calls.length, before, `${p.id}: a refusal reaches no proxy call`);
|
||||
}
|
||||
for (const [verb, args] of [['proxy.login.start', { provider: 'other' }], ['proxy.apikey.add', { provider: 'other', key: 'fixture-key' }]]) {
|
||||
const s = setup({ hosts });
|
||||
await assert.rejects(s.call(verb, args), { code: 'provider-not-allowed' }); assert.equal(s.calls.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('a3: a provider taken out of a test copy of the list is refused at its door, reads Other and leaves the providers answer', async () => {
|
||||
for (const gone of PROVIDERS) {
|
||||
const s = setup({ hosts, providers: PROVIDERS.filter(p => p !== gone) });
|
||||
await assert.rejects(s.call(...door(gone)), { code: 'provider-not-allowed' }, gone.id);
|
||||
assert.equal(s.calls.length, 0, `${gone.id}: refused before any proxy call`);
|
||||
if (gone.signIn === 'oauth') s.state.files = [{ id: 'one.json', name: 'one.json', provider: gone.id, status: 'ready' }];
|
||||
else s.state.groups = [{ name: 'g', 'base-url': gone.baseUrl, keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
|
||||
const answer = await s.call('proxy.accounts');
|
||||
assert.equal(answer.accounts.length, 1);
|
||||
assert.equal(answer.accounts[0].provider, 'other', gone.id);
|
||||
assert.match(answer.accounts[0].displayName, /^Other account /);
|
||||
assert.equal(Object.hasOwn(answer.accounts[0], 'models'), false, `${gone.id}: an unlisted group shows no models`);
|
||||
assert.deepEqual(answer.providers.map(p => p.id), PROVIDERS.filter(p => p !== gone).map(p => p.id));
|
||||
}
|
||||
});
|
||||
|
||||
test('a3: a provider a test copy adds is let through: key group from its base URL, sign-in on its host, name from its label', async () => {
|
||||
const extra = [{ id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: 'https://api.fixture.invalid/v1' },
|
||||
{ id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }];
|
||||
const s = setup({ providers: [...PROVIDERS, ...extra], hosts: { ...hosts, 'fixture-sso': 'sso.fixture.invalid' } });
|
||||
assert.deepEqual(await s.call('proxy.apikey.add', { provider: 'fixture.ai', key: 'fixture-key' }), { added: true });
|
||||
assert.equal(s.state.groups[0]['base-url'], 'https://api.fixture.invalid/v1');
|
||||
assert.match(s.state.groups[0].name, /^mosaic-fixtureai-[0-9a-f]{12}$/);
|
||||
assert.equal(new URL((await s.call('proxy.login.start', { provider: 'fixture-sso' })).url).hostname, 'sso.fixture.invalid');
|
||||
s.state.files = [{ id: 'sso.json', name: 'sso.json', provider: 'fixture-sso', status: 'ready' }];
|
||||
const { accounts } = await s.call('proxy.accounts');
|
||||
assert.deepEqual(accounts.map(a => [a.provider, a.displayName.replace(/ [0-9a-f]{12}$/, '')]), [['fixture-sso', 'Fixture SSO account'], ['fixture.ai', 'Fixture AI account']]);
|
||||
assert.deepEqual(accounts[1].models, []);
|
||||
});
|
||||
|
||||
test('a3: the sign-in address must be on the host the list names for that provider', async () => {
|
||||
const codex = PROVIDERS.find(p => p.id === 'codex');
|
||||
const moved = PROVIDERS.map(p => p === codex ? { ...p, signInHost: 'elsewhere.invalid' } : p);
|
||||
const s = setup({ hosts, providers: moved });
|
||||
await assert.rejects(s.call('proxy.login.start', { provider: 'codex' }), { code: 'proxy-down' });
|
||||
const t = setup({ hosts: { ...hosts, codex: 'elsewhere.invalid' }, providers: moved });
|
||||
assert.equal(new URL((await t.call('proxy.login.start', { provider: 'codex' })).url).hostname, 'elsewhere.invalid');
|
||||
});
|
||||
|
||||
test('a3: the accounts answer carries the providers as id, label and sign-in kind only, no URL, host or key', async () => {
|
||||
const s = setup({ hosts });
|
||||
await s.call('proxy.apikey.add', { provider: 'z.ai', key: 'a3-canary-key-value' });
|
||||
const answer = await s.call('proxy.accounts');
|
||||
assert.deepEqual(answer.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
|
||||
for (const p of answer.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
|
||||
const text = JSON.stringify(answer.providers);
|
||||
for (const word of ['a3-canary-key-value', 'https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
|
||||
});
|
||||
|
||||
// Review P3-1: an entry missing what its door needs is refused before any proxy call, so no sign-in
|
||||
// is opened at the proxy that the page could not cancel; a key group with no base URL is no provider's.
|
||||
test('a3: an entry with no sign-in host or no key base URL is refused before any proxy call and names no group', async () => {
|
||||
const bare = [{ id: 'nohost', label: 'No Host', signIn: 'oauth' }, { id: 'nourl', label: 'No URL', signIn: 'apikey' }];
|
||||
const s = setup({ providers: [...PROVIDERS, ...bare], hosts: { ...hosts, nohost: 'nohost.invalid' } });
|
||||
await assert.rejects(s.call('proxy.login.start', { provider: 'nohost' }), { code: 'provider-not-allowed' });
|
||||
await assert.rejects(s.call('proxy.apikey.add', { provider: 'nourl', key: 'fixture-key' }), { code: 'provider-not-allowed' });
|
||||
assert.equal(s.calls.length, 0);
|
||||
s.state.groups = [{ name: 'g', keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
|
||||
s.state.files = [{ id: 'one.json', name: 'one.json', provider: 'nohost', status: 'ready' }];
|
||||
const { accounts } = await s.call('proxy.accounts');
|
||||
assert.deepEqual(accounts.map(a => a.provider), ['other', 'other']);
|
||||
assert.equal(accounts.some(a => Object.hasOwn(a, 'models')), false);
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
// #1873 chat-fail F3: an account the proxy reports as not working carries one plain line,
|
||||
// built only from the structured fields of the proxy's own account read. No upstream text,
|
||||
// label or email is ever reflected, and no new proxy call is made.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fakeManagement } from './proxy-page-fixture.mjs';
|
||||
const PRIVATE = ['p4-private-label', 'p4-private-email', 'p4-private-token', 'p4-private-message'];
|
||||
const oauth = extra => ({ id: 'oauth-one.json', name: 'oauth-one.json', provider: 'claude', label: PRIVATE[0],
|
||||
email: PRIVATE[1], token: PRIVATE[2], status: 'ready', priority: 3, ...extra });
|
||||
const SIGN_IN = 'The account needs to sign in again. Sign in again, or add another account.';
|
||||
const USAGE = 'The account is out of usage. Wait until it resets, or add another account.';
|
||||
const usageAt = time => `The account is out of usage. It resets at ${time}. Wait until then, or add another account.`;
|
||||
const PAUSED = time => `The model service paused this account until ${time}. Wait until then, sign in again, or add another account.`;
|
||||
const NO_REASON = 'The model service gave no reason. Wait and try again later, sign in again, or add another account.';
|
||||
async function reasonOf(t, extra) {
|
||||
const s = await fakeManagement(t, { files: [oauth(extra)] });
|
||||
const result = await s.call('proxy.accounts');
|
||||
const text = JSON.stringify(result);
|
||||
for (const value of PRIVATE) assert.equal(text.includes(value), false, `${value} reached the page`);
|
||||
assert.deepEqual(s.state.calls, ['GET /v8/management/credentials', 'GET /v8/management/config/api-keys/claude'], 'no new proxy call');
|
||||
return result.accounts[0];
|
||||
}
|
||||
test('an account that must sign in again says so, from requires_sign_in or a refresh error', async t => {
|
||||
for (const extra of [{ status: 'error', requires_sign_in: true, next_action: 'sign_in', recovery_hint: PRIVATE[3] },
|
||||
{ status: 'error', refresh_error: { code: 'invalid_grant', message: PRIVATE[3], http_status: 400 } },
|
||||
{ unavailable: true, status_message: `401 Unauthorized ${PRIVATE[3]}` },
|
||||
{ status: 'error', status_message: `token expired ${PRIVATE[3]}` }])
|
||||
assert.equal((await reasonOf(t, extra)).reason, SIGN_IN, JSON.stringify(extra));
|
||||
});
|
||||
test('an account out of usage names the reset time when the read carries one', async t => {
|
||||
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after: '2099-03-04T05:06:07Z' })).reason,
|
||||
usageAt('2099-03-04 05:06 UTC'));
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message: `usage limit reached ${PRIVATE[3]}`, next_retry_after: '2099-03-04T05:06:07+02:00' })).reason,
|
||||
usageAt('2099-03-04 03:06 UTC'));
|
||||
// No time, a past time or a value that is not a time gives no time, never the value itself.
|
||||
for (const next_retry_after of [undefined, '2000-01-01T00:00:00Z', PRIVATE[3], '2099-13-40T99:99:99Z', 12345, { at: 1 }])
|
||||
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after })).reason, USAGE, String(next_retry_after));
|
||||
});
|
||||
test('a paused account with only a retry time says until when', async t => {
|
||||
assert.equal((await reasonOf(t, { unavailable: true, status_message: PRIVATE[3], next_retry_after: '2099-03-04T05:06:07.123456789Z' })).reason,
|
||||
PAUSED('2099-03-04 05:06 UTC'));
|
||||
});
|
||||
test('a failing account with nothing more in the read says the model service gave no reason', async t => {
|
||||
for (const extra of [{ status: 'error' }, { unavailable: true }, { status: 'unavailable', status_message: PRIVATE[3] },
|
||||
{ status: 'error', status_message: 42, refresh_error: null, requires_sign_in: 'yes', quota_blocked: 1 }])
|
||||
assert.equal((await reasonOf(t, extra)).reason, NO_REASON, JSON.stringify(extra));
|
||||
});
|
||||
test('a working, turned-off or unknown account keeps exactly its fields and gets no line', async t => {
|
||||
for (const extra of [{}, { status: 'active', status_message: 'usage limit reached' }, { disabled: true, requires_sign_in: true }, { status: 'mystery' }])
|
||||
assert.deepEqual(Object.keys(await reasonOf(t, extra)).sort(), ['accountId', 'displayName', 'priority', 'provider', 'status'], JSON.stringify(extra));
|
||||
});
|
||||
test('every line is plain: no em dash, no control character, at most one sentence pair', () => {
|
||||
for (const line of [SIGN_IN, USAGE, usageAt('2099-03-04 05:06 UTC'), PAUSED('2099-03-04 05:06 UTC'), NO_REASON]) {
|
||||
assert.doesNotMatch(line, /[—\u0000-\u001f\u007f]/);
|
||||
assert.ok(line.length <= 160, line);
|
||||
}
|
||||
});
|
||||
// Review round 1: a day the month doesn't have is refused, not rolled into the next month.
|
||||
test('an impossible date gives no reset time; a real leap day does', async t => {
|
||||
for (const next_retry_after of ['2099-02-31T00:00:00Z', '2099-04-31T10:00:00Z', '2099-02-29T00:00:00Z'])
|
||||
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after })).reason, USAGE, next_retry_after);
|
||||
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after: '2096-02-29T01:02:03Z' })).reason, usageAt('2096-02-29 01:02 UTC'));
|
||||
});
|
||||
// Review round 1: quota_blocked wins over a message word, and a bare "expired" is not a sign-in.
|
||||
test('an account blocked on usage whose message says expired gets the usage line', async t => {
|
||||
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, status_message: `usage window expired ${PRIVATE[3]}` })).reason, USAGE);
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message: `trial window expired ${PRIVATE[3]}` })).reason, NO_REASON);
|
||||
for (const status_message of ['session expired', 'credentials expired', 'OAuth token has expired'])
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
|
||||
});
|
||||
// Review round 2: the sign-in words match whole words only, and a prefixed or "is expired" token counts.
|
||||
test('a message word inside another word is not a sign-in; a prefixed or "is expired" token is', async t => {
|
||||
for (const status_message of ['assigning a slot', 'logging paused', 'design input'])
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, NO_REASON, status_message);
|
||||
for (const status_message of ['access_token expired', 'token is expired', 'refresh-token has been expired', 'please sign in'])
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
|
||||
});
|
||||
// Review round 3: "relogin", plurals and past forms of "expired" read as a sign-in too.
|
||||
test('relogin, plural and past forms of an expired sign-in say sign in again', async t => {
|
||||
for (const status_message of ['relogin required', 'tokens have expired', 'session was expired', 'credentials were expired'])
|
||||
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
|
||||
});
|
||||
@@ -0,0 +1,371 @@
|
||||
// #1873 proxy-pickup: a running organization bus picks up the shared model proxy that another
|
||||
// organization's bus initialized, with no restart, through the start path's loader and lock. A
|
||||
// bus whose proxy settings the start path would refuse still refuses, and names the cause in one
|
||||
// plain line. Real buses and a fake loopback management server; no live config.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { createProxyLock } from '../src/proxy-lock.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { PIN } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy, installPaths } from '../../model-proxy/src/settings.mjs';
|
||||
import { FIXTURE_ENTRY, FIXTURE_KEY_NAME } from '../../plugins/model-provider/fixture/index.mjs';
|
||||
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
// A loopback stand-in for the proxy's management API: one ready Claude account with one model.
|
||||
async function fakeProxy(t, key, port = 0) {
|
||||
const seen = { calls: 0, wrongKey: 0 };
|
||||
const server = http.createServer((req, res) => {
|
||||
seen.calls++;
|
||||
if (req.headers.authorization !== `Bearer ${key}`) { seen.wrongKey++; res.writeHead(401); res.end('{}'); return; }
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
const answer = url.pathname === '/v8/management/credentials' ? { files: [{ id: 'acct-1', name: 'acct-1', provider: 'claude', status: 'ready', priority: 1 }] }
|
||||
: url.pathname === '/v8/management/credentials/models' ? { models: [{ id: 'claude-opus-5-5' }] }
|
||||
: url.pathname === '/v8/management/config/api-keys/claude' ? []
|
||||
: url.pathname === '/v8/management/config/access/api-keys' ? []
|
||||
: null;
|
||||
if (answer === null) { res.writeHead(404); res.end('{}'); return; }
|
||||
res.end(JSON.stringify(answer));
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
|
||||
return { port: server.address().port, seen, server };
|
||||
}
|
||||
|
||||
// One instance (config dir + data root) and a fake proxy install whose bytes a test pin names.
|
||||
// The pin keeps the shipped version, so the pinned binary path is the one loadProxy accepts.
|
||||
function instance(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pk-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'instance');
|
||||
fs.mkdirSync(join(configDir, 'secrets', 'agents'), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(join(configDir, 'secrets'), 0o700);
|
||||
fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const paths = installPaths(dataRoot);
|
||||
fs.mkdirSync(join(paths.dir, 'static'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(paths.binary, 'fixture proxy binary\n', { mode: 0o700 });
|
||||
fs.writeFileSync(paths.panel, '<!doctype html>\n', { mode: 0o600 });
|
||||
const pin = { ...PIN, binary: { ...PIN.binary, sha256: sha('fixture proxy binary\n') }, panel: { ...PIN.panel, sha256: sha('<!doctype html>\n') } };
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const key = `pk1873-${randomBytes(24).toString('hex')}`;
|
||||
return { root, configDir, dataRoot, paths, pin, rolesDir, system, key, closers: [] };
|
||||
}
|
||||
|
||||
// A real organization bus on the instance, started with no proxy (as cli bootConfig does when the
|
||||
// instance has no proxy.json at boot).
|
||||
async function orgBus(t, f, id, { providers = ['cliproxy'], edit = () => {}, org = { id }, binding = {} } = {}) {
|
||||
const doc = businessDoc(f.root, id);
|
||||
doc.plugins = { harness: ['pi'], 'model-provider': providers };
|
||||
edit(doc);
|
||||
writeJson(join(f.configDir, 'businesses', `${id}.json`), doc);
|
||||
const business = loadBusiness(id, { dir: f.configDir, rolesDir: f.rolesDir }), resolved = {};
|
||||
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system: f.system, business, instance: name });
|
||||
const dataRoot = join(f.root, `${id}-bus`); fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
|
||||
const bus = await startBroker({ dataRoot, businesses: { [id]: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir: f.rolesDir, system: f.system },
|
||||
instanceRoot: f.dataRoot, org, instanceDataRoot: f.dataRoot, instanceConfigDir: f.configDir,
|
||||
initProxy: args => initializeProxy({ ...args, pin: f.pin }), ...binding });
|
||||
t.after(() => bus.close().catch(() => {}));
|
||||
const human = bus.broker.bindHuman({ business: id, human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const ask = (verb, args) => Promise.resolve().then(() => bus.broker.request(human, { verb, args }));
|
||||
return { bus, ask, dataRoot };
|
||||
}
|
||||
|
||||
// Every stderr line written while `run` is in flight.
|
||||
async function capture(run) {
|
||||
const write = process.stderr.write, lines = [];
|
||||
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
|
||||
try { return { value: await run(), lines }; } finally { process.stderr.write = write; }
|
||||
}
|
||||
|
||||
// The proxy init through bus A writes proxy.json and the key, then the proxy starts on that port.
|
||||
async function initThroughA(t, f, a) {
|
||||
const settings = await a.ask('proxy.init', { key: f.key });
|
||||
const proxy = await fakeProxy(t, f.key, settings.port);
|
||||
return { settings, proxy };
|
||||
}
|
||||
|
||||
const notConfigured = (pattern) => e => e.code === 'not-configured' && typeof e.reason === 'string' && pattern.test(e.reason) && e.reason.length <= 300;
|
||||
|
||||
test('a running organization bus answers accounts and a cliproxy catalogue once another bus initialized the shared proxy, with no restart', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
// Before init: bus B has nothing to pick up, and says so.
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/not been set up/));
|
||||
const before = await b.ask('routes');
|
||||
assert.equal(before.catalogue.status, 'unavailable');
|
||||
assert.equal(before.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(before.catalogue.notices.length, 1);
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
// Bus A holds the client from its own init; bus B picks it up at its next read.
|
||||
assert.deepEqual((await a.ask('proxy.accounts', {})).accounts.map(r => r.provider), ['claude']);
|
||||
const accounts = await b.ask('proxy.accounts', {});
|
||||
assert.deepEqual(accounts.accounts.map(r => [r.provider, r.status]), [['claude', 'ready']]);
|
||||
const after = await b.ask('routes');
|
||||
assert.equal(after.catalogue.status, 'ready');
|
||||
assert.deepEqual(after.catalogue.models.map(m => m.key), ['claude-claude-opus-5-5']);
|
||||
assert.equal(after.catalogue.reason, undefined);
|
||||
assert.equal(proxy.seen.wrongKey, 0);
|
||||
// Bus B reached the proxy through the same lock identity the start path uses.
|
||||
assert.ok(createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }));
|
||||
});
|
||||
|
||||
test('a bus started before the proxy existed and asked only for a catalogue picks the proxy up', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'unavailable');
|
||||
await initThroughA(t, f, a);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'ready');
|
||||
});
|
||||
|
||||
// Each case writes the shared proxy's files by hand into a state the start path refuses.
|
||||
const refusedStates = [
|
||||
['proxy.json names an unpinned binary', /settings do not load/, f => writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: '/elsewhere/cli-proxy-api' })],
|
||||
['proxy.json is not JSON', /settings do not load/, f => fs.writeFileSync(join(f.configDir, 'proxy.json'), '{', { mode: 0o600 })],
|
||||
['the management key file is readable by others', /management key does not load/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o644 });
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
}],
|
||||
['the management key file is missing', /management key does not load/, f => writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary })],
|
||||
['the proxy state names another port', /proxy lock/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o600 });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { mode: 0o700 });
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:40998` });
|
||||
}],
|
||||
['the proxy state directory is open to others', /proxy lock/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o600 });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { mode: 0o755 }); fs.chmodSync(join(f.dataRoot, 'proxy'), 0o755);
|
||||
}],
|
||||
];
|
||||
for (const [name, cause, arrange] of refusedStates) test(`no pickup when ${name}: accounts and catalogue refuse with the cause`, async t => {
|
||||
const f = instance(t);
|
||||
const b = await orgBus(t, f, 'beta');
|
||||
arrange(f);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(cause));
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.match(view.catalogue.notices[0], cause);
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
// The host refuses fixture-proxy-configured only when a dev fixture is recorded for the instance.
|
||||
const recordFixture = f => {
|
||||
fs.mkdirSync(join(f.dataRoot, 'dev-fixture'), { mode: 0o700 });
|
||||
fs.writeFileSync(join(f.dataRoot, 'dev-fixture', 'fixture.json'), '{}\n', { mode: 0o600 });
|
||||
};
|
||||
|
||||
test('no pickup for an organization on the fixture model provider, which the host refuses with a proxy', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'], edit: doc => { doc.launch.models[FIXTURE_KEY_NAME] = { ...FIXTURE_ENTRY }; } });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.match(view.catalogue.notices[0], /fixture/);
|
||||
});
|
||||
|
||||
test('no pickup for an organization whose launch table names the fixture module only', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { edit: doc => { doc.launch.models[FIXTURE_KEY_NAME] = { ...FIXTURE_ENTRY }; } });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('an organization that lists the fixture still picks the proxy up when no fixture is recorded, as the host would start it', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'] });
|
||||
await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
// A fixture recorded later drops the client at the next request.
|
||||
recordFixture(f);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a picked-up client is dropped when proxy.json goes away, its port changes, or the key stops loading', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { settings } = await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
const file = join(f.configDir, 'proxy.json'), keyFile = join(f.configDir, 'secrets', 'proxy-management.key');
|
||||
const saved = fs.readFileSync(file);
|
||||
// Port change: the lock identity is bound to the port, so the bus refuses until a restart.
|
||||
writeJson(file, { ...settings, port: settings.port + 1 === 8317 ? settings.port + 2 : settings.port + 1 });
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/proxy lock/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'unavailable');
|
||||
// Back to the original port, the bus picks it up again.
|
||||
fs.writeFileSync(file, saved);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
// Key file no longer 0600.
|
||||
fs.chmodSync(keyFile, 0o640);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/management key does not load/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
fs.chmodSync(keyFile, 0o600);
|
||||
await b.ask('proxy.accounts', {});
|
||||
// proxy.json removed.
|
||||
fs.rmSync(file);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/not been set up/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
});
|
||||
|
||||
test('a default-instance bus (no organization binding, no lock) follows a port change to the new client, never the old one', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), d = await orgBus(t, f, 'delta', { org: null });
|
||||
const { settings, proxy } = await initThroughA(t, f, a);
|
||||
assert.deepEqual((await d.ask('proxy.accounts', {})).accounts.map(r => r.provider), ['claude']);
|
||||
const old = d.bus.modelProxy;
|
||||
// A listener on the new port that answers nothing to the right key: reaching it proves the move.
|
||||
const moved = await fakeProxy(t, `other-${f.key.slice(0, 6)}`);
|
||||
writeJson(join(f.configDir, 'proxy.json'), { ...settings, port: moved.port });
|
||||
const before = proxy.seen.calls;
|
||||
await assert.rejects(d.ask('proxy.accounts', {}));
|
||||
assert.ok(d.bus.modelProxy && d.bus.modelProxy !== old);
|
||||
assert.ok(moved.seen.calls > 0);
|
||||
assert.equal(proxy.seen.calls, before);
|
||||
});
|
||||
|
||||
test('a picked-up bus reads its catalogue through the shared lock: a fence makes it unavailable', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'ready');
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }).fence({ org: 'alpha' });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.ok(b.bus.modelProxy, 'the client stays; the fence alone holds the catalogue');
|
||||
});
|
||||
|
||||
test('a fixture record path in any state but absent counts as recorded', async t => {
|
||||
const f = instance(t);
|
||||
fs.writeFileSync(join(f.dataRoot, 'dev-fixture'), 'not a directory\n', { mode: 0o600 });
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'] });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('with a fixture recorded, an organization document that no longer validates counts as using it', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
fs.writeFileSync(join(f.configDir, 'businesses', 'beta.json'), '{', { mode: 0o600 });
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('the bus that ran init also drops its client when the key stops loading', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
await a.ask('proxy.accounts', {});
|
||||
fs.rmSync(join(f.configDir, 'secrets', 'proxy-management.key'));
|
||||
await assert.rejects(a.ask('proxy.accounts', {}), notConfigured(/management key does not load/));
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('an init whose lock refuses leaves the init bus holding no client: no ready catalogue without the lock', async t => {
|
||||
const f = instance(t);
|
||||
// The real init, then the proxy state dir is left readable by the group, which the lock refuses.
|
||||
const initProxy = async args => { const settings = await initializeProxy({ ...args, pin: f.pin });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { recursive: true }); fs.chmodSync(join(f.dataRoot, 'proxy'), 0o750); return settings; };
|
||||
const a = await orgBus(t, f, 'alpha', { binding: { initProxy } });
|
||||
await assert.rejects(a.ask('proxy.init', { key: f.key }));
|
||||
await fakeProxy(t, f.key, JSON.parse(fs.readFileSync(join(f.configDir, 'proxy.json'), 'utf8')).port);
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
const view = await a.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.match(view.catalogue.notices[0], /proxy-lock-invalid/);
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a default-instance bus (no lock generation) refreshes its catalogue at once on pickup and on drop', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), d = await orgBus(t, f, 'delta', { org: null });
|
||||
// An unavailable catalogue read before init must not be served after the pickup.
|
||||
assert.equal((await d.ask('routes')).catalogue.status, 'unavailable');
|
||||
await initThroughA(t, f, a);
|
||||
assert.equal((await d.ask('routes')).catalogue.status, 'ready');
|
||||
// A ready catalogue read through the picked-up client must not be served after the drop.
|
||||
fs.rmSync(join(f.configDir, 'proxy.json'));
|
||||
const gone = await d.ask('routes');
|
||||
assert.equal(gone.catalogue.status, 'unavailable');
|
||||
assert.equal(gone.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(d.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a picked-up bus clears a proxy fence through the same client and lock', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
// proxy.fence.clear on a bus that has not read anything yet still picks the proxy up first; the
|
||||
// restart evidence check is the existing one and refuses this empty evidence.
|
||||
await assert.rejects(b.ask('proxy.fence.clear', { evidence: {} }));
|
||||
assert.ok(b.bus.modelProxy);
|
||||
});
|
||||
|
||||
test('a bus serving an invalid organization id never picks up a proxy', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
let b;
|
||||
try { b = await orgBus(t, f, 'beta', { binding: { instanceConfigDir: 42 } }); }
|
||||
catch (error) { assert.equal(error.code, 'invalid-host-request'); return; }
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/organization binding/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('the management key is in no stderr line, response, refusal, event or file the pickup path writes', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
const outputs = [];
|
||||
const { lines } = await capture(async () => {
|
||||
outputs.push(await b.ask('proxy.accounts', {}));
|
||||
outputs.push(await b.ask('routes'));
|
||||
// A refusal after the key stops loading, and the pickup after it loads again.
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
await b.ask('proxy.accounts', {}).catch(error => outputs.push({ code: error.code, reason: error.reason, message: error.message, next: error.next }));
|
||||
outputs.push(await b.ask('routes'));
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o600);
|
||||
outputs.push(await b.ask('proxy.accounts', {}));
|
||||
});
|
||||
assert.ok(lines.some(line => line.startsWith('model-proxy: ')), 'the pickup client writes its usual receipts');
|
||||
assert.equal(lines.join('').includes(f.key), false, 'stderr');
|
||||
assert.equal(JSON.stringify(outputs).includes(f.key), false, 'responses');
|
||||
// Every file under bus B's data root (store, WAL, sessions) and the proxy state directory,
|
||||
// except the proxy's own config.yaml that init writes for the proxy process.
|
||||
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(dir, e.name)) : e.isFile() ? [join(dir, e.name)] : []);
|
||||
const files = [...walk(b.dataRoot), ...walk(join(f.dataRoot, 'proxy')).filter(p => !p.endsWith('/config.yaml'))];
|
||||
assert.ok(files.length > 0);
|
||||
for (const file of files) assert.equal(fs.readFileSync(file).includes(f.key), false, file);
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
// #1873 lane triage-fence: through the broker, no organization gains the system-only Triage
|
||||
// template. Pack preview and apply, the Console hire start, the chief's hire.raise and
|
||||
// decision.raise, and instances.set add as the human and the tester each refuse with
|
||||
// template-system-only; the Console's hire template list omits triage. The coding pack still
|
||||
// previews as before. Fixtures live in a temp directory.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Broker } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { pluginHash } from '../../plugins/src/pinned.mjs';
|
||||
import { installPlugin } from '../../plugins/src/install.mjs';
|
||||
import { starterPack as codingPack } from '../../plugins/starter-pack/coding/index.mjs';
|
||||
import { templateHash } from '../../organization/src/definitions.mjs';
|
||||
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const CODE = 'template-system-only';
|
||||
const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' };
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
|
||||
// The broker started as the runtime starts it, with the organization writer and installed packs.
|
||||
async function runtime(t) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sobus-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const data = join(root, 'data');
|
||||
mkdirSync(data, { mode: 0o700 });
|
||||
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery', 'organization.change'], crossRole: [] } } };
|
||||
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles, vars: { 'bus.tester': true } } };
|
||||
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
const thaw = (p) => { const st = lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) thaw(join(p, e)); } };
|
||||
t.after(async () => { await bus.close(); thaw(root); rmSync(root, { recursive: true, force: true }); });
|
||||
const b = bus.broker;
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const tester = b.bindTester({ business: 'demo' });
|
||||
const call = async (verb, args = {}, cap = owner) => b.request(cap, { verb, args });
|
||||
const file = () => readFileSync(join(root, 'businesses/demo.json'), 'utf8');
|
||||
let n = 0;
|
||||
const install = (pack) => {
|
||||
const src = join(root, `src-${n++}`);
|
||||
mkdirSync(join(src, 'starter-pack'), { recursive: true });
|
||||
writeFileSync(join(src, 'starter-pack', 'index.mjs'), `export const interfaceVersion = 1;\nexport function starterPack() { return ${JSON.stringify(pack)}; }\n`);
|
||||
const manifest = { name: pack.id, version: '1.0.0', kinds: ['starter-pack'], interfaceVersions: { 'starter-pack': 1 }, sha256: '0'.repeat(64),
|
||||
source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
manifest.sha256 = pluginHash(src);
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
installPlugin({ dataRoot: data, source: src, expectedHash: manifest.sha256 });
|
||||
};
|
||||
return { b, root, rolesDir, owner, human, tester, call, file, install };
|
||||
}
|
||||
|
||||
// The A4 broker with the real hire service, so the chief's raise and the Console start reach it.
|
||||
function hires(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sohire-')), rolesDir = rolesCopy(root);
|
||||
writeJson(join(root, 'businesses/demo.json'), { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } });
|
||||
const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 });
|
||||
const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot);
|
||||
const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: () => {} });
|
||||
const loaded = () => { const doc = loadBusiness('demo', { dir: root, rolesDir }); return { ...doc, roles: Object.fromEntries(Object.entries(doc.roles).map(([k, e]) => [k, { ...doc.definitions[e.definition], ...e }])) }; };
|
||||
const b = new Broker({ store, businesses: { demo: loaded() }, hires: service });
|
||||
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const chief = b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' });
|
||||
b.request(chief, { verb: 'role.claim' });
|
||||
const call = (cap, verb, args = {}) => b.request(cap, { verb, args });
|
||||
const triage = { template: 'triage', sha256: templateHash(rolesDir, 'triage') };
|
||||
const hire = (extra = {}) => ({ op: 'hire', level: 'org', name: 'sorter', role: triage, route: ROUTE, reason: 'Sort the inbox', ...extra });
|
||||
const decisions = () => store.get('SELECT count(*) n FROM decisions').n;
|
||||
return { owner, chief, call, hire, decisions };
|
||||
}
|
||||
|
||||
const refuses = async (promise) => assert.rejects(Promise.resolve().then(() => promise), (e) => e?.code === CODE);
|
||||
|
||||
test('pack preview refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.preview.console', { pack: 'sorting' }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('pack apply refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.apply.console', { pack: 'sorting', digest: 'a'.repeat(64) }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the human', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.human));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the tester', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.tester));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('the instances read offers no triage add', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const view = await h.call('instances', {}, h.human);
|
||||
assert.equal(Object.hasOwn(view.definitions, 'triage'), false);
|
||||
});
|
||||
|
||||
test('the Console hire start refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.owner, 'hire.start.console', f.hire()));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief hire.raise refuses a triage template at org, project and root level', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire()));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'project', project: 'stack' })));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'root' })));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief decision.raise naming role.hire or role.change refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.hire', hire: f.hire() }));
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.change', hire: f.hire({ op: 'change', name: 'coder' }) }));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the Console hire template list omits triage and keeps the rest', async (t) => {
|
||||
const f = hires(t);
|
||||
const names = (await f.call(f.owner, 'hire.templates.console')).templates.map((x) => x.name);
|
||||
assert.ok(!names.includes('triage'));
|
||||
assert.ok(names.includes('coder') && names.includes('reviewer'));
|
||||
});
|
||||
|
||||
// The guard: a shipped pack previews and applies as before, and an installed pack with no triage loads.
|
||||
test('the shipped coding pack and an installed pack without triage preview as before', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const preview = await h.call('pack.preview.console', { pack: 'coding' });
|
||||
assert.match(preview.digest, /^[a-f0-9]{64}$/);
|
||||
h.install({ ...codingPack(), id: 'plain', label: 'Plain' });
|
||||
const plain = await h.call('pack.preview.console', { pack: 'plain' });
|
||||
assert.match(plain.digest, /^[a-f0-9]{64}$/);
|
||||
const out = await h.call('pack.apply.console', { pack: 'coding', digest: preview.digest });
|
||||
assert.deepEqual(out.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
});
|
||||
@@ -656,3 +656,80 @@ test('C2-09a: creative bindLaunch without a thread refuses thread-required', t =
|
||||
assert.equal(ctx.count('SELECT count(*) n FROM threads'), 0);
|
||||
assert.equal(ctx.count('SELECT count(*) n FROM role_claims'), 0);
|
||||
});
|
||||
|
||||
// #1873 chat-fail F2: the launcher's trusted failureNotice puts one plain line in the conversation
|
||||
// for each message a refused start or a stalled run left unanswered.
|
||||
const LIMIT_LINE = "The turn failed: the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.\nDetails: start refused: limit-reached";
|
||||
const STALL_LINE = "The turn failed: the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup.\nDetails: stopped: proxy-stall";
|
||||
const lines = (store, id) => store.all("SELECT * FROM messages WHERE in_reply_to=? AND from_run='bus'", id);
|
||||
|
||||
test('#1873 F2: a refused start puts one line per pending message in its session, once, and none for a wait', (t) => {
|
||||
const { b, store, call, A, B } = twoThreads(t);
|
||||
b.endLaunch({ business: 'demo', run: 'a-run', reason: 'idle' });
|
||||
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
|
||||
const notice = (code, extra = {}) => b.failureNotice({ business: 'demo', thread: A, session, code, ...extra });
|
||||
const one = call('human', 'thread.send', { thread: A, body: 'one' });
|
||||
const two = call('human', 'thread.send', { thread: A, body: 'two' });
|
||||
const other = call('human', 'thread.send', { thread: B, body: 'for B' });
|
||||
// A start that waits for a free place leaves no line.
|
||||
for (const code of ['capacity-full', 'instance-running', 'legacy-run-live', 'session-workspace-busy', 'processing-generation-changed', 'proxy-lock-busy', 'project-pending', 'processing-halted']) assert.deepEqual(notice(code), { posted: 0 });
|
||||
assert.deepEqual(notice('limit-reached'), { posted: 2 });
|
||||
for (const sent of [one, two]) {
|
||||
const [line] = lines(store, sent.id);
|
||||
assert.equal(line.body, LIMIT_LINE);
|
||||
assert.deepEqual([line.class, line.from_role, line.to_role, line.from_run], ['RESULT', 'assistant', 'human', 'bus']);
|
||||
assert.equal(store.get('SELECT session FROM message_threads WHERE message=?', line.id).session, session, 'the line is in the session');
|
||||
}
|
||||
assert.deepEqual(lines(store, other.id), [], "another thread's message gets none");
|
||||
// Every retry meets the same refusal: still one line each, under any code.
|
||||
assert.deepEqual(notice('limit-reached'), { posted: 0 });
|
||||
assert.deepEqual(notice('model-provider-unavailable'), { posted: 0 });
|
||||
assert.equal(lines(store, one.id).length, 1);
|
||||
// The message stays pending, so the next start still takes it.
|
||||
assert.equal(b.threadsState('demo').find((s) => s.thread === A).pending, 2);
|
||||
const three = call('human', 'thread.send', { thread: A, body: 'three' });
|
||||
assert.deepEqual(notice('some-new-code'), { posted: 1 });
|
||||
assert.match(lines(store, three.id)[0].body, /^The turn failed: the assistant couldn't start\. .*\nDetails: start refused: some-new-code$/);
|
||||
});
|
||||
|
||||
test('#1873 F2: a stalled run puts one line on each message delivered to it and unread, thread or role', (t) => {
|
||||
const { b, store, call, A } = twoThreads(t);
|
||||
const taken = call('human', 'thread.send', { thread: A, body: 'taken' });
|
||||
assert.deepEqual(call('a', 'message.receive').map((m) => m.id), [taken.id]);
|
||||
const waiting = call('human', 'thread.send', { thread: A, body: 'still waiting' });
|
||||
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 1 });
|
||||
assert.equal(lines(store, taken.id)[0].body, STALL_LINE);
|
||||
assert.deepEqual(lines(store, waiting.id), [], 'a message the run never took waits for the next run');
|
||||
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 0 });
|
||||
// A read message was answered by the turn: no line.
|
||||
const read = call('human', 'thread.send', { thread: A, body: 'read' });
|
||||
call('a', 'message.receive');
|
||||
call('a', 'message.read', { id: read.id });
|
||||
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 1 }, 'only waiting, delivered now');
|
||||
assert.deepEqual(lines(store, read.id), []);
|
||||
// A role run: the human's message to the chief, outside any thread.
|
||||
const asked = call('human', 'message.send', { to: 'chief', class: 'REQUEST', body: 'chief, please' });
|
||||
assert.ok(call('chief', 'message.receive').some((m) => m.id === asked.id));
|
||||
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'chief-run', code: 'proxy-stall' }), { posted: 1 });
|
||||
const [line] = lines(store, asked.id);
|
||||
assert.deepEqual([line.body, line.from_role, line.to_role], [STALL_LINE, 'chief', 'human']);
|
||||
assert.equal(store.get('SELECT count(*) n FROM message_threads WHERE message=?', line.id).n, 0);
|
||||
});
|
||||
|
||||
test('#1873 F2: failureNotice refuses a malformed record before any write', (t) => {
|
||||
const { b, store, A } = twoThreads(t);
|
||||
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
|
||||
const before = store.get('SELECT count(*) n FROM messages').n;
|
||||
const bad = [
|
||||
[{ business: 'demo', code: 'limit-reached' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'a-run', thread: A, session }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'Limit Reached', run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'x'.repeat(65), run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 7, run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'a-run', why: 'secret text' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'nobody-run' }, 'unknown-run'],
|
||||
[{ business: 'demo', code: 'limit-reached', thread: A, session: 'no-such-session' }, 'session-not-found'],
|
||||
];
|
||||
for (const [record, code] of bad) assert.throws(() => b.failureNotice(record), { code }, JSON.stringify(record));
|
||||
assert.equal(store.get('SELECT count(*) n FROM messages').n, before);
|
||||
});
|
||||
@@ -0,0 +1,305 @@
|
||||
// proxy-scope slice 4 (#1873): the Triage key in the bus. Real organization buses on one instance,
|
||||
// a stand-in proxy management server on loopback and a temporary config directory; nothing here
|
||||
// reads a real config, proxy or secret. Each test scans every answer, event, receipt line and
|
||||
// stderr line for every Triage key the stand-in ever held.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { keyPaths, readKey } from '../src/triage-key.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const NOW = Date.parse('2026-11-18T12:00:00.000Z');
|
||||
const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
|
||||
const MANAGE = 'fx1873-s4-manage';
|
||||
const KEY_PATH = '/v8/management/config/access/api-keys';
|
||||
const sha = s => createHash('sha256').update(s).digest('hex');
|
||||
const tag = dir => sha(dir).slice(0, 12);
|
||||
const id = key => sha(key).slice(0, 12);
|
||||
const b64 = () => randomBytes(32).toString('base64url');
|
||||
const code = name => e => e.code === name;
|
||||
|
||||
// Every Triage key the stand-in ever held, and every text a bus produced, across the file.
|
||||
const SEEN = new Set();
|
||||
const TEXTS = [];
|
||||
function leaks(text) {
|
||||
for (const key of SEEN) {
|
||||
const secret = key.slice(-43);
|
||||
if (text.includes(key) || text.includes(secret)) return key.slice(0, 8);
|
||||
for (let i = 0; i + 8 <= secret.length; i++) if (text.includes(secret.slice(i, i + 8))) return key.slice(0, 8);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Every stderr line while the test runs: the bus's model-proxy receipt lines go there.
|
||||
function captureStderr(t) {
|
||||
const write = process.stderr.write, lines = [];
|
||||
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
|
||||
t.after(() => { process.stderr.write = write; TEXTS.push(lines.join('')); });
|
||||
return lines;
|
||||
}
|
||||
|
||||
async function instance(t) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'tkb-')));
|
||||
const configDir = join(root, 'config');
|
||||
fs.mkdirSync(join(configDir, 'secrets'), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(configDir, 0o700); fs.chmodSync(join(configDir, 'secrets'), 0o700);
|
||||
fs.writeFileSync(join(configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
fs.mkdirSync(join(root, 'proxy'), { mode: 0o700 });
|
||||
const sentinel = `msk-${tag(configDir)}-sentinel-${b64()}`, orgKey = `mso-${tag(configDir)}-other-key-${b64()}`;
|
||||
// triagePuts counts the writes that changed a Triage name; the organization buses' own key
|
||||
// reconcile writes the list too, and those do not count.
|
||||
const state = { keys: [sentinel, 'foreign-client-key', orgKey], puts: [], triagePuts: 0 };
|
||||
const triageNames = list => JSON.stringify(list.filter(k => k.startsWith('mst-')).sort());
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.url !== KEY_PATH) {
|
||||
const key = req.headers.authorization?.slice(7);
|
||||
res.writeHead(state.keys.includes(key) ? 200 : 401); res.end('{}'); return;
|
||||
}
|
||||
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end('{}'); return; }
|
||||
if (req.method === 'GET') { res.end(JSON.stringify(state.keys)); return; }
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const next = JSON.parse(Buffer.concat(chunks));
|
||||
for (const k of next) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
state.puts.push(next);
|
||||
if (triageNames(next) !== triageNames(state.keys)) state.triagePuts++;
|
||||
state.keys = next;
|
||||
res.end('{"status":"ok"}');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
const closers = [];
|
||||
t.after(async () => {
|
||||
for (const close of closers.reverse()) await close().catch(() => {});
|
||||
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
|
||||
const receipts = join(root, 'proxy', 'mosaic-keys.receipts.jsonl');
|
||||
if (fs.existsSync(receipts)) TEXTS.push(fs.readFileSync(receipts, 'utf8'));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const f = {
|
||||
root, configDir, port, state, closers, rolesDir, system, sentinel, orgKey, clock: { now: NOW },
|
||||
prefix: `mst-${tag(configDir)}-triage-`,
|
||||
file: keyPaths(configDir).file,
|
||||
record: () => readKey(configDir),
|
||||
triageKeys: () => f.state.keys.filter(k => k.startsWith(f.prefix)),
|
||||
receipts: () => {
|
||||
const p = join(root, 'proxy', 'mosaic-keys.receipts.jsonl');
|
||||
return fs.existsSync(p) ? fs.readFileSync(p, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse) : [];
|
||||
},
|
||||
// A real organization bus on this instance. `proxy: false` starts it with no proxy settings, as
|
||||
// a bus on an instance with no proxy.json does.
|
||||
async bus(orgId, { proxy = true, triageKeys = {} } = {}) {
|
||||
const doc = businessDoc(root, orgId);
|
||||
doc.plugins = { ...doc.plugins, harness: ['pi'] };
|
||||
writeJson(join(configDir, 'businesses', `${orgId}.json`), doc);
|
||||
const business = loadBusiness(orgId, { dir: configDir, rolesDir }), resolved = {};
|
||||
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system, business, instance: name });
|
||||
const dataRoot = join(root, `${orgId}-bus`);
|
||||
fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
|
||||
const bus = await startBroker({ dataRoot, businesses: { [orgId]: busOrganization(business, resolved) },
|
||||
organization: { dir: configDir, rolesDir, system }, ...(proxy ? { proxy: { port, binary: '/fixture-unused' } } : {}),
|
||||
org: { id: orgId }, instanceDataRoot: root, instanceConfigDir: configDir,
|
||||
triageKeys: { intervalMs: 3_600_000, now: () => f.clock.now, ...triageKeys } });
|
||||
closers.push(() => bus.close());
|
||||
const cap = bus.broker.bindHuman({ business: orgId, human: business.human ?? doc.human, via: 'cli', outsideAgent: true });
|
||||
const ask = async (verb, args) => {
|
||||
try { const answer = await bus.broker.request(cap, { verb, args }); TEXTS.push(JSON.stringify(answer)); return answer; }
|
||||
catch (error) { TEXTS.push(JSON.stringify({ code: error.code, reason: error.reason, message: error.message, nextStep: error.nextStep })); throw error; }
|
||||
};
|
||||
const sweep = async () => { const r = await bus.triageKeySweep(); TEXTS.push(JSON.stringify(r)); return r; };
|
||||
return { bus, ask, sweep, dataRoot };
|
||||
},
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
// Every byte under a bus's data root (its store, with events and refusals, and its logs), as text.
|
||||
function eventsText(b, called = true) {
|
||||
const out = [];
|
||||
const walk = dir => {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const p = join(dir, name), st = fs.lstatSync(p);
|
||||
if (st.isDirectory()) walk(p);
|
||||
else if (st.isFile()) out.push(fs.readFileSync(p).toString('latin1'));
|
||||
}
|
||||
};
|
||||
walk(b.dataRoot);
|
||||
if (called) assert.ok(out.join('').includes('proxy.triage.key'), 'the store holds the verb\'s events');
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
test('ensure issues one key, a second ensure keeps it, and both answers carry ids only', async t => {
|
||||
captureStderr(t);
|
||||
const f = await instance(t);
|
||||
const a = await f.bus('alpha');
|
||||
const first = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
assert.equal(first.action, 'issued');
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
const record = f.record();
|
||||
assert.equal(first.keyId, record.keyId);
|
||||
assert.equal(first.keyId, id(f.triageKeys()[0]));
|
||||
assert.deepEqual(first.addedKeyIds, [record.keyId]);
|
||||
assert.equal(fs.statSync(f.file).mode & 0o777, 0o600);
|
||||
const second = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
assert.deepEqual(second, { op: 'ensure', action: 'held', addedKeyIds: [], removedKeyIds: [], keyId: record.keyId, rotateBy: record.rotateBy });
|
||||
assert.equal(f.triageKeys().length, 1, 'ensure twice gives one key');
|
||||
assert.equal(f.record().key, record.key);
|
||||
// Through a second riding bus on the same instance: still the one key.
|
||||
const b = await f.bus('beta');
|
||||
assert.equal((await b.ask('proxy.triage.key', { op: 'ensure' })).action, 'held');
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
assert.equal(f.state.triagePuts, 1, 'only the first ensure wrote the proxy list');
|
||||
// The receipt names the change by op and ids.
|
||||
const receipts = f.receipts().filter(r => r.op?.startsWith('triage.'));
|
||||
assert.deepEqual(receipts.map(r => [r.op, r.addedKeyIds, r.removedKeyIds]), [['triage.key.ensure', [record.keyId], []]]);
|
||||
for (const text of [eventsText(a), eventsText(b)]) assert.equal(leaks(text), null);
|
||||
});
|
||||
|
||||
test('ensure replaces a key the proxy lost, and revoke removes every Triage name and the file', async t => {
|
||||
captureStderr(t);
|
||||
const f = await instance(t);
|
||||
const a = await f.bus('alpha');
|
||||
const issued = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
// The proxy loses the key (removed by hand): ensure issues a new one and names the old as lost.
|
||||
f.state.keys = f.state.keys.filter(k => !k.startsWith(f.prefix));
|
||||
const replaced = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
assert.equal(replaced.action, 'replaced');
|
||||
assert.notEqual(replaced.keyId, issued.keyId);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
// An orphan in the namespace (a crash left it) goes with revoke too.
|
||||
const orphan = `${f.prefix}${b64()}`; SEEN.add(orphan);
|
||||
f.state.keys.push(orphan);
|
||||
const revoked = await a.ask('proxy.triage.key', { op: 'revoke' });
|
||||
assert.equal(revoked.action, 'revoked');
|
||||
assert.deepEqual(revoked.removedKeyIds.sort(), [replaced.keyId, id(orphan)].sort());
|
||||
assert.equal(f.triageKeys().length, 0);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
assert.equal(f.record(), null);
|
||||
// Revoke again: nothing to do, nothing written.
|
||||
const puts = f.state.triagePuts;
|
||||
assert.deepEqual(await a.ask('proxy.triage.key', { op: 'revoke' }), { op: 'revoke', action: 'none', addedKeyIds: [], removedKeyIds: [] });
|
||||
assert.equal(f.state.triagePuts, puts);
|
||||
// Namespace guard: the sentinel, the organization key and the foreign key are still there.
|
||||
for (const k of [f.sentinel, f.orgKey, 'foreign-client-key']) assert.ok(f.state.keys.includes(k), k.slice(0, 4));
|
||||
assert.equal(leaks(eventsText(a)), null);
|
||||
});
|
||||
|
||||
test('a bus that does not ride the owner\'s proxy refuses triage-no-riding-bus, and its sweep does nothing', async t => {
|
||||
captureStderr(t);
|
||||
const f = await instance(t);
|
||||
const loose = await f.bus('loose', { proxy: false });
|
||||
await assert.rejects(loose.ask('proxy.triage.key', { op: 'ensure' }), e => e.code === 'triage-no-riding-bus'
|
||||
&& /^Triage needs one organization that uses the owner's models\./.test(e.nextStep));
|
||||
await assert.rejects(loose.ask('proxy.triage.key', { op: 'revoke' }), code('triage-no-riding-bus'));
|
||||
assert.equal(f.state.triagePuts, 0);
|
||||
// With a key issued through a riding bus and its rotation due, the loose bus still does nothing.
|
||||
const a = await f.bus('alpha');
|
||||
await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
f.clock.now += 31 * DAY;
|
||||
assert.deepEqual(await loose.sweep(), { action: 'none' });
|
||||
assert.equal(f.state.triagePuts, 1);
|
||||
});
|
||||
|
||||
test('the sweep rotates when rotateBy comes, once across two buses that wake together, and again a rotation later', async t => {
|
||||
captureStderr(t);
|
||||
const f = await instance(t);
|
||||
const a = await f.bus('alpha'), b = await f.bus('beta');
|
||||
const issued = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
// Not due yet: neither bus touches the proxy.
|
||||
assert.deepEqual([await a.sweep(), await b.sweep()], [{ action: 'none' }, { action: 'none' }]);
|
||||
assert.equal(f.state.triagePuts, 1);
|
||||
f.clock.now = Date.parse(`${issued.rotateBy}T00:00:00Z`);
|
||||
const both = await Promise.all([a.sweep(), b.sweep()]);
|
||||
assert.deepEqual(both.map(r => r.action).sort(), ['none', 'rotated']);
|
||||
assert.equal(f.state.triagePuts, 2, 'two buses rotated once');
|
||||
const rotated = both.find(r => r.action === 'rotated');
|
||||
const record = f.record();
|
||||
assert.equal(rotated.keyId, record.keyId);
|
||||
assert.deepEqual(record.retiring.map(r => r.keyId), [issued.keyId]);
|
||||
assert.equal(f.triageKeys().length, 2, 'the old key stays live through its grace');
|
||||
// Inside the grace both buses leave it; at retireAt plus the margin one of them retires it.
|
||||
const retireAt = Date.parse(record.retiring[0].retireAt);
|
||||
f.clock.now = retireAt + 10_000;
|
||||
assert.deepEqual((await Promise.all([a.sweep(), b.sweep()])).map(r => r.action), ['none', 'none']);
|
||||
f.clock.now = retireAt + 30_000;
|
||||
const retired = await Promise.all([a.sweep(), b.sweep()]);
|
||||
assert.deepEqual(retired.map(r => r.action).sort(), ['none', 'retired']);
|
||||
assert.equal(f.state.triagePuts, 3);
|
||||
assert.deepEqual(f.triageKeys().map(id), [record.keyId]);
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
// A second rotation 30 days on: again once.
|
||||
f.clock.now = Date.parse(`${record.rotateBy}T00:00:00Z`) + HOUR;
|
||||
const again = await Promise.all([b.sweep(), a.sweep()]);
|
||||
assert.deepEqual(again.map(r => r.action).sort(), ['none', 'rotated']);
|
||||
assert.equal(f.state.triagePuts, 4);
|
||||
assert.equal(f.triageKeys().length, 2);
|
||||
// Namespace guard across every sweep.
|
||||
for (const k of [f.sentinel, f.orgKey, 'foreign-client-key']) assert.ok(f.state.keys.includes(k), k.slice(0, 4));
|
||||
const ops = f.receipts().filter(r => r.op?.startsWith('triage.')).map(r => r.op);
|
||||
assert.deepEqual(ops, ['triage.key.ensure', 'triage.key.rotate', 'triage.key.retire', 'triage.key.rotate']);
|
||||
for (const bus of [a, b]) assert.equal(leaks(eventsText(bus, bus === a)), null);
|
||||
});
|
||||
|
||||
test('the sweep never issues the first key, and a sweep refusal is a receipt line with a code only', async t => {
|
||||
const lines = captureStderr(t);
|
||||
const f = await instance(t);
|
||||
const a = await f.bus('alpha');
|
||||
f.clock.now += 400 * DAY;
|
||||
assert.deepEqual(await a.sweep(), { action: 'none' });
|
||||
assert.equal(f.state.triagePuts, 0);
|
||||
assert.equal(f.record(), null);
|
||||
// A due rotation on a proxy with no sentinel (it may be another proxy): refused, nothing written.
|
||||
await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
f.state.keys = f.state.keys.filter(k => k !== f.sentinel);
|
||||
f.clock.now += 31 * DAY;
|
||||
const r = await a.sweep();
|
||||
assert.deepEqual(r, { action: 'refused', code: 'proxy-not-configured' });
|
||||
assert.equal(f.state.triagePuts, 1);
|
||||
const refusal = lines.join('').split('\n').filter(l => l.includes('triage.key.sweep-refused'));
|
||||
assert.equal(refusal.length, 1);
|
||||
assert.deepEqual(JSON.parse(refusal[0].replace(/^model-proxy: /, '')), { action: 'triage.key.sweep-refused', code: 'proxy-not-configured', reason: 'triage-key-proxy-open' });
|
||||
// The same refusal on the next ticks is not logged again within the hour; after it, once more.
|
||||
const refusals = () => lines.join('').split('\n').filter(l => l.includes('triage.key.sweep-refused')).length;
|
||||
for (let i = 0; i < 3; i++) { f.clock.now += 30_000; assert.equal((await a.sweep()).code, 'proxy-not-configured'); }
|
||||
assert.equal(refusals(), 1);
|
||||
f.clock.now += HOUR;
|
||||
await a.sweep();
|
||||
assert.equal(refusals(), 2);
|
||||
});
|
||||
|
||||
test('a revoke stopped between the proxy write and the file is finished by the next revoke; ensure after a stopped revoke replaces the key', async t => {
|
||||
captureStderr(t);
|
||||
const f = await instance(t);
|
||||
let stage = null;
|
||||
const a = await f.bus('alpha', { triageKeys: { hook: s => { if (s === stage) throw new Error(`stop at ${s}`); } } });
|
||||
await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
stage = 'write';
|
||||
await assert.rejects(a.ask('proxy.triage.key', { op: 'revoke' }), e => e.code === 'storage-unavailable' && !/stop at/.test(e.message));
|
||||
assert.equal(f.triageKeys().length, 0, 'the proxy write happened');
|
||||
assert.ok(f.record(), 'the file stayed');
|
||||
stage = null;
|
||||
// ensure now sees a file whose key the proxy lacks: a new key, the old named lost.
|
||||
const replaced = await a.ask('proxy.triage.key', { op: 'ensure' });
|
||||
assert.equal(replaced.action, 'replaced');
|
||||
stage = 'rename';
|
||||
await assert.rejects(a.ask('proxy.triage.key', { op: 'revoke' }), code('storage-unavailable'));
|
||||
stage = null;
|
||||
assert.equal((await a.ask('proxy.triage.key', { op: 'revoke' })).action, 'revoked');
|
||||
assert.equal(f.record(), null);
|
||||
assert.equal(f.triageKeys().length, 0);
|
||||
});
|
||||
|
||||
test('no answer, event, receipt line or stderr line in this file holds any Triage key the stand-in saw', () => {
|
||||
assert.ok(SEEN.size >= 8, `only ${SEEN.size} keys were seen`);
|
||||
assert.ok(TEXTS.length >= 30, `only ${TEXTS.length} texts`);
|
||||
for (const text of TEXTS) assert.equal(leaks(text), null);
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// proxy-scope slice 4 (#1873): the bus verb proxy.triage.key at the broker. Only the instance
|
||||
// owner's path-bound proof (a human cap from the cli transport, outside any agent) reaches the
|
||||
// runtime's hook; an agent, a tester, a Console proof, a grant holder and an organization owner get
|
||||
// human-required, a reader read-only. The answer and the event carry key ids only, and a hook
|
||||
// failure that is not a bus refusal becomes storage-unavailable with no text of its own.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Broker, BusError } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { REFUSALS } from '../src/refusals.mjs';
|
||||
|
||||
const role = { authority: { withinRole: ['message.send'], crossRole: [] } };
|
||||
const code = name => error => error.code === name;
|
||||
const SUBJECT = { provider: 'fixture', iss: 'https://sso.invalid', sub: 'owner-1' };
|
||||
// A Triage key as triage-key.mjs makes them, so a leak check has a real-looking value to look for.
|
||||
const KEY = `mst-0123456789ab-triage-${'Q'.repeat(20)}xY_-${'z'.repeat(19)}`;
|
||||
|
||||
function fixture(t, { proxyTriageKey = null } = {}) {
|
||||
const store = new Store(fs.mkdtempSync(join(tmpdir(), 'tkv-bus-')));
|
||||
t.after(() => store.close());
|
||||
const b = new Broker({ store, proxyTriageKey, businesses: { demo: { id: 'demo', human: 'owner', arbiters: { technical: 'chief', delivery: 'chief' }, vars: { 'bus.tester': true }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: role } } } });
|
||||
return {
|
||||
store, b,
|
||||
human: b.bindHuman({ business: 'demo', human: 'owner', via: 'cli', outsideAgent: true }),
|
||||
tester: b.bindTester({ business: 'demo' }), reader: b.bindReader({ business: 'demo' }),
|
||||
agent: b.bindLaunch({ business: 'demo', role: 'coder', run: 'tkv-run', harness: 'pi' }),
|
||||
// The owner's Console proof, a granted account that holds org.hire, and an organization owner
|
||||
// who is not the instance owner: none is the path-bound cli proof.
|
||||
console: b.bindConsole({ business: 'demo', human: 'owner', subject: SUBJECT }),
|
||||
grant: b.bindHireConsole({ business: 'demo', actor: 'grantee', subject: { ...SUBJECT, sub: 'grantee-1' }, rights: ['org.hire', 'decide'] }),
|
||||
orgOwner: b.bindHireConsole({ business: 'demo', actor: 'orgowner', subject: { ...SUBJECT, sub: 'orgowner-1' }, rights: ['org.hire'], owner: true }),
|
||||
};
|
||||
}
|
||||
const events = store => JSON.stringify(store.all('SELECT body FROM events'));
|
||||
const bodies = store => store.all('SELECT body FROM events').map(r => JSON.parse(r.body));
|
||||
|
||||
test('proxy.triage.key refuses an agent, a tester, a Console proof, a grant holder and an organization owner with human-required, and a reader with read-only', async t => {
|
||||
let calls = 0;
|
||||
const f = fixture(t, { proxyTriageKey: async () => { calls++; return { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-19', addedKeyIds: ['0123456789ab'], removedKeyIds: [] }; } });
|
||||
for (const op of ['ensure', 'revoke']) {
|
||||
for (const [name, cap] of [['agent', f.agent], ['tester', f.tester], ['console', f.console], ['grant', f.grant], ['orgOwner', f.orgOwner]])
|
||||
assert.throws(() => f.b.request(cap, { verb: 'proxy.triage.key', args: { op } }), code('human-required'), `${name} ${op}`);
|
||||
assert.throws(() => f.b.request(f.reader, { verb: 'proxy.triage.key', args: { op } }), code('read-only'));
|
||||
}
|
||||
assert.equal(calls, 0);
|
||||
// The same verb runs for the owner's cli proof.
|
||||
const answer = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } });
|
||||
assert.equal(answer.action, 'issued');
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('proxy.triage.key takes op ensure or revoke and nothing else, and a bus with no hook is not-configured', async t => {
|
||||
let calls = 0;
|
||||
const f = fixture(t, { proxyTriageKey: async () => { calls++; return { action: 'none', addedKeyIds: [], removedKeyIds: [] }; } });
|
||||
for (const args of [{}, { op: 'rotate' }, { op: 'issue' }, { op: 'ensure', key: KEY }, { op: 'revoke', force: true }, { op: ['ensure'] }])
|
||||
assert.throws(() => f.b.request(f.human, { verb: 'proxy.triage.key', args }), code('invalid-request'), JSON.stringify(args));
|
||||
assert.throws(() => f.b.request(f.human, { verb: 'proxy.triage.key' }), code('invalid-request'));
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(events(f.store).includes(KEY), false);
|
||||
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
|
||||
const g = fixture(t);
|
||||
assert.throws(() => g.b.request(g.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), code('not-configured'));
|
||||
});
|
||||
|
||||
test('the answer and the event of each op carry ids only, even when the hook returns more', async t => {
|
||||
const seen = [];
|
||||
const f = fixture(t, { proxyTriageKey: async op => {
|
||||
seen.push(op);
|
||||
// A hook that returns the key beside the ids: the broker copies the named fields only.
|
||||
return op === 'ensure'
|
||||
? { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-19', addedKeyIds: ['0123456789ab'], removedKeyIds: ['ba9876543210'], key: KEY, old: { key: KEY } }
|
||||
: { action: 'revoked', addedKeyIds: [], removedKeyIds: ['0123456789ab'], key: KEY };
|
||||
} });
|
||||
const ensure = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } });
|
||||
assert.deepEqual(ensure, { op: 'ensure', action: 'issued', addedKeyIds: ['0123456789ab'], removedKeyIds: ['ba9876543210'], keyId: '0123456789ab', rotateBy: '2026-12-19' });
|
||||
const revoke = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } });
|
||||
assert.deepEqual(revoke, { op: 'revoke', action: 'revoked', addedKeyIds: [], removedKeyIds: ['0123456789ab'] });
|
||||
assert.deepEqual(seen, ['ensure', 'revoke']);
|
||||
assert.deepEqual(bodies(f.store).filter(b => b.call === 'proxy.triage.key'), [{ call: 'proxy.triage.key', ...ensure }, { call: 'proxy.triage.key', ...revoke }]);
|
||||
for (const text of [JSON.stringify(ensure), JSON.stringify(revoke), events(f.store)]) {
|
||||
assert.equal(text.includes(KEY), false);
|
||||
assert.equal(text.includes(KEY.slice(-43)), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('an answer the broker cannot vouch for refuses proxy-client-response and records no allowed event', async t => {
|
||||
const answers = [
|
||||
null, { action: 'issued' },
|
||||
{ action: 'deleted', keyId: '0123456789ab', addedKeyIds: [], removedKeyIds: [] },
|
||||
{ action: 'issued', keyId: KEY, addedKeyIds: [], removedKeyIds: [] },
|
||||
{ action: 'issued', keyId: '0123456789ab', addedKeyIds: [KEY], removedKeyIds: [] },
|
||||
{ action: 'held', keyId: '0123456789ab', addedKeyIds: [], removedKeyIds: 'none' },
|
||||
];
|
||||
let next = 0;
|
||||
const f = fixture(t, { proxyTriageKey: async () => answers[next++] });
|
||||
for (const answer of answers)
|
||||
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), code('proxy-client-response'), JSON.stringify(answer));
|
||||
await assert.rejects(Promise.resolve().then(() => fixture(t, { proxyTriageKey: async () => ({ action: 'issued', addedKeyIds: [], removedKeyIds: [] }) }))
|
||||
.then(g => g.b.request(g.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } })), code('proxy-client-response'));
|
||||
assert.equal(bodies(f.store).some(b => b.call === 'proxy.triage.key'), false);
|
||||
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
|
||||
});
|
||||
|
||||
test('a bus refusal from the hook passes through with its guidance; any other failure is storage-unavailable and names nothing from the error', async t => {
|
||||
const f = fixture(t, { proxyTriageKey: async op => { throw op === 'ensure' ? new BusError('triage-no-riding-bus') : Object.assign(new Error(`boom ${KEY} /home/x`), { code: 'EACCES' }); } });
|
||||
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), e => e.code === 'triage-no-riding-bus'
|
||||
&& /Triage needs one organization that uses the owner's models/.test(e.nextStep ?? REFUSALS['triage-no-riding-bus'].nextStep));
|
||||
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } }), e => e.code === 'storage-unavailable'
|
||||
&& !JSON.stringify({ ...e, message: e.message }).includes(KEY.slice(-43)) && !String(e.message).includes('/home/x'));
|
||||
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
|
||||
});
|
||||
|
||||
test('the two slice 4 codes have refusal-table entries with a next step and no absolute path', () => {
|
||||
for (const c of ['triage-no-riding-bus', 'triage-key-rotated']) {
|
||||
const entry = REFUSALS[c];
|
||||
assert.ok(entry, c);
|
||||
assert.equal(typeof entry.nextStep, 'string', c);
|
||||
assert.ok(entry.nextStep.length > 20, c);
|
||||
assert.equal(/\/(home|mnt|srv|tmp)\//.test(entry.nextStep), false, c);
|
||||
}
|
||||
assert.match(REFUSALS['triage-no-riding-bus'].nextStep, /^Triage needs one organization that uses the owner's models\./);
|
||||
});
|
||||
@@ -1425,3 +1425,100 @@ installer writes `<dataRoot>/.deployed` as mode 0444 naming the instance.
|
||||
`webui-service.sh` refuses accounts and deployed instances because its user
|
||||
manager runs under a human or development seat uid. The receipt uid identifies
|
||||
the invoking process; it does not attribute a human or resist tampering by that uid.
|
||||
|
||||
## Triage route (#1873, held for Jason's ruling)
|
||||
|
||||
`mosaic triage route show` prints the Triage route the instance owner set, or
|
||||
`triage route: not set` (exit 0). `mosaic triage route set --model KEY
|
||||
--harness NAME --cap TOKENS --time-zone ZONE [--revision N]` writes it. Both
|
||||
refuse inside an agent run before anything is read (exit 3).
|
||||
|
||||
The file is `<dataRoot>/triage/route.json`
|
||||
(packages/webui/src/triage-route-store.mjs): a catalogue model key, a harness
|
||||
name and a daily cap leaf `{limit, since, reset, timeZone}`. It holds no env
|
||||
value and no key. The day resets at 00:00 in the zone given, which has no
|
||||
default; an unknown zone refuses. The first cap counts from the time it is
|
||||
set; a later change keeps that `since`, as an organization's token limits do,
|
||||
so lowering the cap never drops tokens already spent. The directory is 0700 and the file 0600,
|
||||
owned by the running user; a link, a non-file, a wrong mode or owner, or an
|
||||
unknown field refuses (exit 3). A write is compare-and-set on `revision`
|
||||
(`--revision 0`: only when nothing is set), atomic, and appends one line with
|
||||
the old and new values to `route-receipts.jsonl`. A write that died leaves
|
||||
`route.lock`; the next write refuses and names it, and you remove it by hand.
|
||||
If the route changed but its receipt line could not be written, the write
|
||||
refuses with `triage-route-unrecorded` (exit 3) and names the new revision.
|
||||
`set` checks the harness against packages/plugins/harness/; it does not check
|
||||
the model key against a catalogue yet.
|
||||
|
||||
The Console does not read this file: the Triage host keeps `route: null` until
|
||||
the wiring slice.
|
||||
|
||||
## Triage key (#1873)
|
||||
|
||||
`mosaic triage key issue|rotate|retire|status` manage Triage's own model
|
||||
proxy client key. Every verb refuses inside an agent run before anything is
|
||||
read (exit 3), and takes no options.
|
||||
|
||||
The key is `mst-<tag>-triage-<43 base64url>`, where `<tag>` is the first 12
|
||||
hex of sha256 of the config directory, the tag on the instance's own `msk-`
|
||||
sentinel. An org bus reconciles only its `mso-<tag>-<org>-key-` names and a
|
||||
no-org bus only its `msk-<tag>-` names, so neither removes it. The file is
|
||||
`<configDir>/secrets/triage/model`: `{version, key, keyId, issuedAt,
|
||||
rotateBy, retiring}`. The directory is 0700 and the file 0600, owned by the
|
||||
running user. A link, a non-file, a second hard link, a wrong mode or owner, a
|
||||
file over 64 KiB, or a record that does not match the shape refuses every verb
|
||||
with `triage-key-unreadable` (exit 3).
|
||||
|
||||
- `issue` adds one key and writes the file. It refuses `triage-key-issued`
|
||||
when a key is already issued; that is `rotate`.
|
||||
- `rotate` adds a new key and moves the old one to `retiring`, with a retire
|
||||
time of now plus `rotateGraceMinutes` from proxy.json, where the bus reads
|
||||
it (default 120). `rotateBy` is 30 days on, as for an org key. An old key
|
||||
the proxy no longer holds is dropped at once.
|
||||
- `retire` removes retiring keys whose grace has passed or that the proxy no
|
||||
longer holds. It changes nothing before then.
|
||||
|
||||
Nothing runs on a timer. The retire time is the earliest a retiring key may
|
||||
go; the key stays live in the proxy until someone runs `retire` (or a later
|
||||
`rotate` or `issue`) after it. `rotateBy` works the same way: `status` marks
|
||||
it due, and only `rotate` replaces the key.
|
||||
- `status` prints whether a key is issued, its key id, its age, its rotate-by
|
||||
day, each retiring key, what the proxy list holds, a set fence, any key in
|
||||
the Triage namespace the file does not hold, and the next command. It takes
|
||||
no lock and writes nothing.
|
||||
|
||||
`issue`, `rotate` and `retire` hold the instance proxy lock that org buses
|
||||
take (`<dataRoot>/proxy`). Each reads the list, refuses without this
|
||||
instance's sentinel (`triage-key-proxy-open`), reads it again and refuses if
|
||||
it moved (`triage-key-raced`), sets the fence, writes, reads back and clears
|
||||
the fence. The proxy changes first and the file second. Each run that
|
||||
changes something appends one line of key ids, never keys, to
|
||||
`<dataRoot>/proxy/mosaic-keys.receipts.jsonl`. That file is checked under the
|
||||
lock before anything changes; an unsafe one refuses
|
||||
`triage-key-receipts-unsafe`. A receipt line that still fails after the change
|
||||
refuses `triage-key-unrecorded`. No output, error or receipt holds a key.
|
||||
|
||||
The file is written to a 0600 temp file in the same directory, synced, renamed
|
||||
into place, and the directory is synced. A failed directory sync after the
|
||||
rename refuses `triage-key-unsynced`: the file is in place but may not survive
|
||||
a power loss. `proxy-lock-busy` means another proxy writer holds the lock; if
|
||||
none is running, `mosaic proxy fence status` shows the lock state.
|
||||
|
||||
After a crash:
|
||||
|
||||
- Killed after the proxy write and before the read-back: the fence stays set
|
||||
and every proxy writer on the instance refuses `proxy-uncertain`. `status`
|
||||
shows the fence. Restart the proxy, run `mosaic proxy fence clear
|
||||
--proxy-restarted`, then run the verb again.
|
||||
- Killed after the read-back and before the file write: the proxy holds a key
|
||||
the file does not. `status` names it; the next `issue`, `rotate` or `retire`
|
||||
removes it. A file that could not be written refuses
|
||||
`triage-key-unwritten` and says to run the verb again.
|
||||
- Killed after the temp file is written and before its rename: a
|
||||
`.model.<pid>.<hex>.tmp` file that may hold a key stays in the triage
|
||||
directory. `status` counts it; the next `issue`, `rotate` or `retire`
|
||||
removes it under the lock.
|
||||
- A `retire` killed after the proxy write leaves a retiring key the proxy no
|
||||
longer holds. `status` marks it; the next `retire` drops it from the file.
|
||||
|
||||
Nothing gives the key to the Triage host yet; that is the wiring slice.
|
||||
@@ -56,6 +56,7 @@ import { ORG_CONFIG, runConfigCommand } from "../../organization/src/config-comm
|
||||
import { devCommand, DEV_USAGE, fixtureLaunchEnv, fixtureLauncherOptions } from "./dev-fixture.mjs";
|
||||
import { runCommand, RUN_USAGE } from "./run-evidence.mjs";
|
||||
import { tasksWriteCommand, TASKS_WRITE_OPS, TASKS_WRITE_USAGE } from "./tasks-write.mjs";
|
||||
import { triageCommand, TRIAGE_USAGE } from "./triage.mjs";
|
||||
|
||||
export const USAGE = `usage:
|
||||
${ACCOUNTS_USAGE}
|
||||
@@ -103,6 +104,7 @@ export const USAGE = `usage:
|
||||
mosaic console start [--dev-local-owner [--dev-insecure-bind ADDR --dev-allow-host NAME[,NAME...]]] [--detach] [--port auto|N]
|
||||
mosaic console stop|status
|
||||
mosaic console restart
|
||||
${TRIAGE_USAGE}
|
||||
${DEV_USAGE}
|
||||
${RUN_USAGE}`;
|
||||
|
||||
@@ -818,6 +820,8 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
|
||||
if (verb === "launches") return launches(rest, io, deps);
|
||||
if (verb === "bus") return bus(rest, io, deps);
|
||||
if (verb === "console") return consoleCommand(rest, io, deps);
|
||||
// triage-route-store (#1873): the owner's Triage route file, read and written as the person.
|
||||
if (verb === "triage") return triageCommand(rest, io, deps);
|
||||
if (verb === "dev") return devCommand(rest, io, { system: deps.system });
|
||||
if (verb === "run") return runCommand(rest, io, { system: deps.system, callFor: (p) => channelCallFor(p, io, deps) });
|
||||
if (verb === "-h" || verb === "--help") return io.stdout.write(`${USAGE}\n`);
|
||||
|
||||
@@ -215,12 +215,19 @@ const relayed = (failed) => failed && (typeof failed.message === "string" ? { ..
|
||||
// and names the module rather than escaping the host. What it threw is named by its system code
|
||||
// or its class, never its message, which the host didn't write (#1873).
|
||||
function call(name, what, fn) {
|
||||
try {
|
||||
return fn();
|
||||
} catch (e) {
|
||||
const failed = (e) => {
|
||||
const thrown = quietMessage(e, "a host file") ?? `threw ${/^[A-Za-z][A-Za-z0-9]{0,39}$/.test(String(e?.name)) ? e.name : "a value"} without a system code`;
|
||||
throw new Refusal("harness-failed", `harness ${name} ${what}: ${thrown}`);
|
||||
};
|
||||
let out;
|
||||
try {
|
||||
out = fn();
|
||||
} catch (e) {
|
||||
failed(e);
|
||||
}
|
||||
// #1873 pi-unpin re-check 7: a module may answer with a promise (pi's preflight runs its fit
|
||||
// check as child processes). The caller awaits it; a rejection is refused as a throw is.
|
||||
return typeof out?.then === "function" ? Promise.resolve(out).then(undefined, failed) : out;
|
||||
}
|
||||
|
||||
// host: startHost()'s handle. tracker: true when the broker has task verbs for
|
||||
@@ -302,6 +309,11 @@ export function createLauncher({
|
||||
let ticking = false;
|
||||
const stopping = new Set();
|
||||
const refusedThreads = new Map();
|
||||
// #1873 chat-fail F2: the refusal and message each thread session's plain line was asked for.
|
||||
const noticedThreads = new Map();
|
||||
// #1873 F2: the last refusal seen per thread start, and the last failed post of its line.
|
||||
const refusalSeen = new Map();
|
||||
const noticeFailed = new Map();
|
||||
const startedFor = new Map();
|
||||
// Row 271 (264d): each clear's stop time (by op), and each clear refusal logged once (by op and code).
|
||||
const clearStops = new Map();
|
||||
@@ -449,14 +461,11 @@ export function createLauncher({
|
||||
for (const m of [primary, fallback].filter(Boolean)) {
|
||||
if (!on.includes(m.harness)) throw new Refusal("harness-off", `harness ${m.harness} isn't switched on in plugins.harness`);
|
||||
}
|
||||
// One harness through a fresh loader, so a refusal never leaves an earlier load's module in use.
|
||||
const harnessOf = async (m) => {
|
||||
const loader = makeLoader({ dataRoot:system.instanceRoot ?? dataRoot, log: (entry) => record({ ...entry, instance }) });
|
||||
const { refused } = await loader.load({ harness: [m.harness] });
|
||||
const { refused, module } = await freshHarness(m, (entry) => record({ ...entry, instance }));
|
||||
// #1873: a loader message can quote the module's path or its load error; only a
|
||||
// missing-export one, which names the export, is relayed. Any other refusal names its code.
|
||||
if (refused.length) throw new Refusal("harness-refused", `harness ${m.harness}: ${refused.map((r) => r.code === "missing-export" ? `${r.code}: ${relay(r.message)}` : String(r.code)).join("; ")}`);
|
||||
const module = loader.modules("harness")[0];
|
||||
const levels = call(m.harness, "levels", () => module.levels());
|
||||
if (!levels.includes(m.thinking)) throw new Refusal("thinking-unsupported", `harness ${m.harness} takes thinking ${levels.join(", ")}, not ${m.thinking}`);
|
||||
return module;
|
||||
@@ -551,7 +560,7 @@ export function createLauncher({
|
||||
const pickRoute = async (proxyOf) => {
|
||||
let sessionProxy = await proxyOf(primary);
|
||||
// #1873: a preflight's message is the module's own text, relayed with host paths replaced.
|
||||
const failed = relayed(call(primary.harness, "preflight", () => harness.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy })));
|
||||
const failed = relayed(await call(primary.harness, "preflight", () => harness.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy })));
|
||||
if (failed) {
|
||||
if (!fallback) throw new Refusal(failed.code, failed.message);
|
||||
// The fallback only on a failed primary preflight, and only at launch (row 65). Any refusal of
|
||||
@@ -561,7 +570,7 @@ export function createLauncher({
|
||||
throw e;
|
||||
});
|
||||
sessionProxy = await proxyOf(fallback);
|
||||
const also = relayed(call(fallback.harness, "preflight", () => second.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy })));
|
||||
const also = relayed(await call(fallback.harness, "preflight", () => second.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy })));
|
||||
if (also) throw new Refusal(also.code, `fallback ${fallback.harness}: ${also.message} (primary ${primary.harness}: ${failed.message})`);
|
||||
[model, harness, route, routeReason] = [fallback, second, "fallback", failed.code];
|
||||
}
|
||||
@@ -735,7 +744,7 @@ export function createLauncher({
|
||||
if (store) compactions(store, model.harness, harness, { instance, thread, session, run });
|
||||
const toolSocket = join(runDir, "tools.sock");
|
||||
const turnMarker = join(runDir, "turn.done");
|
||||
const version = harnessVersion !== undefined ? harnessVersion : call(model.harness, "version", () => harness.version({ env }));
|
||||
const version = harnessVersion !== undefined ? harnessVersion : await call(model.harness, "version", () => harness.version({ env }));
|
||||
// Row 137 (#1631): a role and thread holding an approved, unspent merge decision get land_work.
|
||||
// The broker checks the decision again on every land; this only decides what the bundle shows.
|
||||
// Row 156 (#1651): a non-thread instance's land and landing come from one landHolders read, so a
|
||||
@@ -896,7 +905,13 @@ export function createLauncher({
|
||||
}
|
||||
children.set(run, exited);
|
||||
const outputWatch = admittedProxy ? watchModelOutput({ runDir, armAtFirstTurn: true, keyId: modelKeyId, seconds: system.proxy.firstOutputSeconds ?? 120,
|
||||
stop: () => host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId }), receipt: record }) : null;
|
||||
stop: async () => {
|
||||
const out = await host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId });
|
||||
// #1873 chat-fail F2: the message the stopped turn was on gets one plain line, as a failed turn's.
|
||||
try { await host.op({ op: 'failureNotice', record: { business: b.id, run, code: 'proxy-stall' } }); }
|
||||
catch (err) { log(`run ${run}: failure line refused: ${err.code ?? 'failed'}`); }
|
||||
return out;
|
||||
}, receipt: record }) : null;
|
||||
exited.then(async ({ code, signal }) => {
|
||||
outputWatch?.cancel();
|
||||
let receipt;
|
||||
@@ -1066,8 +1081,30 @@ export function createLauncher({
|
||||
await start({ instance: t.instance, launchedBy: b.human, ...where, legacy: t.legacy, legacyThread: legacyThreads.has(t.thread), ...(await check(t.instance, where)) });
|
||||
startedFor.set(key, signature);
|
||||
refusedThreads.delete(key);
|
||||
noticedThreads.delete(key);
|
||||
refusalSeen.delete(key);
|
||||
noticeFailed.delete(key);
|
||||
} catch (e) {
|
||||
const code = e instanceof Refusal ? e.code : "launch-failed";
|
||||
// #1873 chat-fail F2: the person who wrote gets one plain line per message the refusal
|
||||
// leaves unanswered. Asked once per code and message; the bus keeps it to one per message.
|
||||
// launch-failed can be a lost race that the next try wins, so it gets a line only when
|
||||
// the same message is refused with it twice in a row. A post that fails is tried again
|
||||
// on the next tick, and its failure is logged once.
|
||||
const noticed = `${code}|${signature}`;
|
||||
const repeated = refusalSeen.get(key) === noticed;
|
||||
refusalSeen.set(key, noticed);
|
||||
if (noticedThreads.get(key) !== noticed && (code !== "launch-failed" || repeated)) {
|
||||
try {
|
||||
await host.op({ op: "failureNotice", record: { business: b.id, thread: t.thread, session: t.session, code } });
|
||||
noticedThreads.set(key, noticed);
|
||||
noticeFailed.delete(key);
|
||||
} catch (err) {
|
||||
const failed = `${noticed}|${err.code ?? "failed"}`;
|
||||
if (noticeFailed.get(key) !== failed) log(`thread ${t.thread} session ${t.session}: failure line refused: ${err.code ?? "failed"}`);
|
||||
noticeFailed.set(key, failed);
|
||||
}
|
||||
}
|
||||
// Logged once per code, not once per tick.
|
||||
if (refusedThreads.get(key) === code) return;
|
||||
refusedThreads.set(key, code);
|
||||
@@ -1637,6 +1674,38 @@ export function createLauncher({
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
// One harness ({ harness: name }) through a fresh loader, so a refusal never leaves an earlier
|
||||
// load's module in use: { refused, module }, module null when refused. A launch (harnessOf) and
|
||||
// the start's fit warm-up below (#1873 re-check 8) both load through here.
|
||||
async function freshHarness(m, log) {
|
||||
const loader = makeLoader({ dataRoot:system.instanceRoot ?? dataRoot, log });
|
||||
const { refused } = await loader.load({ harness: [m.harness] });
|
||||
return { refused, module: refused.length ? null : loader.modules("harness")[0] };
|
||||
}
|
||||
|
||||
// #1873 pi-unpin re-check 8: each switched-on harness module with ready() (pi's fit check) starts
|
||||
// it here, in the background, so the first launch joins the check in flight instead of starting
|
||||
// it. Nothing waits on it: a launch still awaits its own preflight, which shares this check or
|
||||
// reads its pass. A warm-up that fails or throws is dropped; it caches nothing, and the launch's
|
||||
// preflight runs the check again. Re-check 9: a harness plugin the warm-up can't load leaves one
|
||||
// launch log entry, by its code only (a launch that loads it records the message).
|
||||
function warmHarnesses() {
|
||||
const on = Array.isArray(b.plugins?.harness) ? b.plugins.harness : [];
|
||||
for (const name of on) {
|
||||
(async () => {
|
||||
let logged = false;
|
||||
const refusal = (entry) => {
|
||||
if (logged || entry?.event !== "plugin-refused") return;
|
||||
logged = true;
|
||||
record({ event: "plugin-refused", kind: entry.kind, name: entry.name, code: entry.code, during: "warm-up" });
|
||||
};
|
||||
const { module } = await freshHarness({ harness: name }, refusal);
|
||||
if (typeof module?.ready === "function") await module.ready({ env });
|
||||
})().catch(() => {});
|
||||
}
|
||||
}
|
||||
if (launches) warmHarnesses();
|
||||
|
||||
host.beforeClose(close);
|
||||
return { business: b, registry, listen, launchPm, fromSession, tick, close };
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { listOrgs, orgLock, resolveOrg } from '../../organization/src/org-regist
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { templateRender, validateOrg, createOrg, showOrg, updateOrg, queueInit, queueShow, projectRepoInit, projectRepoShow, projectRepoSet, deleteOrg, archiveOrg, restoreOrg } from '../../organization/src/org-service.mjs';
|
||||
import { installedStarterPacks } from '../../plugins/src/starter-pack.mjs';
|
||||
import { appendReceipt } from '../../model-proxy/src/admin.mjs';
|
||||
import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs';
|
||||
import { loadSystem, orgPaths, rolesDir } from './config.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
@@ -173,6 +174,18 @@ async function templateCommand(args, io, deps) {
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
const busStartVerb = id => `mosaic bus start ${id} --dev-local-owner --detach`;
|
||||
// #1873 ride-default: `mosaic org update` that takes cliproxy off an organization records the removal
|
||||
// in the instance's proxy receipts first, where Ride all reads it, as the Console's admin save does.
|
||||
// A record that cannot be written refuses the update and writes nothing. A stale revision records
|
||||
// nothing and is left to updateOrg's own refusal.
|
||||
const providerList = doc => (Array.isArray(doc?.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []);
|
||||
export async function orgUpdate(ctx, id, doc, { ifRevision, record = org => appendReceipt(ctx.dataRoot, { time: new Date().toISOString(), op: 'ride-removed', org }) } = {}) {
|
||||
const shown = await showOrg(ctx, id);
|
||||
if (shown.revision === ifRevision && providerList(shown.doc).includes('cliproxy') && !providerList(doc).includes('cliproxy')) {
|
||||
try { await record(id); } catch { throw new CliError('the removal of the model proxy could not be recorded, so nothing was saved', 3); }
|
||||
}
|
||||
return updateOrg(ctx, id, doc, { ifRevision });
|
||||
}
|
||||
export async function orgCommand(args, io, deps = {}) {
|
||||
try {
|
||||
// #1873 T1: the definitions verbs take their own options.
|
||||
@@ -195,7 +208,7 @@ export async function orgCommand(args, io, deps = {}) {
|
||||
const instance = devOwnerInstance(io.env); const system = deps.system ?? loadSystem({ env: io.env, instance }); const ctx = { configDir: configDir(io.env), dataRoot: system.dataRoot, instance, principal: DEV_OWNER };
|
||||
if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
else if (words[0] === 'create' && words.length === 2) { allowed([], ['--from']); result = await createOrg(ctx, words[1], await document(need('--from'))); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await updateOrg(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await orgUpdate(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'archive' && words.length === 2) result = await archiveOrg(ctx, words[1], { ...lifecycle, busStop: busStopForDelete, copyRemote: await (deps.copyRemoteFor ?? copyRemoteFor)(ctx) });
|
||||
else if (words[0] === 'restore' && words.length === 2) {
|
||||
const startBus = !p.flags.has('--no-bus');
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// #1873 triage-route-store: the owner's terminal verbs for the Triage route file,
|
||||
// <dataRoot>/triage/route.json (packages/webui/src/triage-route-store.mjs).
|
||||
//
|
||||
// mosaic triage route show
|
||||
// mosaic triage route set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N]
|
||||
//
|
||||
// Both are human verbs: an agent run is refused before anything is read (exit 3), from this
|
||||
// process's environment and the one the command was given, as the bus and Console lifecycle verbs
|
||||
// refuse it. `show` with no file prints "not set" and exits 0. Without --revision a write
|
||||
// compares with the revision read under the store's lock; pass --revision from `show` to make the
|
||||
// write conditional on what was shown (0: only when no route is set yet).
|
||||
//
|
||||
// Nothing here wires the route into the Triage host: the Console keeps `route: null` until the
|
||||
// wiring slice. `set` checks the harness against the repository's harness modules; it does not
|
||||
// check the model key against a catalogue, since none exists outside an organization's bus yet.
|
||||
//
|
||||
// mosaic triage key issue | rotate | retire | status
|
||||
//
|
||||
// Triage's own model proxy client key (packages/bus/src/triage-key.mjs, shared with the bus). Human verbs as well,
|
||||
// refused in an agent run before anything is read. No output names a key, only its id.
|
||||
import { lstatSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readRoute, RouteStoreError, writeRoute } from "../../webui/src/triage-route-store.mjs";
|
||||
import { loadSystem } from "./config.mjs";
|
||||
import { configDir } from "../../organization/src/organization-config.mjs";
|
||||
import { issueKey, keyPaths, keyStatus, retireKeys, rotateKey, TriageKeyError } from "../../bus/src/triage-key.mjs";
|
||||
import { CliError } from "./errors.mjs";
|
||||
import { refuseInsideAgent } from "./transport.mjs";
|
||||
|
||||
export const TRIAGE_USAGE = "mosaic triage route show | set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N] | key issue | rotate | retire | status";
|
||||
const KEY_VERBS = ["issue", "rotate", "retire", "status"];
|
||||
const HARNESS_ROOT = fileURLToPath(new URL("../../plugins/harness/", import.meta.url));
|
||||
const VALUES = ["--model", "--harness", "--cap", "--time-zone", "--revision"];
|
||||
const WHOLE = /^(0|[1-9][0-9]*)$/;
|
||||
// The actor every terminal write records: the instance owner, the only person who runs this verb.
|
||||
const ACTOR = "owner";
|
||||
|
||||
const usage = (why) => new CliError(`${why}\nusage: ${TRIAGE_USAGE}`, 4);
|
||||
|
||||
// Option names, never values, in a refusal.
|
||||
function parse(args) {
|
||||
const values = {}, positional = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i];
|
||||
if (VALUES.includes(a)) {
|
||||
if (i + 1 >= args.length) throw usage(`${a} needs one value`);
|
||||
if (Object.hasOwn(values, a)) throw usage(`${a} is given twice`);
|
||||
values[a] = args[++i];
|
||||
} else if (a.startsWith("--")) throw usage("unknown option");
|
||||
else positional.push(a);
|
||||
}
|
||||
return { values, positional };
|
||||
}
|
||||
|
||||
function whole(text, name) {
|
||||
if (!WHOLE.test(text)) throw new CliError(`triage-route-invalid: ${name} must be a whole number`, 2);
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
function knownHarness(name) {
|
||||
if (!/^[a-z][a-z0-9-]{0,31}$/.test(name)) return false;
|
||||
try { return lstatSync(join(HARNESS_ROOT, name, "index.mjs")).isFile(); } catch { return false; }
|
||||
}
|
||||
|
||||
function storeError(error) {
|
||||
if (!(error instanceof RouteStoreError)) throw error;
|
||||
return new CliError(`${error.code}: ${error.message}`, error.code === "triage-route-invalid" ? 2 : 3);
|
||||
}
|
||||
|
||||
function show(route) {
|
||||
if (!route) return "triage route: not set\n";
|
||||
const { cap } = route;
|
||||
return [
|
||||
`triage route: revision ${route.revision}`,
|
||||
`model: ${route.model}`,
|
||||
`harness: ${route.harness}`,
|
||||
`cap: ${cap.limit} tokens a day, resets ${cap.reset} ${cap.timeZone}, counted since ${cap.since}`,
|
||||
`updated: ${route.updatedAt} by ${route.updatedBy}`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// A key error prints its code and fixed words. Anything else becomes one fixed line, so no value
|
||||
// that an unexpected error might carry reaches the terminal.
|
||||
function keyError(error) {
|
||||
if (error instanceof CliError) return error;
|
||||
if (error instanceof TriageKeyError) return new CliError(`${error.code}: ${error.message}`, error.exitCode);
|
||||
return new CliError("triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status", 3);
|
||||
}
|
||||
|
||||
const age = (ms) => {
|
||||
const m = Math.max(0, Math.floor(ms / 60_000));
|
||||
return `${Math.floor(m / 1440)}d ${Math.floor((m % 1440) / 60)}h ${m % 60}m`;
|
||||
};
|
||||
const ids = (list) => (list.length ? list.join(", ") : "none");
|
||||
|
||||
function statusText({ record, proxy }, nowMs, file) {
|
||||
const lines = [`triage key: ${record ? "issued" : "not issued"}`, `file: ${file}`];
|
||||
const rotateDue = record && Date.parse(`${record.rotateBy}T00:00:00Z`) <= nowMs;
|
||||
const retireDue = record ? record.retiring.filter((r) => Date.parse(r.retireAt) <= nowMs) : [];
|
||||
if (record) {
|
||||
lines.push(`key id: ${record.keyId}`, `issued: ${record.issuedAt} (age ${age(nowMs - Date.parse(record.issuedAt))})`, `rotate by: ${record.rotateBy}${rotateDue ? " (due)" : ""}`);
|
||||
record.retiring.forEach((r, i) => {
|
||||
const held = proxy.retiringHeld?.[i];
|
||||
lines.push(`retiring: ${r.keyId}, live until a retire after ${r.retireAt}${Date.parse(r.retireAt) <= nowMs ? " (due)" : ""}${held === false ? " (not in the proxy list)" : ""}`);
|
||||
});
|
||||
}
|
||||
const state = {
|
||||
"not-set-up": "not set up for this instance (no proxy.json)",
|
||||
"no-sentinel": "its key list has no sentinel for this instance",
|
||||
unreadable: `not read (${proxy.code})`,
|
||||
read: record ? (proxy.holdsKey ? "holds the key" : "does not hold the key") : "read",
|
||||
}[proxy.state];
|
||||
lines.push(`proxy: ${state}`);
|
||||
if (proxy.fence) lines.push("proxy fence: set, an earlier proxy write has an uncertain outcome");
|
||||
if (proxy.leftoverTemps) lines.push(`leftover temp files in the triage secrets directory: ${proxy.leftoverTemps} (the next issue, rotate or retire removes them)`);
|
||||
if (proxy.orphanKeyIds?.length) lines.push(`keys in the Triage namespace the file does not hold: ${ids(proxy.orphanKeyIds)}`);
|
||||
let next;
|
||||
if (proxy.fence) next = "restart the proxy, then mosaic proxy fence clear --proxy-restarted";
|
||||
else if (proxy.state !== "read") next = proxy.state === "not-set-up" ? "set up the model proxy first (mosaic proxy init)" : "check the proxy with mosaic proxy status";
|
||||
else if (!record) next = "mosaic triage key issue";
|
||||
else if (!proxy.holdsKey || rotateDue) next = "mosaic triage key rotate";
|
||||
else if (retireDue.length || proxy.leftoverTemps || proxy.orphanKeyIds?.length || proxy.retiringHeld?.includes(false)) next = "mosaic triage key retire";
|
||||
else next = "nothing";
|
||||
lines.push(`next: ${next}`, "");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function keyCommand(sub, args, io, deps) {
|
||||
if (!KEY_VERBS.includes(sub)) throw usage("unknown triage key command");
|
||||
if (args.length) throw usage(args[0].startsWith("--") ? "unknown option" : "unexpected argument");
|
||||
try {
|
||||
const system = deps.system ?? loadSystem({ env: io.env });
|
||||
const dir = configDir(io.env);
|
||||
const now = deps.now ? () => deps.now().getTime() : Date.now;
|
||||
const opts = { configDir: dir, system, now, uid: deps.triageKeyUid, fileUid: deps.triageKeyFileUid, hook: deps.triageKeyHook };
|
||||
if (sub === "status") {
|
||||
io.stdout.write(statusText(await keyStatus(opts), now(), keyPaths(dir).file));
|
||||
return;
|
||||
}
|
||||
if (sub === "issue") {
|
||||
const r = await issueKey(opts);
|
||||
io.stdout.write(`triage key issued: ${r.keyId}, rotate by ${r.rotateBy}\nfile: ${keyPaths(dir).file}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed keys this file did not hold: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
if (sub === "rotate") {
|
||||
const r = await rotateKey(opts);
|
||||
io.stdout.write(`triage key rotated: ${r.keyId}, rotate by ${r.rotateBy}\n`);
|
||||
io.stdout.write(r.old.lost
|
||||
? `old key ${r.old.keyId} was not in the proxy list; nothing to retire\n`
|
||||
: `old key ${r.old.keyId} stays live until mosaic triage key retire runs at or after ${r.old.retireAt}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
const r = await retireKeys(opts);
|
||||
io.stdout.write(r.removedKeyIds.length ? `triage key retire: removed ${ids(r.removedKeyIds)}\n` : "triage key retire: nothing to remove\n");
|
||||
} catch (e) { throw keyError(e); }
|
||||
}
|
||||
|
||||
export function triageCommand(rest, io, deps = {}) {
|
||||
refuseInsideAgent(process.env);
|
||||
refuseInsideAgent(io.env);
|
||||
const [noun, sub, ...args] = rest;
|
||||
if (noun === "key" && sub !== undefined) return keyCommand(sub, args, io, deps);
|
||||
if (noun !== "route" || !["show", "set"].includes(sub)) throw usage("unknown triage command");
|
||||
const { values, positional } = parse(args);
|
||||
if (positional.length) throw usage("unexpected argument");
|
||||
const dataRoot = () => (deps.system ?? loadSystem({ env: io.env })).dataRoot;
|
||||
if (sub === "show") {
|
||||
if (Object.keys(values).length) throw usage("show takes no options");
|
||||
let route;
|
||||
try { route = readRoute(dataRoot()); } catch (e) { throw storeError(e); }
|
||||
io.stdout.write(show(route));
|
||||
return;
|
||||
}
|
||||
for (const name of ["--model", "--harness", "--cap", "--time-zone"]) if (!Object.hasOwn(values, name)) throw usage(`set needs ${name}`);
|
||||
if (!knownHarness(values["--harness"])) throw new CliError("triage-route-invalid: no harness module has that name", 2);
|
||||
const input = {
|
||||
model: values["--model"], harness: values["--harness"], limit: whole(values["--cap"], "--cap"),
|
||||
timeZone: values["--time-zone"], by: ACTOR,
|
||||
...(Object.hasOwn(values, "--revision") ? { revision: whole(values["--revision"], "--revision") } : {}),
|
||||
};
|
||||
let route;
|
||||
try { route = writeRoute(dataRoot(), input, deps.now ? { now: deps.now } : {}); } catch (e) { throw storeError(e); }
|
||||
io.stdout.write(`triage route set: revision ${route.revision}\n`);
|
||||
}
|
||||
@@ -105,6 +105,7 @@ async function start(t, { f, adapter }, { businessId = "acme", orgRoot, copyTran
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -99,6 +99,7 @@ async function start(t, { f, adapter }) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -30,6 +30,7 @@ const ops = {
|
||||
credentialStatus: m => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: m => runtime.threadsState(m.business),
|
||||
threadIdle: m => runtime.threadIdle(m.record),
|
||||
failureNotice: m => runtime.failureNotice(m.record),
|
||||
mayLaunch: m => runtime.mayLaunch(m),
|
||||
landHeld: m => runtime.landHeld(m.record),
|
||||
landHolders: m => runtime.landHolders(m.business),
|
||||
|
||||
+2
-1
@@ -16,7 +16,7 @@ import { pushWorking, fetchReview } from '../../../harness/src/git-tools.mjs';
|
||||
import { callTool } from '../../../harness/src/tools.mjs';
|
||||
import { toolServer } from '../../../harness/src/runner.mjs';
|
||||
import { buildBundle } from '../../../harness/src/bundle.mjs';
|
||||
import { HARNESS } from '../../../harness/tests/helpers.mjs';
|
||||
import { HARNESS, harnessReady } from '../../../harness/tests/helpers.mjs';
|
||||
import { ensureCheckouts } from '../../../seat/src/checkout.mjs';
|
||||
import { newRun, Registry, readSessions, writeSessionFile, workspaceDir } from '../../../seat/src/session.mjs';
|
||||
import { startTimeOf } from '../../src/host.mjs';
|
||||
@@ -127,6 +127,7 @@ async function runtime() {
|
||||
const cap = bus.bindLaunch(launch_record).cap;
|
||||
roles[role] = { cap, run: id, workspace, runDir };
|
||||
call(role, 'role.claim');
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
const bundle = buildBundle({ dir: join(runDir, 'bundle'), resolved, contract: readFileSync(resolved.contract, 'utf8'),
|
||||
arbiter: role === 'cto', tracker: Boolean(resolved.tracker), credentials: [], skillsDir: join(dataRoot, 'skills-enabled'), harness: HARNESS.pi,
|
||||
harnessVersion: '0.85.1', session: { run: id, workspace, checkouts, toolSocket: join(runDir, 'tools.sock'), turnMarker: join(runDir, 'turn.done') } });
|
||||
|
||||
@@ -77,6 +77,7 @@ async function start(t, { f, adapter }, threadIdle) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => threadIdle(runtime, m),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -95,6 +95,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -48,6 +48,7 @@ function requestHost(x) {
|
||||
landHeld: m => x.bus.landHeld(m.record), landHolders: m => x.bus.landHolders(m.business),
|
||||
sessionClears: m => x.bus.sessionClears(m.business),
|
||||
threadsState: m => x.bus.threadsState(m.business), lifecycleRequests: m => x.bus.lifecycleRequests(m.business),
|
||||
failureNotice: m => x.bus.failureNotice(m.record),
|
||||
'request.admission': m => x.bus.admission(m), 'request.launches': m => x.bus.requestLaunches(m.business),
|
||||
'request.launchResult': m => x.bus.requestLaunchResult(m.record), 'request.manifest': m => x.bus.requestManifest(m.record),
|
||||
'request.release': m => x.bus.requestRelease(m.cap, m.record), 'request.chief': m => x.bus.requestChief(m.business),
|
||||
|
||||
@@ -12,7 +12,8 @@ import { createHash } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { createInterface } from "node:readline";
|
||||
import { connect } from "node:net";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, watch, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
@@ -24,6 +25,8 @@ import { bootConfig, loadSystem } from "../src/config.mjs";
|
||||
import { cmdlineOf, startHost, startTimeOf } from "../src/host.mjs";
|
||||
import { createLauncher } from "../src/launcher.mjs";
|
||||
import { mockAnthropic, REPO } from "../../harness/tests/helpers.mjs";
|
||||
import { piStandIn } from "../../harness/tests/pi-stand-in.mjs";
|
||||
import * as pi from "../../plugins/harness/pi/index.mjs";
|
||||
import { fakeHarnesses, fixture, HOST_CREDENTIALS, tmp, withoutHostCredentials } from "./helpers.mjs";
|
||||
|
||||
const FAKE = fileURLToPath(new URL("../../harness/tests/fixtures/fake-adapter.mjs", import.meta.url));
|
||||
@@ -151,7 +154,8 @@ const log = (f) => readFileSync(launchLogFile(f.dataRoot, "acme"), "utf8").trim(
|
||||
test('P3 proxy key reaches the spawned runner but never session.json or the bundle', { skip, timeout: 30000 }, async t => {
|
||||
const proxy = { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' };
|
||||
const prepared = prepare(t, doc => {
|
||||
doc.launch.models['claude-opus-5-5'] = { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' };
|
||||
// #1873 harness-matrix: a Claude route on pi is refused, so the key check rides a non-Claude proxy route.
|
||||
doc.launch.models['claude-opus-5-5'] = { provider: 'proxy', model: 'fixture-route-model', route: 'glm' };
|
||||
return doc;
|
||||
});
|
||||
const { launcher, f, close } = await setup(t, doc => doc, prepared, { testProxy: proxy });
|
||||
@@ -265,6 +269,142 @@ test("bus start --pm: the launcher instance (the chief of staff) runs under its
|
||||
assert.equal(end.exitCode, 0);
|
||||
});
|
||||
|
||||
// #1873 pi-unpin S1/S2: the version label comes from the pi the module finds. A pi whose --version
|
||||
// fails gives a null label, and the launch still goes ahead.
|
||||
test("pi-unpin: a pi named by MOSAIC_PI_BIN that exits 1 on --version records a null harnessVersion and still launches", { skip, timeout: 30000 }, async (t) => {
|
||||
const prepared = prepare(t);
|
||||
const pkg = join(prepared.root, "pi-prefix", "lib", "node_modules", "@earendil-works", "pi-coding-agent");
|
||||
mkdirSync(join(pkg, "dist", "bundle"), { recursive: true });
|
||||
writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "3.0.0", bin: { pi: "dist/bundle/cli.js" } }));
|
||||
// #1873 S3: the stand-in passes the fit check; only its --version fails.
|
||||
writeFileSync(join(pkg, "dist", "bundle", "cli.js"), piStandIn({ versionExit: 1 }), { mode: 0o755 });
|
||||
mkdirSync(join(prepared.root, "pi-prefix", "bin"));
|
||||
const bin = join(prepared.root, "pi-prefix", "bin", "pi");
|
||||
symlinkSync("../lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", bin);
|
||||
prepared.f.env.MOSAIC_PI_BIN = bin;
|
||||
// env() reads the bus's own environment, as the launcher's is process.env outside tests.
|
||||
const before = process.env.MOSAIC_PI_BIN;
|
||||
process.env.MOSAIC_PI_BIN = bin;
|
||||
t.after(() => { if (before === undefined) delete process.env.MOSAIC_PI_BIN; else process.env.MOSAIC_PI_BIN = before; });
|
||||
const { f, launcher, close } = await setup(t, (doc) => doc, prepared, { harnessVersion: undefined });
|
||||
const chief = await launcher.launchPm();
|
||||
assert.equal(chief.harness, "pi");
|
||||
const [s] = readSessions(f.dataRoot);
|
||||
const manifest = JSON.parse(readFileSync(join(s.runDir, "bundle", "manifest.json"), "utf8"));
|
||||
assert.equal(manifest.harnessVersion, null);
|
||||
assert.equal(await close(), 0);
|
||||
});
|
||||
|
||||
// #1873 re-check 8: a pi stand-in under root/pi-prefix, as an npm prefix holds it. Returns its bin.
|
||||
function piPrefix(root, knobs) {
|
||||
const pkg = join(root, "pi-prefix", "lib", "node_modules", "@earendil-works", "pi-coding-agent");
|
||||
mkdirSync(join(pkg, "dist", "bundle"), { recursive: true });
|
||||
writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "3.0.0", bin: { pi: "dist/bundle/cli.js" } }));
|
||||
writeFileSync(join(pkg, "dist", "bundle", "cli.js"), piStandIn(knobs), { mode: 0o755 });
|
||||
mkdirSync(join(root, "pi-prefix", "bin"));
|
||||
const bin = join(root, "pi-prefix", "bin", "pi");
|
||||
symlinkSync("../lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", bin);
|
||||
return bin;
|
||||
}
|
||||
// Each fit run makes one scratch directory under tmpdir(), so a watch there counts the runs.
|
||||
// quiet() waits until no run has started for a while, so a check an earlier test left going
|
||||
// (the real pi's, warmed by its launcher) is not counted.
|
||||
function fitRuns(t) {
|
||||
const made = new Set();
|
||||
const watcher = watch(tmpdir(), (event, name) => { if (name && name.startsWith("mosaic-pi-fit-")) made.add(name); });
|
||||
t.after(() => watcher.close());
|
||||
const quiet = async () => {
|
||||
let n;
|
||||
do { n = made.size; await new Promise((r) => setTimeout(r, 700)); } while (made.size !== n);
|
||||
};
|
||||
return { made, quiet };
|
||||
}
|
||||
function busPiBin(t, prepared, bin) {
|
||||
prepared.f.env.MOSAIC_PI_BIN = bin;
|
||||
const before = process.env.MOSAIC_PI_BIN;
|
||||
process.env.MOSAIC_PI_BIN = bin;
|
||||
t.after(() => { if (before === undefined) delete process.env.MOSAIC_PI_BIN; else process.env.MOSAIC_PI_BIN = before; });
|
||||
}
|
||||
|
||||
// #1873 pi-unpin re-check 8: the launcher starts pi's fit check when it starts, before any launch,
|
||||
// and does not wait for it. The first launch joins that check: the two together make one check's
|
||||
// runs, not two.
|
||||
test("pi-unpin re-check 8: the launcher starts pi's fit check when it starts, and the first launch joins it", { skip, timeout: 60000 }, async (t) => {
|
||||
const { made, quiet } = fitRuns(t);
|
||||
// One check on its own, for another stand-in: how many runs it makes.
|
||||
const alone = piPrefix(tmp(t, "mosaic-launch-pi-"), {});
|
||||
await quiet();
|
||||
made.clear();
|
||||
assert.equal(await pi.preflight({ env: { ANTHROPIC_API_KEY: "stand-in", MOSAIC_PI_BIN: alone } }), null);
|
||||
await quiet();
|
||||
const runs = made.size;
|
||||
assert.ok(runs > 10, `one check made ${runs} runs`);
|
||||
const prepared = prepare(t);
|
||||
busPiBin(t, prepared, piPrefix(prepared.root, {}));
|
||||
made.clear();
|
||||
const { launcher, close } = await setup(t, (doc) => doc, prepared, { harnessVersion: undefined });
|
||||
// No launch yet, and the check is under way.
|
||||
await until(() => made.size > 0, 10000).catch(() => assert.fail("no fit run started before the first launch"));
|
||||
const chief = await launcher.launchPm();
|
||||
assert.equal(chief.harness, "pi");
|
||||
await quiet();
|
||||
assert.equal(made.size, runs, "the launch joined the check the launcher started");
|
||||
assert.equal(await close(), 0);
|
||||
});
|
||||
|
||||
// A warm-up that fails leaves no unhandled rejection and keeps no verdict: the next preflight runs
|
||||
// the check again and refuses on its own.
|
||||
test("pi-unpin re-check 8: a fit check the launcher starts that fails is dropped: no unhandled rejection, nothing kept", { skip, timeout: 60000 }, async (t) => {
|
||||
const { made, quiet } = fitRuns(t);
|
||||
const unhandled = [];
|
||||
const seen = (e) => unhandled.push(e);
|
||||
process.on("unhandledRejection", seen);
|
||||
t.after(() => process.off("unhandledRejection", seen));
|
||||
const prepared = prepare(t);
|
||||
const bin = piPrefix(prepared.root, { dropFlags: ["--no-themes"] });
|
||||
busPiBin(t, prepared, bin);
|
||||
await quiet();
|
||||
made.clear();
|
||||
const { close } = await setup(t, (doc) => doc, prepared, { harnessVersion: undefined });
|
||||
await until(() => made.size > 0, 10000).catch(() => assert.fail("no fit run started before the first launch"));
|
||||
// This preflight joins the failing check; then it is gone.
|
||||
const env = { ANTHROPIC_API_KEY: "stand-in", MOSAIC_PI_BIN: bin };
|
||||
const refusal = { code: "harness-feature-missing", message: "pi 9.9.9 (MOSAIC_PI_BIN) lacks --no-themes" };
|
||||
assert.deepEqual(await pi.preflight({ env }), refusal);
|
||||
await quiet();
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.deepEqual(unhandled, []);
|
||||
made.clear();
|
||||
assert.deepEqual(await pi.preflight({ env }), refusal);
|
||||
await quiet();
|
||||
assert.ok(made.size > 0, "the failed check was kept");
|
||||
assert.equal(await close(), 0);
|
||||
});
|
||||
|
||||
// Re-check 9: a harness plugin the warm-up can't load leaves one launch log entry, by its code
|
||||
// only, so the message (which may name a host path) stays out of it.
|
||||
test("pi-unpin re-check 9: a harness plugin the launcher's warm-up can't load leaves one launch log entry, by code only", { skip, timeout: 30000 }, async (t) => {
|
||||
const given = prepare(t, (doc) => {
|
||||
doc.plugins = { ...doc.plugins, harness: [...doc.plugins.harness, "broken"] };
|
||||
return doc;
|
||||
});
|
||||
const makeLoader = await fakeHarnesses(t, { pi: given.adapter, "claude-code": given.adapter }, (write) => {
|
||||
write("harness", "broken", `throw new Error("broken at /srv/fit-secret-path");\n`);
|
||||
});
|
||||
const { f, close } = await setup(t, undefined, given, { makeLoader });
|
||||
const refused = () => existsSync(launchLogFile(f.dataRoot, "acme")) ? log(f).filter((e) => e.event === "plugin-refused") : [];
|
||||
await until(() => refused().length > 0, 10000).catch(() => assert.fail("the warm-up left no record of the refused plugin"));
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
const entries = refused();
|
||||
assert.equal(entries.length, 1, JSON.stringify(entries));
|
||||
const [entry] = entries;
|
||||
assert.deepEqual(Object.keys(entry).sort(), ["at", "code", "during", "event", "kind", "name"]);
|
||||
assert.deepEqual([entry.kind, entry.name, entry.during], ["harness", "broken", "warm-up"]);
|
||||
assert.match(entry.code, /^[a-z][a-z-]+$/);
|
||||
assert.doesNotMatch(readFileSync(launchLogFile(f.dataRoot, "acme"), "utf8"), /fit-secret-path/);
|
||||
assert.equal(await close(), 0);
|
||||
});
|
||||
|
||||
test("the chief of staff launches a coder through its launch tool; the coder answers; refusals name their code", { skip, timeout: 30000 }, async (t) => {
|
||||
const { f, launcher, client, cto } = await setup(t);
|
||||
const sock = launchSocketPath(f.dataRoot);
|
||||
|
||||
@@ -95,6 +95,7 @@ async function start(t, { f, adapter }, options = {}) {
|
||||
definitionScan: (m) => runtime.definitionScan({ business: m.business, definition: m.definition, entry: m.entry }),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -21,12 +21,20 @@ const id = value => createHash('sha256').update(value).digest('hex').slice(0,12)
|
||||
// #774 R2: extra names more harnesses to switch on and load (a fallback route's); real names the
|
||||
// harnesses loaded as the real module, so their own preflight runs; hostEnv adds launcher env
|
||||
// such as MOSAIC_CLAUDE_BIN.
|
||||
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so the pi stream case reads
|
||||
// a non-Claude model the proxy serves in Anthropic format (upstream other) from a stand-in catalogue.
|
||||
// The chief's model key stays claude-opus-5-5; on pi its upstream model is not a Claude name.
|
||||
export const PI_CHIEF_MODEL='fixture-chief-model';
|
||||
const STREAM_OTHER=Object.freeze({provider:'other',model:'fixture-stream-model',module:'cliproxy',upstream:'other'});
|
||||
const streamCatalogue=()=>({invalidate(){},read:async()=>({status:'ready',observedAt:'2026-11-19T00:00:00.000Z',notices:[],
|
||||
models:[{key:'other-fixture-stream-model',module:'cliproxy',upstream:'other',provider:'other',model:'fixture-stream-model',label:'other / fixture-stream-model',available:true,reason:'unverified',harnesses:['claude-code','pi']}]})});
|
||||
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false,harness='pi',bwrap=null,admit=null,extra=[],real=[],hostEnv={},modelStream=null,modelCatalogue=null}={}){
|
||||
const root=fs.mkdtempSync(join(tmpdir(),'ml653-')),closers=[],history=new Set(['fx653-manage']),proxyReceipts=[],logs=[];
|
||||
let server,bus,launcher,stderr;const trace={preflightAttempts:0,successfulPreflights:0,enableBeforeSpawn:[],bindings:[],stalls:[],ops:[]};
|
||||
const checkHistory=entries=>{const text=JSON.stringify(entries);for(const value of history)if(text.includes(value))throw Error('fixture credential leaked');};
|
||||
t.after(async()=>{const failures=[];for(const close of [...closers].reverse()){try{await close();}catch{failures.push('owned-close');}}try{server?.closeAllConnections();if(server?.listening)await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));}catch{failures.push('owned-server-close');}try{checkHistory({logs,proxyReceipts,trace});}catch{failures.push('value-free-receipts');}if(stderr)process.stderr.write=stderr;try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('owned-root-close');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned managed fixture cleanup failed');});
|
||||
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:[harness,...extra]};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness};doc.roles.chief.vars.model='claude-opus-5-5';if(modelStream){doc.launch.models['claude-opus-5-5']={provider:'anthropic',model:'claude-opus-5-5'};}return doc;});
|
||||
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:[harness,...extra]};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness};doc.roles.chief.vars.model='claude-opus-5-5';if(harness==='pi')doc.launch.models['claude-opus-5-5']={provider:'zai',model:PI_CHIEF_MODEL};if(modelStream){doc.launch.models['claude-opus-5-5']=harness==='pi'?STREAM_OTHER:{provider:'anthropic',model:'claude-opus-5-5'};if(harness==='pi')doc.plugins={...doc.plugins,'model-provider':['cliproxy']};}return doc;});
|
||||
if(modelStream&&harness==='pi'&&!modelCatalogue)modelCatalogue=streamCatalogue();
|
||||
const env={PATH:process.env.PATH,HOME:process.env.HOME,TMPDIR:process.env.TMPDIR,MOSAIC_CONFIG:f.config,MOSAIC_ROLES_DIR:f.roles,...hostEnv};
|
||||
// The nonproxy positive fixture supplies its own fake pi login. Managed
|
||||
// proxy fixtures deliberately hold no upstream credential at all.
|
||||
@@ -90,6 +98,7 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
|
||||
case 'landRelease':return bus.landRelease(m.record);
|
||||
case 'threadsState':return bus.threadsState(m.business);
|
||||
case 'threadIdle':return bus.threadIdle(m.record);
|
||||
case 'failureNotice':return bus.failureNotice(m.record);
|
||||
case 'lifecycleRequests':return bus.lifecycleRequests(m.business);
|
||||
case 'sessionClears':return bus.sessionClears(m.business);
|
||||
default:throw Error('fixture unrequested trusted operation');
|
||||
|
||||
@@ -11,8 +11,11 @@ async function launched(t,options){const f=await managedLaunchFixture(t,options)
|
||||
test('653 actual managed proxy launch stays idle unarmed then stops first silent turn through trusted runtime',{skip,timeout:30000},async t=>{
|
||||
const {f,s}=await launched(t);assert.equal(f.trace.successfulPreflights,1);assert.deepEqual(f.trace.enableBeforeSpawn,[true]);assert.equal(f.trace.bindings[0].modelKeyId,f.expectedKeyId());assert.equal(s.modelKeyId,f.expectedKeyId());assert.notEqual(s.pid,s.runnerPid);
|
||||
await pause(1250);assert.equal(f.trace.stalls.length,0,'idle beyond configured initial budget does not stop');assert.equal(fs.existsSync(join(s.runDir,'proxy-first-turn')),false);assert.equal(startTimeOf(s.runnerPid),s.runnerStartTime);
|
||||
const before=process.hrtime.bigint();f.send('SILENT');await waitFor(()=>fs.existsSync(join(s.runDir,'proxy-first-turn')),'actual managed adapter turn publishes marker');const stamp=BigInt(fs.readFileSync(join(s.runDir,'proxy-first-turn'),'utf8').trim().split(' ')[1]);assert.ok(stamp>=before&&stamp<=process.hrtime.bigint());assert.equal(fs.existsSync(join(s.runDir,'proxy-first-output')),false);
|
||||
await waitFor(()=>f.trace.stalls.length===1,'actual caller watcher reaches trusted modelStall');assert.deepEqual(f.trace.stalls,[{run:s.run,keyId:s.modelKeyId,stopped:true}]);await waitFor(()=>f.sessions().length===0,'normal managed exit unregisters session');assert.equal(f.launchLog().some(r=>r.action==='proxy-stall'&&r.keyIds?.includes(s.modelKeyId)&&!r.code),true);f.assertHistoryGuard();f.valueFree();
|
||||
const before=process.hrtime.bigint();const sent=f.send('SILENT');await waitFor(()=>fs.existsSync(join(s.runDir,'proxy-first-turn')),'actual managed adapter turn publishes marker');const stamp=BigInt(fs.readFileSync(join(s.runDir,'proxy-first-turn'),'utf8').trim().split(' ')[1]);assert.ok(stamp>=before&&stamp<=process.hrtime.bigint());assert.equal(fs.existsSync(join(s.runDir,'proxy-first-output')),false);
|
||||
await waitFor(()=>f.trace.stalls.length===1,'actual caller watcher reaches trusted modelStall');assert.deepEqual(f.trace.stalls,[{run:s.run,keyId:s.modelKeyId,stopped:true}]);await waitFor(()=>f.sessions().length===0,'normal managed exit unregisters session');assert.equal(f.launchLog().some(r=>r.action==='proxy-stall'&&r.keyIds?.includes(s.modelKeyId)&&!r.code),true);f.assertHistoryGuard();
|
||||
// #1873 chat-fail F2: the stopped turn's message gets one plain line, as a failed turn's.
|
||||
const line=await f.reply(sent);assert.equal(line.body,"The turn failed: the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup.\nDetails: stopped: proxy-stall");assert.deepEqual([line.from_role,line.from_run,line.class],['chief','bus','RESULT']);
|
||||
f.valueFree();
|
||||
});
|
||||
test('653 actual managed proxy output cancels caller watcher and first timestamp never resets',{skip,timeout:30000},async t=>{
|
||||
const {f,s}=await launched(t);const first=f.send('OUTPUT');const answer=await f.reply(first);assert.equal(answer.body,'fx653-private-output');const file=join(s.runDir,'proxy-first-turn'),stamp=fs.readFileSync(file,'utf8');assert.equal(fs.statSync(file).mode&0o777,0o600);assert.equal(fs.readFileSync(join(s.runDir,'proxy-first-output'),'utf8'),'output\n');
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// #1873 ride-default, re-check 3 P1-1: `mosaic org update` that takes cliproxy off an organization
|
||||
// records the removal in the instance's proxy receipts before it writes, as the Console's admin save
|
||||
// does, so Ride all leaves the organization off.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { orgUpdate } from '../src/org.mjs';
|
||||
import * as orgService from '../../organization/src/org-service.mjs';
|
||||
import { createProxyAdmin } from '../../model-proxy/src/admin-control.mjs';
|
||||
import { receiptFile } from '../../model-proxy/src/admin.mjs';
|
||||
|
||||
const owner = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' };
|
||||
function scratch(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'org-upd-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
return { configDir, dataRoot, instance: 'test', principal: owner };
|
||||
}
|
||||
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
|
||||
const withProviders = (doc, list) => ({ ...doc, plugins: { ...(doc.plugins ?? {}), 'model-provider': list } });
|
||||
async function cliproxyOrg(ctx, id) {
|
||||
const doc = withProviders(await orgService.templateRender(id), ['cliproxy']);
|
||||
await orgService.createOrg(ctx, id, doc);
|
||||
return orgService.showOrg(ctx, id);
|
||||
}
|
||||
|
||||
test('the reviewer probe: an organization taken off cliproxy by mosaic org update is skipped by Ride all as removed', async t => {
|
||||
const ctx = scratch(t);
|
||||
const shown = await cliproxyOrg(ctx, 'cli');
|
||||
await orgUpdate(ctx, 'cli', withProviders(shown.doc, []), { ifRevision: shown.revision });
|
||||
assert.deepEqual((await orgService.showOrg(ctx, 'cli')).doc.plugins['model-provider'], []);
|
||||
assert.deepEqual(receipts(ctx.dataRoot).map(r => [r.op, r.org]), [['ride-removed', 'cli']]);
|
||||
const writes = [];
|
||||
const call = async verb => {
|
||||
if (verb === 'plugins') return { revision: 'r', plugins: { 'model-provider': [] } };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { writes.push('cli'); return { revision: 'r2' }; }
|
||||
throw new Error(`unexpected ${verb}`);
|
||||
};
|
||||
const proxy = createProxyAdmin({ dataRoot: ctx.dataRoot, configDir: ctx.configDir, unit: { unit: 'u', status: async () => ({}) }, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}),
|
||||
riders: async () => [{ id: 'cli', fixture: false, cliproxy: false, changes: '', call }] });
|
||||
const r = await proxy.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 'cli', reason: 'removed' }]);
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test('mosaic org update records only a removal of cliproxy, and saves nothing when the record cannot be written', async t => {
|
||||
const ctx = scratch(t);
|
||||
const recorded = [];
|
||||
const record = async id => { recorded.push(id); };
|
||||
// Keeping cliproxy, or an organization that never had it, records nothing.
|
||||
let shown = await cliproxyOrg(ctx, 'keep');
|
||||
await orgUpdate(ctx, 'keep', { ...shown.doc }, { ifRevision: shown.revision, record });
|
||||
const plain = await orgService.templateRender('plain');
|
||||
await orgService.createOrg(ctx, 'plain', withProviders(plain, []));
|
||||
shown = await orgService.showOrg(ctx, 'plain');
|
||||
await orgUpdate(ctx, 'plain', { ...shown.doc }, { ifRevision: shown.revision, record });
|
||||
assert.deepEqual(recorded, []);
|
||||
// A stale revision records nothing and is refused by the service.
|
||||
shown = await cliproxyOrg(ctx, 'stale');
|
||||
await assert.rejects(orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision + 1, record }), { code: 'revision-conflict' });
|
||||
assert.deepEqual(recorded, []);
|
||||
// A record that fails refuses the update: the organization keeps cliproxy, at the same revision.
|
||||
await assert.rejects(orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision, record: async () => { throw Object.assign(new Error('disk full at /x/proxy-admin.jsonl'), { code: 'ENOSPC' }); } }),
|
||||
err => err.exitCode === 3 && err.message === 'the removal of the model proxy could not be recorded, so nothing was saved');
|
||||
const after = await orgService.showOrg(ctx, 'stale');
|
||||
assert.deepEqual(after.doc.plugins['model-provider'], ['cliproxy']); assert.equal(after.revision, shown.revision);
|
||||
// The removal itself records once, before the write.
|
||||
await orgUpdate(ctx, 'stale', withProviders(shown.doc, []), { ifRevision: shown.revision, record: async id => { recorded.push(id); assert.deepEqual((await orgService.showOrg(ctx, 'stale')).doc.plugins['model-provider'], ['cliproxy'], 'recorded before the write'); } });
|
||||
assert.deepEqual(recorded, ['stale']);
|
||||
});
|
||||
|
||||
test('the mosaic org update command records the removal in the instance\'s own proxy receipts', async t => {
|
||||
const { spawnSync } = await import('node:child_process');
|
||||
const { resolve } = await import('node:path');
|
||||
const repo = resolve(import.meta.dirname, '../../..');
|
||||
const home = fs.mkdtempSync(join(tmpdir(), 'org-upd-cli-'));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
const env = { ...process.env, HOME: home, MOSAIC_CONFIG: join(home, '.config/mosaic-orgupd/config.json') };
|
||||
const run = (cmd, ...args) => { const r = spawnSync(join(repo, cmd), args, { cwd: repo, env, encoding: 'utf8' }); assert.equal(r.status, 0, r.stderr); return r.stdout; };
|
||||
run('scripts/bootstrap.sh', '--instance', 'orgupd');
|
||||
const on = join(home, 'on.json'), off = join(home, 'off.json');
|
||||
const doc = withProviders(await orgService.templateRender('cliw'), ['cliproxy']);
|
||||
fs.writeFileSync(on, JSON.stringify(doc)); fs.writeFileSync(off, JSON.stringify(withProviders(doc, [])));
|
||||
run('scripts/mosaic', 'org', 'create', 'cliw', '--from', on);
|
||||
const { revision } = JSON.parse(run('scripts/mosaic', 'org', 'show', 'cliw', '--json'));
|
||||
run('scripts/mosaic', 'org', 'update', 'cliw', '--from', off, '--if-revision', String(revision));
|
||||
assert.deepEqual(JSON.parse(run('scripts/mosaic', 'org', 'show', 'cliw', '--json')).doc.plugins['model-provider'], []);
|
||||
assert.deepEqual(receipts(join(home, '.mosaic-orgupd')).map(r => [r.op, r.org]), [['ride-removed', 'cliw']]);
|
||||
});
|
||||
@@ -90,6 +90,8 @@ async function routed(t, harness) {
|
||||
const makeLoader = await fakeHarnesses(t, { pi: null, 'claude-code': null }, write => {
|
||||
// fsthrows: its preflight reads a missing file, so the error's message quotes the path.
|
||||
write('harness', 'fsthrows', `export * from ${PI};\nimport { readFileSync } from "node:fs";\nexport function preflight() { readFileSync(${JSON.stringify(absent)}); }\n`);
|
||||
// fsrejects (#1873 re-check 8): an async preflight, as pi's is, whose promise rejects with that error.
|
||||
write('harness', 'fsrejects', `export * from ${PI};\nimport { readFileSync } from "node:fs";\nexport async function preflight() { readFileSync(${JSON.stringify(absent)}); }\n`);
|
||||
// plainthrows: a plain Error whose message quotes a host path, as a module's own text.
|
||||
write('harness', 'plainthrows', `export * from ${PI};\nexport function preflight() { throw new Error(${JSON.stringify(`cannot read ${absent}`)}); }\n`);
|
||||
// pathfails: a preflight that returns a failure whose message quotes a host path.
|
||||
@@ -146,6 +148,15 @@ test('a harness whose preflight throws a system error refuses harness-failed nam
|
||||
clean(JSON.stringify(s.last()), s.root);
|
||||
});
|
||||
|
||||
// #1873 re-check 8 P3-1: a preflight promise that rejects is refused as a throw is, by the call and
|
||||
// the system code, never the raw error or its path.
|
||||
test('a harness whose async preflight rejects with a system error refuses harness-failed naming the call and code, never the path', async t => {
|
||||
const s = await routed(t, 'fsrejects');
|
||||
assert.deepEqual(await s.launch(), { ok: false, error: 'harness-failed' });
|
||||
assert.equal(s.last().why, 'harness fsrejects preflight: cannot open a host file (ENOENT)');
|
||||
clean(JSON.stringify(s.last()), s.root);
|
||||
});
|
||||
|
||||
test('a harness the loader refuses names its code only, never the loader message or a path', async t => {
|
||||
const s = await routed(t, 'absent');
|
||||
assert.deepEqual(await s.launch(), { ok: false, error: 'harness-refused' });
|
||||
|
||||
@@ -34,10 +34,11 @@ function privateArtifacts(f, session, keys) {
|
||||
f.valueFree();
|
||||
}
|
||||
|
||||
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so pi joins the z.ai and
|
||||
// codex routes on a non-Claude model, and a Claude route on pi refuses below.
|
||||
const ROUTE_MODEL = 'fixture-route-model';
|
||||
for (const [provider, route, generated, api] of [
|
||||
['zai', null, 'mosaic-proxy-glm', 'openai-completions'],
|
||||
['anthropic', null, 'anthropic', 'anthropic-messages'],
|
||||
['proxy', 'anthropic', 'anthropic', 'anthropic-messages'],
|
||||
['proxy', 'glm', 'mosaic-proxy-glm', 'openai-completions'],
|
||||
['proxy', 'codex', 'mosaic-proxy-codex', 'openai-responses'],
|
||||
]) {
|
||||
@@ -45,8 +46,7 @@ for (const [provider, route, generated, api] of [
|
||||
const f = await managedLaunchFixture(t);
|
||||
assert.deepEqual(f.upstreamCredentialNames, [], 'managed proxy fixture has no inherited fake upstream credential');
|
||||
editBusiness(f, doc => {
|
||||
doc.launch.models['claude-opus-5-5'].provider = provider;
|
||||
if (route) doc.launch.models['claude-opus-5-5'].route = route;
|
||||
doc.launch.models['claude-opus-5-5'] = { provider, model: ROUTE_MODEL, ...(route ? { route } : {}) };
|
||||
});
|
||||
const answer = await f.launcher.launchPm();
|
||||
const session = f.sessions().find(value => value.run === answer.run);
|
||||
@@ -69,7 +69,7 @@ for (const [provider, route, generated, api] of [
|
||||
assert.equal(models.providers[generated].api, api);
|
||||
assert.equal(models.providers[generated].baseUrl,
|
||||
other.baseUrl + (api === 'anthropic-messages' ? '' : '/v1'));
|
||||
assert.equal(models.providers[generated].models.some(model => model.id === 'claude-opus-5-5'), true);
|
||||
assert.equal(models.providers[generated].models.some(model => model.id === ROUTE_MODEL), true);
|
||||
for (const value of Object.values(models.providers)) assert.equal(value.apiKey, '$ANTHROPIC_API_KEY');
|
||||
for (const key of [own.key, other.key]) assert.equal(text.includes(key), false, 'models contain no key value');
|
||||
assert.equal(fs.statSync(path).mode & 0o777, 0o600);
|
||||
@@ -79,6 +79,26 @@ for (const [provider, route, generated, api] of [
|
||||
});
|
||||
}
|
||||
|
||||
// A legacy entry with no provider plugin gets no catalogue check, so a Claude-named model on a z.ai
|
||||
// or codex route is treated as OAuth too (review P1-1).
|
||||
for (const [provider, route, name] of [['anthropic', null], ['proxy', 'anthropic'], ['zai', null, 'claude-opus-5-5'], ['proxy', 'glm', 'claude-opus-5-5'], ['proxy', 'codex', 'claude-sonnet-5-5']]) {
|
||||
test(`#1873 a stored Claude route ${provider}${route ? ':' + route : ''}${name ? ' ' + name : ''} on pi refuses model-harness-incompatible with no key acquisition or session`, { skip, timeout: 30000 }, async t => {
|
||||
const f = await managedLaunchFixture(t);
|
||||
editBusiness(f, doc => {
|
||||
doc.launch.models['claude-opus-5-5'].provider = provider;
|
||||
if (route) doc.launch.models['claude-opus-5-5'].route = route;
|
||||
if (name) doc.launch.models['claude-opus-5-5'].model = name;
|
||||
});
|
||||
await assert.rejects(f.launcher.launchPm(), error => error.code === 'model-harness-incompatible');
|
||||
assert.equal(f.trace.preflightAttempts, 0, 'refused before P2 issues a key');
|
||||
assert.equal(f.trace.bindings.length, 0);
|
||||
assert.equal(f.sessions().length, 0);
|
||||
assert.equal(f.runDirectories().length, 0);
|
||||
assert.equal(f.launchLog().some(e => e.event === 'refused' && e.code === 'model-harness-incompatible'), true);
|
||||
f.valueFree();
|
||||
});
|
||||
}
|
||||
|
||||
test('P3 joined Claude harness receives the admitted P2 key only through transient auth env', { skip, timeout: 30000 }, async t => {
|
||||
const f = await managedLaunchFixture(t, { harness: 'claude-code' });
|
||||
assert.deepEqual(f.upstreamCredentialNames, [], 'Claude proxy fixture holds no upstream credential');
|
||||
@@ -117,7 +137,7 @@ test('P3 joined unsupported provider refuses with no key acquisition, fallback,
|
||||
test('row 332 R2 joined pi launch goes live when launch.models also holds an unroutable entry, which models.json leaves out', { skip, timeout: 30000 }, async t => {
|
||||
const f = await managedLaunchFixture(t);
|
||||
editBusiness(f, doc => {
|
||||
doc.launch.models['claude-opus-5-5'].provider = 'anthropic';
|
||||
doc.launch.models['claude-opus-5-5'] = { provider: 'zai', model: ROUTE_MODEL };
|
||||
doc.launch.models.router = { provider: 'openrouter', model: 'x' };
|
||||
});
|
||||
const answer = await f.launcher.launchPm();
|
||||
@@ -126,7 +146,7 @@ test('row 332 R2 joined pi launch goes live when launch.models also holds an unr
|
||||
assert.equal(f.trace.successfulPreflights, 1);
|
||||
assert.equal(f.runDirectories().length, 1, 'one run directory, the live one');
|
||||
const { providers } = JSON.parse(fs.readFileSync(join(session.runDir, 'home', '.pi', 'agent', 'models.json'), 'utf8'));
|
||||
assert.equal(providers.anthropic.models.some(model => model.id === 'claude-opus-5-5'), true);
|
||||
assert.equal(providers['mosaic-proxy-glm'].models.some(model => model.id === ROUTE_MODEL), true);
|
||||
assert.equal(Object.values(providers).some(value => value.models.some(model => model.id === 'x')), false, 'no openrouter entry');
|
||||
privateArtifacts(f, session, [f.bus.credentials.modelRecord('acme/chief').key]);
|
||||
});
|
||||
@@ -95,6 +95,7 @@ function requestHost(x) {
|
||||
landHeld: m => x.bus.landHeld(m.record), landHolders: m => x.bus.landHolders(m.business),
|
||||
sessionClears: m => x.bus.sessionClears(m.business),
|
||||
threadsState: m => x.bus.threadsState(m.business), lifecycleRequests: m => x.bus.lifecycleRequests(m.business),
|
||||
failureNotice: m => x.bus.failureNotice(m.record),
|
||||
'request.admission': m => x.bus.admission(m), 'request.launches': m => x.bus.requestLaunches(m.business),
|
||||
'request.launchResult': m => x.bus.requestLaunchResult(m.record), 'request.manifest': m => x.bus.requestManifest(m.record),
|
||||
'request.release': m => x.bus.requestRelease(m.cap, m.record), 'request.chief': m => x.bus.requestChief(m.business),
|
||||
|
||||
@@ -96,6 +96,7 @@ async function start(t, { f, adapter, access }, threadsState) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => threadsState(runtime, m),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -92,6 +92,7 @@ async function start(t, { f, adapter }, { tickMs = 100, stopTimeoutMs } = {}) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -112,6 +112,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -93,6 +93,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
@@ -496,6 +497,78 @@ test("REQ-LIMIT-3 REQ-LIMIT-4 a thread start whose instance is at its token limi
|
||||
assert.equal(launchLog(f).filter((e) => e.event === "refused" && e.thread === A).length, 1);
|
||||
});
|
||||
|
||||
// #1873 chat-fail F2: a refused start leaves one plain line in the chat for each message it left
|
||||
// unanswered, with the cause and next step, never one per retry and never the refusal's reason.
|
||||
const LIMIT_LINE = "The turn failed: the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.\nDetails: start refused: limit-reached";
|
||||
test("#1873 F2 a refused thread start puts one plain line per unanswered message in the chat, not one per retry", { skip, timeout: 60000 }, async (t) => {
|
||||
const prepared = prepare(t, { edit: atLimit });
|
||||
const { f } = prepared;
|
||||
const host = await start(t, prepared);
|
||||
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
|
||||
const A = host.call("thread.create", { project, name: "alpha" }).id;
|
||||
const first = host.call("thread.send", { thread: A, body: "for A" });
|
||||
const lines = (sent) => host.call("thread.messages", { thread: A }).filter((m) => m.in_reply_to === sent.id);
|
||||
const [line] = await until(() => lines(first).length && lines(first));
|
||||
assert.equal(line.body, LIMIT_LINE);
|
||||
assert.deepEqual([line.from_role, line.from_run], ["assistant", "bus"]);
|
||||
assert.equal(line.to_role, "human");
|
||||
assert.equal(line.class, "RESULT");
|
||||
assert.doesNotMatch(line.body, /token-limit|tokens\.instances|"limit"/, "the refusal's reason stays out of the chat");
|
||||
for (let i = 0; i < 3; i++) await host.launcher.tick();
|
||||
assert.equal(lines(first).length, 1, "a retry adds no line");
|
||||
// A second message gets its own line; the first keeps its one.
|
||||
const second = host.call("thread.send", { thread: A, body: "again" });
|
||||
await until(() => lines(second).length);
|
||||
for (let i = 0; i < 3; i++) await host.launcher.tick();
|
||||
assert.deepEqual(lines(second).map((m) => m.body), [LIMIT_LINE]);
|
||||
assert.equal(lines(first).length, 1);
|
||||
assert.deepEqual(threadRuns(f, A), []);
|
||||
// The messages stay pending: the start is retried and answers them once the limit allows.
|
||||
assert.equal(launchLog(f).filter((e) => e.event === "refused" && e.thread === A).length, 1);
|
||||
});
|
||||
|
||||
// #1873 review round 1 (P2-2): launch-failed can be a lost race that the next try wins, so one
|
||||
// such refusal posts nothing and the answer arrives alone; the same refusal twice posts one line.
|
||||
const failedLines = (host, thread) => host.call("thread.messages", { thread }).filter((m) => m.body.startsWith("The turn failed"));
|
||||
test("#1873 F2 one launch-failed refusal that the next start clears leaves no failure line", { skip, timeout: 60000 }, async (t) => {
|
||||
const prepared = prepare(t);
|
||||
let throws = 1;
|
||||
const host = await start(t, prepared, { ops: (runtime) => ({ landHeld: (m) => { if (throws-- > 0) throw new Error("fixture: lost race"); return runtime.landHeld(m.record); } }) });
|
||||
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
|
||||
const A = host.call("thread.create", { project, name: "alpha" }).id;
|
||||
const sent = host.call("thread.send", { thread: A, body: "for A" });
|
||||
const reply = await until(() => host.call("thread.messages", { thread: A }).find((m) => m.in_reply_to === sent.id && m.class === "RESULT"));
|
||||
assert.match(reply.body, /THREAD \{/, "the first reply is the answer");
|
||||
assert.equal(throws, -1, "the first start was refused");
|
||||
assert.deepEqual(failedLines(host, A), []);
|
||||
});
|
||||
test("#1873 F2 the same launch-failed refusal twice for one message posts one line", { skip, timeout: 60000 }, async (t) => {
|
||||
const prepared = prepare(t);
|
||||
const host = await start(t, prepared, { ops: () => ({ landHeld: () => { throw new Error("fixture: always refused"); } }) });
|
||||
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
|
||||
const A = host.call("thread.create", { project, name: "alpha" }).id;
|
||||
host.call("thread.send", { thread: A, body: "for A" });
|
||||
const [line] = await until(() => failedLines(host, A).length && failedLines(host, A));
|
||||
assert.match(line.body, /\nDetails: start refused: launch-failed$/);
|
||||
for (let i = 0; i < 3; i++) await host.launcher.tick();
|
||||
assert.equal(failedLines(host, A).length, 1);
|
||||
});
|
||||
// #1873 review round 1 (P3-3): a line whose post fails is posted on a later tick, once.
|
||||
test("#1873 F2 a failure line whose post is refused once arrives on a later tick, exactly once", { skip, timeout: 60000 }, async (t) => {
|
||||
const prepared = prepare(t, { edit: atLimit });
|
||||
let throws = 1;
|
||||
const host = await start(t, prepared, { ops: (runtime) => ({ failureNotice: (m) => { if (throws-- > 0) throw new Error("fixture: bus busy"); return runtime.failureNotice(m.record); } }) });
|
||||
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
|
||||
const A = host.call("thread.create", { project, name: "alpha" }).id;
|
||||
host.call("thread.send", { thread: A, body: "for A" });
|
||||
const [line] = await until(() => failedLines(host, A).length && failedLines(host, A));
|
||||
assert.equal(line.body, LIMIT_LINE);
|
||||
assert.equal(throws, -1, "the first post was refused");
|
||||
for (let i = 0; i < 3; i++) await host.launcher.tick();
|
||||
assert.equal(failedLines(host, A).length, 1);
|
||||
assert.equal(host.logs.filter((l) => /failure line refused/.test(l)).length, 1);
|
||||
});
|
||||
|
||||
test("REQ-LIMIT-4 a thread run at its token limit stops at the end of its turn: the reply lands, and the end record names the limit", { skip, timeout: 60000 }, async (t) => {
|
||||
const prepared = prepare(t, { edit: atLimit });
|
||||
const { f } = prepared;
|
||||
|
||||
@@ -97,6 +97,7 @@ async function start(t, { f, adapter, access }) {
|
||||
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
|
||||
threadsState: (m) => runtime.threadsState(m.business),
|
||||
threadIdle: (m) => runtime.threadIdle(m.record),
|
||||
failureNotice: (m) => runtime.failureNotice(m.record),
|
||||
mayLaunch: (m) => runtime.mayLaunch(m),
|
||||
landHeld: (m) => runtime.landHeld(m.record),
|
||||
landHolders: (m) => runtime.landHolders(m.business),
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
// #1873 triage-key: `mosaic triage key issue|rotate|retire|status`, Triage's own model proxy key.
|
||||
// A stand-in management server on loopback and a temporary config directory only; nothing here
|
||||
// reads a real config, proxy or secret. Every stdout, stderr, receipt and file the verbs leave is
|
||||
// scanned for every key the stand-in ever saw, at the end of each test and once more at the end.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { run } from "../src/cli.mjs";
|
||||
import { AGENT_MARKERS } from "../src/transport.mjs";
|
||||
import { DEFAULT_ROTATE_GRACE_MINUTES, keyPaths, retireAtFor, rotateByFor } from "../../bus/src/triage-key.mjs";
|
||||
import { ModelKeys } from "../../bus/src/model-keys.mjs";
|
||||
import { ManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
import { startBroker } from "../../bus/src/runtime.mjs";
|
||||
import { busOrganization } from "../../bus/src/organization-context.mjs";
|
||||
import { Registry } from "../../seat/src/session.mjs";
|
||||
import { loadBusiness } from "../../organization/src/organization-config.mjs";
|
||||
import { resolveInstance } from "../../organization/src/resolve.mjs";
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from "../../organization/tests/helpers.mjs";
|
||||
import { humanEnv, io } from "./helpers.mjs";
|
||||
|
||||
const REPO = new URL("../../../", import.meta.url).pathname;
|
||||
const NOW = Date.parse("2026-11-18T12:00:00.000Z");
|
||||
const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
|
||||
const MANAGE = "fx1873-manage";
|
||||
const KEY_PATH = "/v8/management/config/access/api-keys";
|
||||
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
||||
const tag = (dir) => sha(dir).slice(0, 12);
|
||||
const id = (key) => sha(key).slice(0, 12);
|
||||
const b64 = () => randomBytes(32).toString("base64url");
|
||||
const iso = (ms) => new Date(ms).toISOString();
|
||||
|
||||
// Every output any verb produced in this file, and every Triage key the stand-in ever held.
|
||||
const OUTPUTS = [];
|
||||
const SEEN = new Set();
|
||||
const VERBS = ["issue", "rotate", "retire", "status"];
|
||||
|
||||
function leaks(text, keys = SEEN) {
|
||||
for (const key of keys) {
|
||||
const secret = key.slice(-43);
|
||||
if (text.includes(key) || text.includes(secret)) return true;
|
||||
for (let i = 0; i + 8 <= secret.length; i++) if (text.includes(secret.slice(i, i + 8))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function walk(dir, skip, out = []) {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const p = join(dir, name), st = fs.lstatSync(p);
|
||||
if (st.isDirectory()) walk(p, skip, out);
|
||||
else if (st.isFile() && !skip.includes(p)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function fixture(t, { sentinel = true } = {}) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "tk-")));
|
||||
const configDir = join(root, "config");
|
||||
fs.mkdirSync(join(configDir, "secrets"), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(configDir, 0o700); fs.chmodSync(join(configDir, "secrets"), 0o700);
|
||||
fs.writeFileSync(join(configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
fs.mkdirSync(join(root, "proxy"), { mode: 0o700 });
|
||||
const prefix = `mst-${tag(configDir)}-triage-`;
|
||||
const state = {
|
||||
keys: [...(sentinel ? [`msk-${tag(configDir)}-sentinel-${b64()}`] : []), "foreign-client-key", `mso-${tag(configDir)}-demo-key-${b64()}`],
|
||||
gets: 0, puts: [], ignorePut: false, dropSentinelOnPut: false, onGet: null,
|
||||
};
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.url !== KEY_PATH) {
|
||||
const key = req.headers.authorization?.slice(7);
|
||||
res.writeHead(state.keys.includes(key) ? 200 : 401); res.end("{}"); return;
|
||||
}
|
||||
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end("{}"); return; }
|
||||
if (req.method === "GET") { state.gets++; const body = JSON.stringify(state.keys); state.onGet?.(state.gets); res.end(body); return; }
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const next = JSON.parse(Buffer.concat(chunks));
|
||||
for (const k of next) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
state.puts.push(next);
|
||||
if (state.dropSentinelOnPut) state.keys = next.filter((k) => !k.startsWith("msk-") || !k.includes("-sentinel-"));
|
||||
else if (!state.ignorePut) state.keys = next;
|
||||
res.end('{"status":"ok"}');
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = server.address().port;
|
||||
const closers = [];
|
||||
t.after(async () => {
|
||||
for (const close of closers) await close();
|
||||
server.closeAllConnections(); await new Promise((resolve) => server.close(resolve));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const f = {
|
||||
root, configDir, prefix, state, server, port, closers, now: NOW,
|
||||
system: { dataRoot: root, proxy: { port, binary: "/fixture-unused" } },
|
||||
file: keyPaths(configDir).file, dir: keyPaths(configDir).dir,
|
||||
env: (extra = {}) => humanEnv({ MOSAIC_CONFIG: join(configDir, "config.json"), ...extra }),
|
||||
async cli(argv, { env, deps = {}, system = f.system } = {}) {
|
||||
const s = io(env ?? f.env());
|
||||
const code = await run(argv, s, { system, now: () => new Date(f.now), ...deps });
|
||||
const out = { code, stdout: s.out.text, stderr: s.err.text };
|
||||
OUTPUTS.push(out.stdout, out.stderr);
|
||||
return out;
|
||||
},
|
||||
// The same verb in a child process that SIGKILLs itself at `stage`.
|
||||
crash(argv, stage) {
|
||||
const script = `
|
||||
import { run } from ${JSON.stringify(new URL("../src/cli.mjs", import.meta.url).href)};
|
||||
import { io } from ${JSON.stringify(new URL("./helpers.mjs", import.meta.url).href)};
|
||||
const p = JSON.parse(process.env.TK_CRASH);
|
||||
const s = io(process.env);
|
||||
const code = await run(p.argv, s, { system: p.system, now: () => new Date(p.now),
|
||||
triageKeyHook: (stage) => { if (stage === p.stage) process.kill(process.pid, "SIGKILL"); } });
|
||||
process.stdout.write(s.out.text); process.stderr.write(s.err.text); process.exitCode = code;`;
|
||||
const env = f.env({ TK_CRASH: JSON.stringify({ argv, stage, system: f.system, now: f.now }) });
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, ["--input-type=module", "-e", script], { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "", stderr = "";
|
||||
child.stdout.on("data", (d) => { stdout += d; });
|
||||
child.stderr.on("data", (d) => { stderr += d; });
|
||||
child.on("exit", (code, signal) => { OUTPUTS.push(stdout, stderr); resolve({ code, signal, stdout, stderr }); });
|
||||
});
|
||||
},
|
||||
record: () => JSON.parse(fs.readFileSync(f.file, "utf8")),
|
||||
triageKeys: () => state.keys.filter((k) => k.startsWith(prefix)),
|
||||
receipts: () => {
|
||||
const file = join(root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
return fs.existsSync(file) ? fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
|
||||
},
|
||||
fenced: () => fs.existsSync(join(root, "proxy", "mosaic-keys.uncertain")),
|
||||
// No file under the fixture but the key file itself holds a key; neither does any output.
|
||||
scan(alsoKeyFiles = []) {
|
||||
for (const k of state.keys) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
for (const p of walk(root, [f.file, join(configDir, "secrets", "proxy-management.key"), ...alsoKeyFiles])) {
|
||||
assert.equal(leaks(fs.readFileSync(p, "latin1")), false, `a key is in ${p}`);
|
||||
}
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false, "a key is in an output");
|
||||
},
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
const ok = (r) => assert.equal(r.code, 0, r.stderr);
|
||||
const refusal = (r, code, words) => {
|
||||
assert.equal(r.code, 3, r.stderr);
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, new RegExp(`^mosaic: ${code}: ${words ?? ""}`));
|
||||
};
|
||||
|
||||
test("issue adds one key under the lock, writes the 0600 file, and records ids only", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const before = [...f.state.keys];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(Object.keys(rec), ["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
assert.match(rec.key, new RegExp(`^${f.prefix}[A-Za-z0-9_-]{43}$`));
|
||||
assert.equal(rec.keyId, id(rec.key));
|
||||
assert.equal(rec.issuedAt, iso(NOW));
|
||||
assert.equal(rec.rotateBy, "2026-12-18");
|
||||
assert.deepEqual(rec.retiring, []);
|
||||
assert.equal(r.stdout, `triage key issued: ${rec.keyId}, rotate by 2026-12-18\nfile: ${f.file}\n`);
|
||||
assert.deepEqual(f.state.keys, [...before, rec.key]);
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
const file = fs.lstatSync(f.file), dir = fs.lstatSync(f.dir);
|
||||
assert.equal(file.mode & 0o777, 0o600); assert.equal(dir.mode & 0o777, 0o700);
|
||||
assert.equal(file.uid, process.getuid()); assert.equal(dir.uid, process.getuid());
|
||||
assert.deepEqual(f.receipts(), [{ op: "triage.key.issue", time: iso(NOW), addedKeyIds: [rec.keyId], removedKeyIds: [] }]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(join(f.root, "proxy", "keys.generation"), "utf8"), "1\n");
|
||||
// A second issue refuses and changes nothing; rotate is the verb for that.
|
||||
const again = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(again, "triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate\n$");
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
assert.deepEqual(f.record(), rec);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("status reads the file and the list and writes nothing", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const none = await f.cli(["triage", "key", "status"]);
|
||||
ok(none);
|
||||
assert.equal(none.stdout, `triage key: not issued\nfile: ${f.file}\nproxy: read\nnext: mosaic triage key issue\n`);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const rec = f.record(), puts = f.state.puts.length, receipts = f.receipts().length;
|
||||
f.now = NOW + 3 * DAY + 4 * HOUR + 5 * MIN;
|
||||
const shown = await f.cli(["triage", "key", "status"]);
|
||||
ok(shown);
|
||||
assert.equal(shown.stdout, [
|
||||
"triage key: issued", `file: ${f.file}`, `key id: ${rec.keyId}`, `issued: ${iso(NOW)} (age 3d 4h 5m)`,
|
||||
"rotate by: 2026-12-18", "proxy: holds the key", "next: nothing", "",
|
||||
].join("\n"));
|
||||
f.now = Date.parse("2026-12-18T00:00:00.000Z");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /rotate by: 2026-12-18 \(due\)\n[^]*next: mosaic triage key rotate\n$/);
|
||||
f.now = NOW + HOUR;
|
||||
f.state.keys = f.state.keys.filter((k) => k !== rec.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: does not hold the key\nnext: mosaic triage key rotate\n$/);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.equal(f.receipts().length, receipts);
|
||||
assert.equal(fs.readdirSync(join(f.root, "proxy")).includes("mosaic-keys.lock"), false);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate adds a new key and keeps the old one for the bus grace; retire removes it once due", async (t) => {
|
||||
const f = await fixture(t);
|
||||
refusal(await f.cli(["triage", "key", "rotate"]), "triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
f.now = NOW + HOUR;
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
const second = f.record();
|
||||
const retireAt = iso(NOW + HOUR + 120 * MIN);
|
||||
assert.notEqual(second.key, first.key);
|
||||
assert.equal(second.issuedAt, iso(NOW + HOUR));
|
||||
assert.deepEqual(second.retiring, [{ key: first.key, keyId: first.keyId, issuedAt: first.issuedAt, retireAt }]);
|
||||
assert.equal(r.stdout, `triage key rotated: ${second.keyId}, rotate by 2026-12-18\nold key ${first.keyId} stays live until mosaic triage key retire runs at or after ${retireAt}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [first.key, second.key]);
|
||||
f.now = NOW + HOUR + 119 * MIN;
|
||||
const early = await f.cli(["triage", "key", "retire"]);
|
||||
ok(early);
|
||||
assert.equal(early.stdout, "triage key retire: nothing to remove\n");
|
||||
assert.equal(f.state.puts.length, 2);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt}\\n[^]*next: nothing\\n$`));
|
||||
f.now = NOW + HOUR + 120 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt} \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
const done = await f.cli(["triage", "key", "retire"]);
|
||||
ok(done);
|
||||
assert.equal(done.stdout, `triage key retire: removed ${first.keyId}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [second.key]);
|
||||
assert.deepEqual(f.record(), { ...second, retiring: [] });
|
||||
assert.deepEqual(f.receipts().map((e) => e.op), ["triage.key.issue", "triage.key.rotate", "triage.key.retire"]);
|
||||
assert.deepEqual(f.receipts()[2].removedKeyIds, [first.keyId]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate takes the grace from proxy.json, where the bus reads it, and drops an old key the proxy lost", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: 30 } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const second = f.record();
|
||||
assert.equal(second.retiring[0].retireAt, iso(NOW + 30 * MIN));
|
||||
// The proxy lost the current key: rotate drops it at once, as the bus does for an agent key.
|
||||
f.state.keys = f.state.keys.filter((k) => k !== second.key);
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`old key ${second.keyId} was not in the proxy list; nothing to retire\\n$`));
|
||||
assert.deepEqual(f.record().retiring.map((e) => e.keyId), [first.keyId]);
|
||||
// A retiring key past its time, or no longer in the list, leaves on the next rotate.
|
||||
f.now = NOW + 31 * MIN;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const last = f.record();
|
||||
assert.deepEqual(last.retiring.map((e) => e.keyId), [id(f.triageKeys()[0])]);
|
||||
assert.equal(f.triageKeys().includes(first.key), false);
|
||||
assert.equal(f.triageKeys().length, 2);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("lifetime and grace match the bus's own ModelKeys for the same clock and proxy settings", async (t) => {
|
||||
const runtime = fs.readFileSync(join(REPO, "packages/bus/src/runtime.mjs"), "utf8");
|
||||
const literal = runtime.match(/rotateGraceMinutes: proxy\.rotateGraceMinutes \?\? (\d+)/);
|
||||
assert.ok(literal, "the bus no longer reads rotateGraceMinutes as this test expects");
|
||||
assert.equal(Number(literal[1]), DEFAULT_ROTATE_GRACE_MINUTES);
|
||||
for (const grace of [undefined, 45]) {
|
||||
const f = await fixture(t);
|
||||
if (grace !== undefined) f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: grace } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
f.now = NOW + 3 * HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const ours = f.record();
|
||||
// The bus, driven the way runtime.mjs drives it, on its own in-memory list.
|
||||
let keys = [`msk-${tag(f.configDir)}-sentinel-${b64()}`], record = null, now = NOW;
|
||||
const credentials = { registerModel() {}, modelRecord: () => record, writeModel: (_, r) => { record = r; }, status: () => [] };
|
||||
const client = { getKeys: async () => [...keys], putKeys: async (k) => { keys = [...k]; return { ok: true }; } };
|
||||
const bus = new ModelKeys({ credentials, client, configDir: f.configDir, baseUrl: "http://127.0.0.1:1", now: () => now,
|
||||
...(grace === undefined ? {} : { rotateGraceMinutes: f.system.proxy.rotateGraceMinutes ?? Number(literal[1]) }) });
|
||||
await bus.reconcile();
|
||||
await bus.ensure("demo/x");
|
||||
assert.equal(record.rotateBy, rotateByFor(NOW));
|
||||
now = NOW + 3 * HOUR;
|
||||
await bus.rotate("demo/x");
|
||||
assert.equal(ours.rotateBy, record.rotateBy);
|
||||
assert.equal(ours.retiring[0].retireAt, record.retiring[0].retireAt);
|
||||
assert.equal(ours.retiring[0].retireAt, retireAtFor(now, f.system.proxy));
|
||||
f.scan();
|
||||
}
|
||||
});
|
||||
|
||||
test("an agent caller is refused before anything is read, for every key verb", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { env: { ...f.env(), [marker]: "1" } });
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`);
|
||||
}
|
||||
const saved = process.env[marker];
|
||||
process.env[marker] = "1";
|
||||
try {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb]);
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.match(r.stderr, new RegExp(`found ${marker} in the environment`));
|
||||
}
|
||||
} finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; }
|
||||
}
|
||||
assert.equal(f.state.gets, 0);
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
assert.equal(fs.existsSync(f.dir), false);
|
||||
assert.deepEqual(fs.readdirSync(join(f.root, "proxy")), []);
|
||||
});
|
||||
|
||||
test("usage: unknown key verbs, options and arguments exit 4 and echo no value", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const argv of [["triage", "key"], ["triage", "key", "nope"], ["triage", "key", "issue", "extra"], ["triage", "key", "status", "--json"]]) {
|
||||
const r = await f.cli(argv);
|
||||
assert.equal(r.code, 4, argv.join(" "));
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, /\nusage: mosaic triage route show [^\n]*\| key issue \| rotate \| retire \| status\n$/);
|
||||
}
|
||||
const r = await f.cli(["triage", "key", "rotate", "--key", "secret-value"]);
|
||||
assert.equal(r.code, 4);
|
||||
assert.match(r.stderr, /^mosaic: unknown option\n/);
|
||||
assert.doesNotMatch(r.stderr, /secret-value/);
|
||||
assert.equal(f.state.gets, 0);
|
||||
});
|
||||
|
||||
test("an unsafe key store refuses every verb before any proxy write", async (t) => {
|
||||
const uid = process.getuid();
|
||||
const cases = [
|
||||
["file mode", (f) => fs.chmodSync(f.file, 0o644), {}, "the key file mode is not 0600"],
|
||||
["file owner", () => {}, { triageKeyFileUid: uid + 1 }, "the key file is not owned by this user"],
|
||||
["file link", (f) => { fs.renameSync(f.file, join(f.dir, "real")); fs.symlinkSync(join(f.dir, "real"), f.file); }, {}, "the key file is a link"],
|
||||
["file is a directory", (f) => { fs.rmSync(f.file); fs.mkdirSync(f.file, { mode: 0o700 }); }, {}, "the key file is not a regular file"],
|
||||
["file is a FIFO", (f) => { fs.rmSync(f.file); assert.equal(spawnSync("mkfifo", ["-m", "600", f.file]).status, 0); }, {}, "the key file is not a regular file"],
|
||||
["hard link", (f) => fs.linkSync(f.file, join(f.dir, "second")), {}, "the key file has more than one link"],
|
||||
["not JSON", (f) => fs.writeFileSync(f.file, "{"), {}, "the key file is not JSON"],
|
||||
["extra field", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), extra: 1 })), {}, "the key file does not match the key shape"],
|
||||
["another instance's key", (f) => { const r = f.record(); const key = `mst-${tag("/elsewhere")}-triage-${b64()}`; fs.writeFileSync(f.file, JSON.stringify({ ...r, key, keyId: id(key) })); }, {}, "the key file does not match the key shape"],
|
||||
["wrong key id", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), keyId: "000000000000" })), {}, "the key file does not match the key shape"],
|
||||
["too large", (f) => fs.writeFileSync(f.file, " ".repeat(64 * 1024 + 1)), {}, "the key file is too large"],
|
||||
["triage directory mode", (f) => fs.chmodSync(f.dir, 0o755), {}, "the triage secrets directory mode is not 0700"],
|
||||
["triage directory link", (f) => { fs.renameSync(f.dir, join(f.configDir, "secrets", "moved")); fs.symlinkSync(join(f.configDir, "secrets", "moved"), f.dir); }, {}, "the triage secrets directory is a link"],
|
||||
["triage directory is a file", (f) => { fs.rmSync(f.dir, { recursive: true }); fs.writeFileSync(f.dir, "", { mode: 0o600 }); }, {}, "the triage secrets directory is not a directory"],
|
||||
["secrets mode", (f) => fs.chmodSync(join(f.configDir, "secrets"), 0o750), {}, "the secrets directory mode is not 0700"],
|
||||
["owner", () => {}, { triageKeyUid: uid + 1 }, "the secrets directory is not owned by this user"],
|
||||
];
|
||||
for (const [name, spoil, deps, words] of cases) {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
spoil(f);
|
||||
const keys = [...f.state.keys], puts = f.state.puts.length;
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { deps });
|
||||
refusal(r, "triage-key-unreadable", `the Triage key store is unreadable: ${words.replace(/[.()]/g, "\\$&")}\n$`);
|
||||
assert.equal(f.state.puts.length, puts, `${name}: ${verb}`);
|
||||
}
|
||||
assert.deepEqual(f.state.keys, keys);
|
||||
// The spoils above move or link the key file itself; those copies are the key file.
|
||||
f.scan([join(f.dir, "real"), join(f.dir, "second"), join(f.configDir, "secrets", "moved", "model")]);
|
||||
}
|
||||
// No secrets directory at all: status says not issued; issue refuses before the proxy changes.
|
||||
const f = await fixture(t);
|
||||
fs.rmSync(join(f.configDir, "secrets"), { recursive: true });
|
||||
fs.mkdirSync(join(f.configDir, "secrets"), { mode: 0o700 });
|
||||
fs.writeFileSync(join(f.configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
fs.chmodSync(join(f.configDir, "secrets"), 0o755);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unreadable", "the Triage key store is unreadable: the secrets directory mode is not 0700\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
});
|
||||
|
||||
test("the instance proxy lock, the fence, the sentinel and the proxy itself each refuse plainly", async (t) => {
|
||||
// Lock held by a live process: busy after the lock's wait, and nothing changes.
|
||||
const f = await fixture(t);
|
||||
const lockFile = join(f.root, "proxy", "mosaic-keys.lock");
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: process.pid, token: "a".repeat(32) })}\n`, { mode: 0o600 });
|
||||
const busy = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(busy, "proxy-lock-busy", "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status\n$");
|
||||
assert.equal(f.state.gets, 1);
|
||||
// A lock left by a process that is gone is reaped, and the verb goes ahead.
|
||||
const dead = spawnSync(process.execPath, ["-e", ""]).pid;
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: dead, token: "b".repeat(32) })}\n`, { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.equal(fs.existsSync(lockFile), false);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.rmSync(f.file);
|
||||
f.state.keys = f.state.keys.filter((k) => !k.startsWith(f.prefix));
|
||||
// A set fence: every write refuses, status names it and the way out.
|
||||
const putsBefore = f.state.puts.length;
|
||||
fs.writeFileSync(join(f.root, "proxy", "mosaic-keys.uncertain"), "{}\n", { mode: 0o600 });
|
||||
for (const verb of ["issue", "rotate", "retire"]) refusal(await f.cli(["triage", "key", verb]), "proxy-uncertain");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy fence: set, an earlier proxy write has an uncertain outcome\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\n$/);
|
||||
assert.equal(f.state.puts.length, putsBefore);
|
||||
// No sentinel for this instance (another instance's does not count).
|
||||
const g = await fixture(t, { sentinel: false });
|
||||
g.state.keys.push(`msk-${tag("/elsewhere")}-sentinel-${b64()}`);
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-proxy-open");
|
||||
assert.match((await g.cli(["triage", "key", "status"])).stdout, /proxy: its key list has no sentinel for this instance\nnext: check the proxy with mosaic proxy status\n$/);
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
// No proxy set up, no management key, proxy down.
|
||||
const h = await fixture(t);
|
||||
const bare = { dataRoot: h.root };
|
||||
refusal(await h.cli(["triage", "key", "issue"], { system: bare }), "triage-key-no-proxy");
|
||||
assert.equal((await h.cli(["triage", "key", "status"], { system: bare })).stdout,
|
||||
`triage key: not issued\nfile: ${h.file}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o644);
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-management-key-invalid");
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o600);
|
||||
h.server.closeAllConnections(); await new Promise((resolve) => h.server.close(resolve));
|
||||
h.server.close = (cb) => cb();
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-client-down");
|
||||
assert.match((await h.cli(["triage", "key", "status"])).stdout, /proxy: not read \(proxy-client-down\)\n/);
|
||||
assert.equal(fs.existsSync(h.file), false);
|
||||
f.scan(); g.scan(); h.scan();
|
||||
});
|
||||
|
||||
test("a write the proxy does not confirm keeps the fence; a list that moves mid-verb is not overwritten", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.state.ignorePut = true;
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
// The store's directory was made and checked before the proxy changed, not after.
|
||||
assert.equal(fs.lstatSync(f.dir).mode & 0o777, 0o700);
|
||||
assert.deepEqual(f.receipts(), []);
|
||||
// A PUT the proxy takes but whose read-back has lost this instance's sentinel is not confirmed.
|
||||
const s = await fixture(t);
|
||||
s.state.dropSentinelOnPut = true;
|
||||
refusal(await s.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(s.fenced(), true);
|
||||
assert.equal(fs.existsSync(s.file), false);
|
||||
s.scan();
|
||||
const g = await fixture(t);
|
||||
g.state.onGet = (n) => { if (n === 1) g.state.keys = [...g.state.keys, "late-foreign-key"]; };
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-raced");
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
assert.equal(g.fenced(), false);
|
||||
f.scan(); g.scan();
|
||||
});
|
||||
|
||||
test("keys outside the Triage namespace are never touched; Triage keys the file does not hold are removed", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const agent = `msk-${tag(f.configDir)}-${b64()}`, other = `mst-${tag("/elsewhere")}-triage-${b64()}`;
|
||||
const orphan = `${f.prefix}${b64()}`, odd = `${f.prefix}short`;
|
||||
f.state.keys.push(agent, other, orphan, odd);
|
||||
const foreign = f.state.keys.filter((k) => k !== orphan && k !== odd);
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
// A malformed name under the Triage prefix is still Triage's, as the bus treats its own prefix.
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(orphan)}, ${id(odd)}\\n$`));
|
||||
for (const verb of ["rotate", "retire"]) { f.now += 3 * HOUR; ok(await f.cli(["triage", "key", verb])); }
|
||||
for (const k of foreign) assert.ok(f.state.keys.includes(k), "a key outside the namespace left the list");
|
||||
assert.equal(f.state.keys.includes(orphan), false);
|
||||
assert.equal(f.state.keys.includes(odd), false);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the PUT, before the read-back: the fence holds; status says so; clear, then issue recovers", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const crashed = await f.crash(["triage", "key", "issue"], "put");
|
||||
assert.equal(crashed.signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`proxy fence: set[^\\n]*\\nkeys in the Triage namespace the file does not hold: ${id(f.triageKeys()[0])}\\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\\n$`));
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
assert.equal(f.fenced(), false);
|
||||
const stray = f.triageKeys()[0];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(stray)}\\n$`));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the read-back, before the file write: no fence; status names the stray key; issue removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const [stray] = f.triageKeys();
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`^triage key: not issued\\n[^]*keys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// The same crash in rotate: the file keeps the old key, the stray new one is named, retire removes it.
|
||||
const held = f.record();
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "write")).signal, "SIGKILL");
|
||||
assert.deepEqual(f.record(), held);
|
||||
const strayNew = f.triageKeys().find((k) => k !== held.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`proxy: holds the key\\nkeys in the Triage namespace the file does not hold: ${id(strayNew)}\\nnext: mosaic triage key retire\\n$`));
|
||||
const retired = await f.cli(["triage", "key", "retire"]);
|
||||
ok(retired);
|
||||
assert.equal(retired.stdout, `triage key retire: removed ${id(strayNew)}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [held.key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("file written but the old key not yet retired: status shows it due; a crash inside retire recovers on the next retire", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now = NOW + 121 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after [^\\n]* \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
// retire dies after the proxy dropped the key but before the file was rewritten.
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.state.keys.includes(first.key), false);
|
||||
assert.equal(f.record().retiring.length, 1);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /\(due\) \(not in the proxy list\)\n[^]*next: mosaic triage key retire\n$/);
|
||||
const puts = f.state.puts.length;
|
||||
const r = await f.cli(["triage", "key", "retire"]);
|
||||
ok(r);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
// And a retire killed after its PUT leaves the fence, like any other write.
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now += 121 * MIN;
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "put")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
refusal(await f.cli(["triage", "key", "retire"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a file that cannot be written after the proxy changed is reported with its recovery", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.mkdirSync(f.dir, { mode: 0o700 });
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "write") fs.chmodSync(f.dir, 0o755); } } });
|
||||
refusal(r, "triage-key-unwritten", "the proxy list changed but ");
|
||||
assert.match(r.stderr, /run mosaic triage key issue again, which clears what this run left\n$/);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.chmodSync(f.dir, 0o700);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the temp file, before its rename: status counts it; the next verb removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "rename")).signal, "SIGKILL");
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const temps = fs.readdirSync(f.dir).filter((n) => n.endsWith(".tmp"));
|
||||
assert.equal(temps.length, 1);
|
||||
assert.match(temps[0], /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/);
|
||||
// The temp file holds the key the proxy now has; that is why it must go.
|
||||
const [stray] = f.triageKeys();
|
||||
assert.ok(fs.readFileSync(join(f.dir, temps[0]), "utf8").includes(stray));
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`leftover temp files in the triage secrets directory: 1 \\(the next issue, rotate or retire removes them\\)\\nkeys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
// Something else in the directory is not a leftover and stays.
|
||||
fs.writeFileSync(join(f.dir, "notes.tmp"), "", { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// Retire, with nothing else to do, still removes a leftover.
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "rename")).signal, "SIGKILL");
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.doesNotMatch((await f.cli(["triage", "key", "status"])).stdout, /leftover/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("the receipts file is checked before the proxy changes; a receipt that fails after is named", async (t) => {
|
||||
const receipts = (f) => join(f.root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
const spoils = [
|
||||
["mode", (f) => { fs.writeFileSync(receipts(f), "", { mode: 0o644 }); fs.chmodSync(receipts(f), 0o644); }, "the proxy receipts file mode is not 0600"],
|
||||
["link", (f) => { fs.writeFileSync(join(f.root, "elsewhere"), "", { mode: 0o600 }); fs.symlinkSync(join(f.root, "elsewhere"), receipts(f)); }, "the proxy receipts file cannot be opened"],
|
||||
["FIFO", (f) => assert.equal(spawnSync("mkfifo", ["-m", "600", receipts(f)]).status, 0), "the proxy receipts file cannot be opened"],
|
||||
];
|
||||
for (const [name, spoil, words] of spoils) {
|
||||
const f = await fixture(t);
|
||||
spoil(f);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-receipts-unsafe", `${words}; nothing was changed\n$`);
|
||||
assert.equal(f.state.puts.length, 0, name);
|
||||
assert.equal(f.fenced(), false, name);
|
||||
assert.equal(fs.existsSync(f.file), false, name);
|
||||
f.scan();
|
||||
}
|
||||
// Safe before the change, unsafe at the receipt: the change stands and the refusal says so.
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "receipt") fs.chmodSync(receipts(f), 0o644); } } });
|
||||
refusal(r, "triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status\n$");
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(receipts(f), "utf8"), "");
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a directory sync that fails after the rename is named, and the receipt is still written", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "sync") throw new Error("EIO"); } } });
|
||||
refusal(r, "triage-key-unsynced", `${f.file.replace(/[.]/g, "\\.")} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status\n$`);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(f.triageKeys(), [rec.key]);
|
||||
assert.deepEqual(f.receipts().map((e) => e.addedKeyIds), [[rec.keyId]]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\nnext: nothing\n$/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("an unexpected error prints fixed words, never the error's own text", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const secret = `mst-${tag(f.configDir)}-triage-${b64()}`;
|
||||
SEEN.add(secret);
|
||||
// Outside the proxy write: the verb's own fallback line.
|
||||
const broken = { dataRoot: f.root, get proxy() { throw new Error(`boom ${secret}`); } };
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { system: broken });
|
||||
assert.equal(r.code, 3, verb);
|
||||
assert.equal(r.stderr, "mosaic: triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status\n");
|
||||
}
|
||||
// Inside the proxy write: the write's own fixed line, and the fence stays for a human.
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "put") throw new Error(`boom ${secret}`); } } });
|
||||
refusal(r, "triage-key-failed", "the proxy write failed\n$");
|
||||
assert.equal(f.fenced(), true);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
// The org bus reconciles its own `mso-` namespace at start and a no-org bus its `msk-` one; a
|
||||
// Triage key sits in neither, so both leave it. Stray keys in each namespace show the reconcile ran.
|
||||
test("an org bus that starts and reconciles, and a no-org reconcile, both leave the Triage key alone", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const triage = f.record().key;
|
||||
const strayOrg = `mso-${tag(f.configDir)}-demo-key-${b64()}`;
|
||||
f.state.keys.push(strayOrg);
|
||||
const rolesDir = rolesCopy(f.root), system = systemFor(f.root), doc = businessDoc(f.root, "demo");
|
||||
doc.plugins = { ...doc.plugins, harness: ["pi"] };
|
||||
const file = writeJson(join(f.configDir, "businesses", "demo.json"), doc);
|
||||
assert.ok(file);
|
||||
const business = loadBusiness("demo", { dir: f.configDir, rolesDir }), resolved = {};
|
||||
for (const instance of Object.keys(business.roles)) resolved[instance] = resolveInstance({ system, business, instance });
|
||||
fs.mkdirSync(join(f.root, "data"), { mode: 0o700 });
|
||||
new Registry(join(f.root, "data"));
|
||||
const bus = await startBroker({ dataRoot: join(f.root, "data"), businesses: { demo: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir, system }, proxy: { port: f.port, binary: "/fixture-unused" },
|
||||
org: { id: "demo" }, instanceDataRoot: f.root, instanceConfigDir: f.configDir });
|
||||
f.closers.push(() => bus.close());
|
||||
const orgKey = (await bus.modelPreflight({ business: "demo", role: "chief" })).key;
|
||||
assert.ok(orgKey.startsWith(`mso-${tag(f.configDir)}-demo-key-`));
|
||||
assert.equal(f.state.keys.includes(strayOrg), false, "the org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the org bus removed the Triage key");
|
||||
// A no-org reconcile on the same instance.
|
||||
const strayAgent = `msk-${tag(f.configDir)}-${b64()}`;
|
||||
f.state.keys.push(strayAgent);
|
||||
const client = new ManagementClient({ baseUrl: `http://127.0.0.1:${f.port}`, key: MANAGE });
|
||||
const keys = new ModelKeys({ credentials: { status: () => [], modelRecord: () => null }, client, configDir: f.configDir, baseUrl: `http://127.0.0.1:${f.port}` });
|
||||
await keys.reconcile();
|
||||
assert.equal(f.state.keys.includes(strayAgent), false, "the no-org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the no-org reconcile removed the Triage key");
|
||||
// Triage still works under the shared lock while the org bus runs, and leaves the org key.
|
||||
f.now += HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
assert.ok(f.state.keys.includes(orgKey));
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\n/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("scripts/mosaic routes triage key status with the instance's own config directory", (t) => {
|
||||
const home = fs.mkdtempSync(join(tmpdir(), "tkm-"));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-tktest/config.json") });
|
||||
const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "tktest"], { env, encoding: "utf8" });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const r = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "status"], { env, encoding: "utf8", timeout: 60000 });
|
||||
OUTPUTS.push(r.stdout, r.stderr);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, `triage key: not issued\nfile: ${join(home, ".config/mosaic-tktest/secrets/triage/model")}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
const refused = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "issue"], { env: { ...env, CLAUDECODE: "1" }, encoding: "utf8", timeout: 60000 });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /found CLAUDECODE in the environment/);
|
||||
});
|
||||
|
||||
test("no output of any verb in this file holds any key the stand-in saw", () => {
|
||||
assert.ok(SEEN.size >= 20, `only ${SEEN.size} keys were seen`);
|
||||
assert.ok(OUTPUTS.length >= 100);
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false);
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
// #1873 triage-route-store: `mosaic triage route show|set`, the owner's terminal verbs for the
|
||||
// Triage route file (packages/webui/src/triage-route-store.mjs). Human verbs: an agent run is
|
||||
// refused before anything is read (exit 3), as the other human verbs refuse it. `show` with no
|
||||
// file says the route is not set and exits 0.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { run } from "../src/cli.mjs";
|
||||
import { AGENT_MARKERS } from "../src/transport.mjs";
|
||||
import { routePaths } from "../../webui/src/triage-route-store.mjs";
|
||||
import { humanEnv, io } from "./helpers.mjs";
|
||||
|
||||
const REPO = new URL("../../../", import.meta.url).pathname;
|
||||
const MOSAIC = join(REPO, "scripts/mosaic");
|
||||
const NOW = new Date("2026-11-18T12:00:00.000Z");
|
||||
const SET = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "200000", "--time-zone", "America/Chicago"];
|
||||
|
||||
function dataRoot(t) {
|
||||
const d = mkdtempSync(join(tmpdir(), "tr-"));
|
||||
t.after(() => rmSync(d, { recursive: true, force: true }));
|
||||
return d;
|
||||
}
|
||||
async function cli(argv, d, env = humanEnv()) {
|
||||
const s = io(env);
|
||||
const code = await run(argv, s, { system: { dataRoot: d }, now: () => NOW });
|
||||
return { code, stdout: s.out.text, stderr: s.err.text };
|
||||
}
|
||||
|
||||
test("show with no route says it is not set and exits 0", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
assert.deepEqual(await cli(["triage", "route", "show"], d), { code: 0, stdout: "triage route: not set\n", stderr: "" });
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
|
||||
test("set writes the route; show reads it back", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
const set = await cli(SET, d);
|
||||
assert.equal(set.code, 0, set.stderr);
|
||||
assert.equal(set.stdout, "triage route set: revision 1\n");
|
||||
const shown = await cli(["triage", "route", "show"], d);
|
||||
assert.equal(shown.code, 0);
|
||||
assert.equal(shown.stdout, [
|
||||
"triage route: revision 1",
|
||||
"model: glm-5",
|
||||
"harness: claude-code",
|
||||
"cap: 200000 tokens a day, resets 00:00 America/Chicago, counted since 2026-11-18T12:00:00.000Z",
|
||||
"updated: 2026-11-18T12:00:00.000Z by owner",
|
||||
"",
|
||||
].join("\n"));
|
||||
const doc = JSON.parse(readFileSync(routePaths(d).file, "utf8"));
|
||||
assert.equal(doc.updatedBy, "owner");
|
||||
// --revision makes the write conditional on what show printed.
|
||||
const five = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "5", "--time-zone", "America/Chicago", "--revision", "1"];
|
||||
assert.equal((await cli(five, d)).code, 0);
|
||||
assert.equal(JSON.parse(readFileSync(routePaths(d).file, "utf8")).cap.limit, 5);
|
||||
const stale = await cli([...SET, "--revision", "1"], d);
|
||||
assert.equal(stale.code, 3);
|
||||
assert.match(stale.stderr, /^mosaic: triage-route-stale: /);
|
||||
});
|
||||
|
||||
test("refused input exits 2 or 4 and writes nothing", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
const without = (flag) => { const a = [...SET]; const i = a.indexOf(flag); a.splice(i, 2); return a; };
|
||||
const swap = (flag, value) => { const a = [...SET]; a[a.indexOf(flag) + 1] = value; return a; };
|
||||
const cases = [
|
||||
[without("--model"), 4], [without("--harness"), 4], [without("--cap"), 4], [without("--time-zone"), 4],
|
||||
[swap("--cap", "-1"), 2], [swap("--cap", "1e3"), 2], [swap("--cap", "01"), 2], [swap("--cap", "9007199254740993"), 2],
|
||||
[swap("--time-zone", "Atlantis/Lost"), 2], [swap("--model", "Has Space"), 2],
|
||||
[swap("--harness", "nonesuch"), 2], [swap("--harness", "../pi"), 2],
|
||||
[[...SET, "--revision", "x"], 2], [[...SET, "--revision", "-1"], 2],
|
||||
[[...SET, "--cap", "5"], 4], [[...SET, "--unknown", "1"], 4], [[...SET, "extra"], 4],
|
||||
[["triage", "route", "show", "--model", "x"], 4], [["triage", "route", "show", "extra"], 4],
|
||||
[["triage", "route"], 4], [["triage", "route", "remove"], 4], [["triage"], 4], [["triage", "key"], 4],
|
||||
];
|
||||
for (const [argv, want] of cases) {
|
||||
const r = await cli(argv, d);
|
||||
assert.equal(r.code, want, `${argv.join(" ")}: ${r.stderr}`);
|
||||
assert.equal(r.stdout, "");
|
||||
}
|
||||
// An unknown option is named as one, and its value never reaches the message.
|
||||
const unknown = await cli([...SET, "--unknown", "secret-value"], d);
|
||||
assert.equal(unknown.code, 4);
|
||||
assert.match(unknown.stderr, /^mosaic: unknown option\n/);
|
||||
assert.doesNotMatch(unknown.stderr, /secret-value/);
|
||||
assert.equal(existsSync(routePaths(d).file), false);
|
||||
});
|
||||
|
||||
test("an unreadable store exits 3 on show and on set", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
assert.equal((await cli(SET, d)).code, 0);
|
||||
chmodSync(routePaths(d).file, 0o644);
|
||||
for (const argv of [["triage", "route", "show"], [...SET, "--revision", "1"]]) {
|
||||
const r = await cli(argv, d);
|
||||
assert.equal(r.code, 3);
|
||||
assert.match(r.stderr, /^mosaic: triage-route-unreadable: the Triage route store is unreadable: route\.json mode is not 0600\n$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("an agent caller is refused before anything is read, for show and set", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
for (const argv of [["triage", "route", "show"], SET]) {
|
||||
const r = await cli(argv, d, { ...humanEnv(), [marker]: "1" });
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`);
|
||||
}
|
||||
}
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
|
||||
test("scripts/mosaic routes triage to the verb; a marker in the process env refuses", (t) => {
|
||||
const home = mkdtempSync(join(tmpdir(), "trm-"));
|
||||
t.after(() => rmSync(home, { recursive: true, force: true }));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-trtest/config.json") });
|
||||
const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "trtest"], { env, encoding: "utf8" });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const mosaic = (args, extra = {}) => spawnSync(MOSAIC, args, { env: { ...env, ...extra }, encoding: "utf8", timeout: 60000 });
|
||||
const shown = mosaic(["triage", "route", "show"]);
|
||||
assert.equal(shown.status, 0, shown.stderr);
|
||||
assert.equal(shown.stdout, "triage route: not set\n");
|
||||
const set = mosaic(SET.slice(0));
|
||||
assert.equal(set.status, 0, set.stderr);
|
||||
assert.equal(set.stdout, "triage route set: revision 1\n");
|
||||
const dataDir = join(home, ".mosaic-trtest");
|
||||
assert.equal(JSON.parse(readFileSync(routePaths(dataDir).file, "utf8")).model, "glm-5");
|
||||
const refused = mosaic(["triage", "route", "show"], { CLAUDECODE: "1" });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /found CLAUDECODE in the environment/);
|
||||
assert.equal(refused.stdout, "");
|
||||
});
|
||||
|
||||
test("a marker in this process's own environment refuses even when the command's env is clean", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
const saved = process.env[marker];
|
||||
process.env[marker] = "1";
|
||||
try {
|
||||
for (const argv of [["triage", "route", "show"], SET]) {
|
||||
const r = await cli(argv, d, humanEnv());
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.match(r.stderr, new RegExp(`found ${marker} in the environment`));
|
||||
}
|
||||
} finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; }
|
||||
}
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
+116
-7
@@ -18,13 +18,122 @@ Every harness layer below is a row S0 line
|
||||
(`docs/plans/2026-10-04_slice-1.md`, "What S6 can rely on"), and each
|
||||
bundle's `manifest.json` names the lines it relies on (`reliesOn`):
|
||||
|
||||
| | Pi | Claude Code |
|
||||
|---|---|---|
|
||||
| 1. block a tool | `tool_call` handler returns a block | PreToolUse command hook exits 2; `--bare` is never passed |
|
||||
| 2. gate crash | a throw in the handler blocks | the hook runs as `<gate> \|\| exit 2` |
|
||||
| 3. gate missing | a missing `-e` file refuses to start | the wrapper blocks |
|
||||
| 4. gate hang | the runner's wall clock plus the `agent_end` marker | `timeout -k 2 10 <gate> \|\| exit 2`, hook timeout 20 |
|
||||
| 5. bash | limited only by the tool limit | limited only by the tool limit |
|
||||
| | Pi | Claude Code | How pi's line is checked |
|
||||
|---|---|---|---|
|
||||
| 1. block a tool | `tool_call` handler returns a block | PreToolUse command hook exits 2; `--bare` is never passed | suites, on the repository's pi (`pi-session.test.mjs`) |
|
||||
| 2. gate crash | a throw in the handler blocks | the hook runs as `<gate> \|\| exit 2` | suites, on the repository's pi |
|
||||
| 3. gate missing | a missing `-e` file refuses to start | the wrapper blocks | at every start, by the fit check, on the pi that runs; and suites |
|
||||
| 4. gate hang | the runner's wall clock plus the `agent_end` marker | `timeout -k 2 10 <gate> \|\| exit 2`, hook timeout 20 | suites, on the repository's pi |
|
||||
| 5. bash | limited only by the tool limit | limited only by the tool limit | suites, on the repository's pi |
|
||||
|
||||
Pi is not pinned (#1873 pi-unpin). Before a session starts, `preflight`
|
||||
awaits the fit check in `src/pi-fit.mjs` on the binary the module found
|
||||
(the Triage host and route await the module's `ready` instead), and
|
||||
`env` reads its pass. It runs that binary in a sandbox with the network
|
||||
unshared and calls no model. Each run is a child process the check
|
||||
awaits, up to four at a time, so the bus's event loop keeps running
|
||||
while it does; callers that ask while a check runs share it. Each run
|
||||
gets the environment a bus session's pi gets, built by the same code
|
||||
(the launcher's `ENV_ALLOW` and `sessionEnv`, the sandbox's
|
||||
`sessionSetenv`, the runner's `adapterEnv` and the pi module's
|
||||
`harnessEnv`) from the bus process's own environment, less the provider
|
||||
keys, and starts the binary through `/bin/sh` as the adapter does. So
|
||||
`HOME` is a scratch home, `TMPDIR` is `/tmp` bound to scratch, a run has
|
||||
`TERM`, `TZ` or `LC_ALL` only when the bus has it (a bus started by its
|
||||
unit has none), and no run sets `PI_CODING_AGENT_DIR`, which no session
|
||||
has: pi's agent directory is `$HOME/.pi/agent`, where the user sources
|
||||
are planted. A test fails when the fit runs' names, or the values the
|
||||
code sets, differ from a bus session's, apart from the provider
|
||||
variables, for a login shell's host and a unit's. It needs
|
||||
`--help` to list, in its option column, every flag the adapter passes
|
||||
(with rpc mode and each thinking level), and a missing `-e` file to stop
|
||||
the start in rpc and in `-p`. The planted ambient sources must stay
|
||||
unloaded with the seal flags on (skills and prompt templates are read
|
||||
from `get_commands` in rpc and from the `-e` extension's command list in
|
||||
`-p`): extensions, MCP
|
||||
servers, skills and prompt templates (found in their directories, listed
|
||||
in a `settings.json`, or in a local package a `settings.json` lists),
|
||||
context files (`AGENTS.md`, `CLAUDE.md`, `SYSTEM.md`) and a trusted
|
||||
project's `.pi/SYSTEM.md` and `.pi/APPEND_SYSTEM.md`. The project has a
|
||||
saved trust, so only `--no-approve` keeps those two out. An `-e`
|
||||
extension writes the system prompt, command names and session id it sees
|
||||
at `session_start`; the sealed runs must show the `--system-prompt` file
|
||||
and none of the planted sources. A control run passes the seal flags less every loader flag
|
||||
(`--no-approve`, `--no-extensions`, `--no-skills`,
|
||||
`--no-prompt-templates`, `--no-context-files`, and `--no-mcp` when
|
||||
listed), so it keeps `--offline`, `--no-themes`, `--no-tools` and
|
||||
`--no-session`, and the same `-e` and `--system-prompt`. It must show
|
||||
each kind of source (an MCP server only when `--help` lists `--no-mcp`)
|
||||
and answer `get_state` and `get_commands`, and its `-e` extension must
|
||||
list the planted skill and prompt template, or the check can't tell and
|
||||
refuses. For every kind but the trusted project files, only a source
|
||||
outside the project counts there, since a project source can wait on
|
||||
trust and `--no-approve` would then hide a seal flag the binary ignores.
|
||||
Then one sealed rpc run per loader flag leaves out only that flag: its
|
||||
kind must show, and no other kind (an MCP server may show beside an
|
||||
extension when `--help` lists no `--no-mcp`, since pi then ties MCP to
|
||||
`--no-extensions`). So each loader flag is shown to keep its own kind
|
||||
out, and no other seal flag, nor their order, can stand in for it. Five
|
||||
sealed `-p` runs have a bus session's shape: the arguments the adapter
|
||||
passes for a session, in its order, from `sessionShape` in
|
||||
`src/pi-fit.mjs`, with two `-e` and `--session-dir`. The adapter's four
|
||||
session branches (a tool list or `--no-tools`, `-c` over a stored
|
||||
session or none, `--thinking` or none, `--mode json` or none) are spread
|
||||
over the five runs so every pair of them is passed together. A `-c` run
|
||||
gets a stored session and must resume it. Each must load both `-e`
|
||||
files and show no planted source. A test drives the adapter, in a bus
|
||||
session's environment, through every branch set with no tools, one or
|
||||
two, `-c` over a pi-named session file or an unrelated file, each
|
||||
thinking level and each provider a session can name. It runs over a
|
||||
login shell's host and a unit's, and fails on an argv `sessionShape`
|
||||
doesn't build, a pair no run passes, or a variable the adapter reads
|
||||
that no session sets. So a branch on `TZ` or `LC_ALL` being unset, or on
|
||||
`TERM` missing from the environment, turns it red. (Bash run as
|
||||
`/bin/sh` sets an unset `TERM` to `dumb` for the shell without exporting
|
||||
it, so `${TERM:-}` in the adapter is never empty, in a session or here.)
|
||||
It can't see a branch keyed on a
|
||||
value it doesn't try (a model, a path, another tool or provider). A last `-p` run is the
|
||||
argv the adapter builds in `-p` with `MOSAIC_SKILLS`, one `-e` file, no
|
||||
tools and no session (`workerShape`), so `--no-skills` and then two
|
||||
`--skill` directories, `--no-tools`, `--no-session`, `--provider` and
|
||||
`--model`. A test runs the adapter and holds its argv to `workerShape`.
|
||||
No caller makes this exact run today: task launches refuse skill
|
||||
directories, and only the interactive launch (`scripts/agent.sh`) sets
|
||||
`MOSAIC_SKILLS`, in the TUI, which no fit run can drive. It is the
|
||||
nearest headless form of the adapter's `--skill` argv.
|
||||
The run's `-e` extension must list both skills and no planted one. pi
|
||||
0.85.1 adds a `--skill` directory to discovery, so a pi that let
|
||||
`--skill` bring the planted skills back is refused there, and so is one
|
||||
that drops a `--skill` directory once `--no-skills` is on. This run
|
||||
replaces the plain sealed `-p` run with `--no-session` and no `--skill`,
|
||||
so it adds no run. Each run gets a fresh scratch directory, so no run sees
|
||||
what another left. Not run: `--fork` and the interactive TUI
|
||||
(worker containers and `scripts/agent.sh` only), `-p` with
|
||||
`--no-session` and no `--skill` (a task launch's shape; every bus session
|
||||
passes `--session-dir`), `--skill` beside `--tools`, `--session-dir`,
|
||||
`-c`, `--thinking` or `--mode json`, or in rpc (the TUI launch passes the
|
||||
first three; no bus session passes `--skill`), `--skill` with no `-e`
|
||||
(every fit run needs its `-e` extension to see what loaded), one or three
|
||||
or more `--skill` directories, the branches three or
|
||||
four at a time beyond the five runs, `-c` over a session directory that
|
||||
holds nothing for the project (one more run costs about 340 ms cold),
|
||||
and a session's own values (tools beyond `read` and `bash`, thinking
|
||||
levels beyond `low`, provider, model, key, `-e` files, request). The
|
||||
runs are offline with no key, so nothing past the start is tried. A pi
|
||||
built to act one way in the fit runs and another way with those is
|
||||
outside what a start-time check can catch. A run killed for taking
|
||||
over 20 s or printing over 4 MB can't be checked and says which. A
|
||||
`--version` that fails or hangs past 3 s only leaves no label. Pi
|
||||
0.85.1 appends the agent directory's `APPEND_SYSTEM.md` whatever the
|
||||
flags, so the check doesn't plant one. Any failure refuses the launch with
|
||||
`harness-feature-missing` and one line that names the binary by its label,
|
||||
for example `pi 2.0.0 (MOSAIC_PI_BIN) lacks --no-context-files`. When
|
||||
`--help` lists `--no-mcp`, the adapter passes it too. A pass is cached in
|
||||
memory by a digest of the package's files (and npm's lock files, for
|
||||
the repository's copy) and the names in the runs' environment, so a bus
|
||||
restarted under other names checks again. Lines 1, 2, 4 and 5 are not
|
||||
checked at start; a pi other than the repository's copy relies on them
|
||||
unproved until a scripted-model fit run exists (design section 5, S6).
|
||||
|
||||
Claude Code also runs with `--restricted`: no user, project or local
|
||||
settings, file tools confined to the working directory, and no `CLAUDE.md`
|
||||
|
||||
@@ -100,7 +100,8 @@ export function sessionModel(resolved, models = null, which = "primary", { proxy
|
||||
if (models === null) return { harness, provider: null, model, thinking };
|
||||
const entry = Object.hasOwn(models, model) ? models[model] : null;
|
||||
if (!entry) throw new BundleError(`instance ${resolved.instance}: unknown model table selection for ${ROUTE_VARS[which][1]} var`);
|
||||
const transport = entry.provider === "proxy" || proxy ? checkedTransport(entry, null, resolver) : null;
|
||||
// #1873 harness-matrix: the route's own harness, so a model the module holds off it refuses here.
|
||||
const transport = entry.provider === "proxy" || proxy ? checkedTransport(entry, harness, resolver) : null;
|
||||
return { harness, provider: entry.provider, model: entry.model, modelKey: model, thinking,
|
||||
...(transport ? { proxyRoute: transport.routeId, proxyTransport: transport } : {}) };
|
||||
|
||||
@@ -432,9 +433,13 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
|
||||
];
|
||||
// The module's own files. A name the bundle already wrote refuses at write (flag wx).
|
||||
const transports = {};
|
||||
// #1873 harness-matrix: only models the provider's route() lets this session's harness run, so a
|
||||
// pi session's models.json never names an upstream claude model or a Claude-named legacy entry.
|
||||
// route() has no account data: a module entry the catalogue holds to claude-code for an OAuth name
|
||||
// can still be listed. Only the session's own model is admitted against the catalogue.
|
||||
if (proxy) for (const [key, entry] of Object.entries(models ?? {})) {
|
||||
try { transports[key] = checkedTransport(entry, null, resolver); }
|
||||
catch (e) { if (e?.code !== 'proxy-provider-unsupported') throw e; }
|
||||
try { transports[key] = checkedTransport(entry, model.harness, resolver); }
|
||||
catch (e) { if (!['proxy-provider-unsupported', 'model-harness-incompatible'].includes(e?.code)) throw e; }
|
||||
}
|
||||
const own = harness.bundle({ dir, files: { ...files }, session: { ...session, ...model }, write, quote, models, proxy, transports });
|
||||
Object.assign(files, own.files);
|
||||
|
||||
@@ -1,2 +1,155 @@
|
||||
// Shared by the sender and recipient's reply-cycle check.
|
||||
export const LENGTH_FAILURE_NOTICE_PREFIX = 'Mosaic turn failure: ';
|
||||
|
||||
// #1873 chat-fail F1: the plain cause of a failed turn. It lives here, not in a file of its own,
|
||||
// because the session sandbox mounts only RUNNER_FILES (packages/seat/src/sandbox.mjs) and this
|
||||
// file is already one of them.
|
||||
//
|
||||
// The adapter contract (adapters/README.md) puts the answer on stdout and makes a
|
||||
// nonzero exit a failure. A harness that ends on an error result may still print that
|
||||
// result on stdout before it exits nonzero. That text is the only cause the runner
|
||||
// has, so the chat line carries it, made safe first:
|
||||
//
|
||||
// 0. %XX escapes and HTML character references are decoded and the text is put in NFKC
|
||||
// form, so an encoded or full-width email, path or secret is seen as itself.
|
||||
// 1. ANSI escapes go, every control, format, separator, surrogate and private-use
|
||||
// character goes, and whitespace collapses to single spaces.
|
||||
// 2. If a secret the turn's environment holds (a variable named like a key, token,
|
||||
// secret, password or credential) appears in the text, even split by whitespace or
|
||||
// controls, no text is shown at all.
|
||||
// 3. Links, email addresses, absolute and Windows paths, "Bearer x" values, the value after
|
||||
// a key word ("key: x", "\"api_key\":\"x\"", "token x"), known key prefixes and long
|
||||
// letter-and-digit runs become [redacted].
|
||||
// 4. The rest is cut to CAUSE_MAX characters.
|
||||
//
|
||||
// Only the last READ_MAX characters are classified and shown. A harness prints its error
|
||||
// result last, and an answer streamed before the failure may itself talk about limits or
|
||||
// signing in. Redaction runs over the whole text first, so the cut never parts a key word
|
||||
// from its value.
|
||||
//
|
||||
// Three causes are recognised from the text and shown as a fixed plain line with the
|
||||
// next step: the account is out of usage, its sign-in expired or was refused, or it
|
||||
// doesn't offer the model. Anything else shows the cleaned text. The fixed lines never
|
||||
// carry any of the error's own words.
|
||||
|
||||
export const CAUSE_MAX = 300;
|
||||
const READ_MAX = 2000;
|
||||
export const PLAIN = Object.freeze({
|
||||
usage: "the model account is out of usage. Check Settings > Model setup.",
|
||||
signin: "the model account's sign-in expired or was refused. Sign in again in Settings > Model setup.",
|
||||
model: "the model this agent uses isn't offered by its account. Pick another model in Settings > Model setup.",
|
||||
});
|
||||
export const WITHHELD = "the error text held a secret, so it isn't shown. Check Settings > Model setup.";
|
||||
|
||||
const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
|
||||
// Cf (format: zero-width, bidi overrides) is removed so a split token rejoins and is seen.
|
||||
const INVISIBLE = /[\p{Cf}\p{Cs}\p{Co}]/gu;
|
||||
// Cc (C0, DEL, C1), line and paragraph separators become spaces.
|
||||
const BREAKS = /[\p{Cc}\p{Zl}\p{Zp}]/gu;
|
||||
|
||||
const USAGE = /usage limit|hit your [\w -]{0,24}limit|(?<!context |output |token |length )limit reached|credit balance is too low|insufficient[_ ]quota|quota (?:exceeded|exhausted)|exceeded your current quota|out of (?:usage|credits)/i;
|
||||
const SIGNIN = /(?:oauth |access |auth )?token (?:has )?expired|invalid api key|invalid x-api-key|invalid bearer token|authentication_error|authentication failed|run \/login|not logged in|unauthori[sz]ed|(?:error|status)[: ]+401\b|sign[- ]?in (?:again|required|expired)|log ?in (?:again|required|expired)|invalid_grant/i;
|
||||
const MODEL = /issue with the selected model|model_not_found|\bmodel\b.{0,80}\b(?:not found|does not exist|not available|isn't available|not supported|may not exist|not offered|no access)|not_found_error.{0,80}\bmodel\b|unknown model|no such model/i;
|
||||
|
||||
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", commat: "@", lowbar: "_", period: ".", colon: ":", sol: "/", bsol: "\\", num: "#", equals: "=", hyphen: "-", dash: "-" };
|
||||
function codePoint(n) {
|
||||
return Number.isInteger(n) && n > 0 && n <= 0x10ffff && (n < 0xd800 || n > 0xdfff) ? String.fromCodePoint(n) : " ";
|
||||
}
|
||||
// %XX escapes (twice encoded included) and HTML character references are decoded, then NFKC
|
||||
// folds full-width and compatibility forms to their plain letters.
|
||||
export function decodeText(text) {
|
||||
let out = String(text);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const next = out
|
||||
.replace(/(?:%[0-9a-f]{2})+/gi, run => { try { return decodeURIComponent(run); } catch { return run.replace(/%([0-9a-f]{2})/gi, (_, h) => String.fromCharCode(parseInt(h, 16))); } })
|
||||
.replace(/&#(\d{1,7});?|&#x([0-9a-f]{1,6});?|&([a-z]{2,7});/gi, (all, dec, hex, name) =>
|
||||
dec ? codePoint(Number(dec)) : hex ? codePoint(parseInt(hex, 16)) : ENTITY[name.toLowerCase()] ?? all);
|
||||
if (next === out) break;
|
||||
out = next;
|
||||
}
|
||||
return out.normalize("NFKC");
|
||||
}
|
||||
// The text with every space, control, format, mark, surrogate and private-use character gone,
|
||||
// for the env-secret check.
|
||||
function compactText(text) {
|
||||
return decodeText(text).replace(ANSI, "").replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{M}\p{Z}\s]/gu, "");
|
||||
}
|
||||
|
||||
const SECRET_NAME = /KEY|TOKEN|SECRET|PASS|CRED|AUTH|COOKIE/i;
|
||||
// Values from the turn's environment that must never reach a chat line.
|
||||
export function secretValues(env) {
|
||||
const out = [];
|
||||
for (const [name, value] of Object.entries(env ?? {})) {
|
||||
if (typeof value !== "string" || !SECRET_NAME.test(name)) continue;
|
||||
const compact = compactText(value);
|
||||
if (compact.length >= 8) out.push(compact);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A key word, with any prefix joined by _ or - (access_token, client_secret, x-api-key).
|
||||
const KEY_WORD = "(?:\\w*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization|cookie|session)";
|
||||
// Redaction runs over the whole text, up to the runner's 128000 characters, so a pattern that
|
||||
// could start anywhere inside a long run without spaces starts only where the run starts: it
|
||||
// matches the same text in linear time, not quadratic.
|
||||
const REDACT = [
|
||||
/(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/\S*/gi, // any link, its userinfo and query included, from the run's start
|
||||
/\bwww\.\S+/gi,
|
||||
/(?<!\S)(?=\S*\S@\S)\S+/g, // email addresses and user@host: the whole run holding the @
|
||||
/(?:^|(?<=[\s("'=:]))(?:~|\.{1,2})?\/\S+/g, // absolute and home paths
|
||||
/\b[A-Za-z]:\\\S*/g, // Windows paths
|
||||
/\\\\\S+/g, // UNC paths
|
||||
/\b(?:bearer|basic)\s+\S+/gi,
|
||||
// The value after a key word: "key: x", "key=x" and the JSON form "\"api_key\":\"x\"" always;
|
||||
// "token x" with only a space when x is quoted, holds a digit or is 8 characters or more.
|
||||
new RegExp(`\\b${KEY_WORD}["']?\\s*[:=]\\s*(?:"[^"]*"?|'[^']*'?|[^\\s,;}]+)`, "gi"),
|
||||
new RegExp(`\\b${KEY_WORD}["']?\\s+(?:"[^"]*"?|'[^']*'?|(?=[^\\s"',;}]*\\d)[^\\s"',;}]+|[^\\s"',;}]{8,})`, "gi"),
|
||||
/\b(?:sk|msk|rk|pk|ghp|gho|ghs|glpat|xox[a-z])[-_]\S+/gi,
|
||||
/\beyJ\S+/g, // JWT
|
||||
// A long run that mixes letters and digits, or any very long run, reads as a key.
|
||||
/[A-Za-z0-9_\-+/=.]{32,}/g,
|
||||
/(?<![A-Za-z0-9_\-+/=.])(?=[A-Za-z0-9_\-+/=.]*\d)(?=[A-Za-z0-9_\-+/=.]*[A-Za-z])[A-Za-z0-9_\-+/=.]{16,}/g,
|
||||
];
|
||||
|
||||
export function cleanText(text) {
|
||||
return String(text).replace(ANSI, "").replace(INVISIBLE, "").replace(BREAKS, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
// A text read from its tail keeps its end, where the error is; any other keeps its start.
|
||||
function cap(text, fromEnd = false, n = CAUSE_MAX) {
|
||||
const chars = Array.from(text);
|
||||
if (chars.length <= n) return text;
|
||||
return fromEnd ? "..." + chars.slice(-(n - 3)).join("") : chars.slice(0, n - 3).join("") + "...";
|
||||
}
|
||||
|
||||
// The plain cause for a failed turn's stdout, or null when there is no text.
|
||||
// `secrets` is secretValues(env) for the turn.
|
||||
export function turnCause(stdout, secrets = []) {
|
||||
if (typeof stdout !== "string") return null;
|
||||
const decoded = decodeText(stdout);
|
||||
const clean = cleanText(decoded);
|
||||
if (!clean) return null;
|
||||
// The secret check covers the whole text, not only the part that is read.
|
||||
const compact = compactText(stdout);
|
||||
if (secrets.some(value => compact.includes(value))) return WITHHELD;
|
||||
// Only the tail is classified and shown. Redaction runs over the whole text before any cut,
|
||||
// so a cut that lands between a key word and its value can't leave the value bare.
|
||||
const tail = clean.length > READ_MAX;
|
||||
const read = tail ? clean.slice(-READ_MAX) : clean;
|
||||
if (USAGE.test(read)) return PLAIN.usage;
|
||||
if (SIGNIN.test(read)) return PLAIN.signin;
|
||||
if (MODEL.test(read)) return PLAIN.model;
|
||||
let shown = clean;
|
||||
for (const re of REDACT) shown = shown.replace(re, "[redacted]");
|
||||
shown = shown.replace(/(?:\[redacted\]\s*){2,}/g, "[redacted] ").trim();
|
||||
// The cut drops the partial word it lands in; a redacted text short enough needs no cut.
|
||||
if (shown.length > READ_MAX) shown = shown.slice(-READ_MAX).replace(/^\S+\s*/, "");
|
||||
// Text that redacts to nothing but [redacted] says nothing; the technical reason stands alone.
|
||||
return shown && shown !== "[redacted]" ? cap(shown, tail) : null;
|
||||
}
|
||||
|
||||
// The chat body for a failed turn: the plain cause first, the technical reason after.
|
||||
export const DETAILS = "\nDetails: ";
|
||||
export function failureBody(turn) {
|
||||
return turn.cause ? `The turn failed: ${turn.cause}${DETAILS}${turn.reason}` : `The turn failed: ${turn.reason}`;
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
// #1873 pi-unpin S3: the start-time fit check for a pi binary the harness module found. Nothing
|
||||
// here compares a version. The check runs the binary only inside a sandbox with the network
|
||||
// unshared, the found package mounted as a session mounts it, and a bus session's environment
|
||||
// (fitEnv below), so its agent directory is $HOME/.pi/agent under a scratch HOME, as a session's
|
||||
// is. No model is called and no provider key is passed. It asks:
|
||||
//
|
||||
// --version a label for the refusal line and the record; not a gate
|
||||
// --help lists, in its option column, every flag Mosaic passes, with rpc mode and each
|
||||
// thinking level
|
||||
// control rpc, planted ambient sources, a saved trust for the project, the seal flags less
|
||||
// every loader flag (the ones that each keep one kind of source out: --no-approve,
|
||||
// --no-extensions, --no-skills, --no-prompt-templates, --no-context-files, and
|
||||
// --no-mcp when --help lists it), the --system-prompt file the sealed runs pass, and
|
||||
// one -e extension that writes what it sees at session_start: the system prompt, the
|
||||
// command names and the session id. The binary answers get_state and get_commands,
|
||||
// its -e extension lists the planted skill and prompt template (the -p runs see
|
||||
// those kinds only that way), and it shows each kind of planted source:
|
||||
// an extension, a skill, a prompt template, a context file, a trusted project file
|
||||
// (the project's .pi/APPEND_SYSTEM.md, which only the trust --no-approve must undo
|
||||
// lets in), and an MCP server when --help lists --no-mcp. Only a source outside the
|
||||
// project counts for the other kinds, since a project source can wait on trust. A
|
||||
// kind it doesn't show could not be told apart from a sealed one.
|
||||
// sealed rpc the adapter's seal flags (and --no-mcp when --help lists it), the -e extension and
|
||||
// --system-prompt. The binary answers both, loads that extension (a session's gate
|
||||
// comes in that way), uses the --system-prompt file, and shows no planted source.
|
||||
// one out one more sealed rpc run per loader flag, with every seal flag but that one. The
|
||||
// kind it keeps out must show, and no other kind (pi without --no-mcp ties MCP to
|
||||
// --no-extensions, so an MCP server may show beside an extension). So each loader flag
|
||||
// is shown to keep its own kind out, and no other seal flag, nor the order they come
|
||||
// in, can stand in for it.
|
||||
// session five -p runs in a bus session's shape, with the arguments adapters/pi/adapter.sh
|
||||
// passes for a session, in its order (sessionShape below): two -e, --session-dir in
|
||||
// place of --no-session, a fixed --provider and --model, -p and a message. The
|
||||
// adapter's four session branches (a tool list or --no-tools, -c over a stored
|
||||
// session or none, --thinking or none, --mode json or none) are spread over the five
|
||||
// runs so each pair of them is passed together (SESSION_RUNS). A -c run gets a
|
||||
// stored session for the project and must resume it. Each run loads both -e
|
||||
// extensions, uses the --system-prompt file, and shows no
|
||||
// planted source. A test drives the adapter through every branch set, tool list
|
||||
// length and thinking level, and fails on an argv sessionShape doesn't build or a
|
||||
// pair no run passes.
|
||||
// worker -p the arguments adapters/pi/adapter.sh builds in -p with MOSAIC_SKILLS, one -e
|
||||
// file, no tools and no session, in its order (workerShape below): the -e,
|
||||
// --no-skills then two --skill directories, --no-tools, --no-session, the fixed
|
||||
// --provider and --model, --system-prompt, -p and a message. Its -e extension must
|
||||
// reach session_start and list both given skills, and no planted source may show.
|
||||
// pi 0.85.1 adds a --skill directory to discovery, so a pi that let --skill turn
|
||||
// discovery back on would show the planted skills here, and one that drops a --skill
|
||||
// directory once --no-skills is on would not list it. No caller makes this exact
|
||||
// run today: task launches refuse skill directories (packages/processing-control
|
||||
// containers.mjs), and only the interactive container launch (scripts/agent.sh)
|
||||
// sets MOSAIC_SKILLS, in the TUI with --tools and --session-dir, which no fit run
|
||||
// can drive. This is the nearest headless form of the adapter's --skill argv. It
|
||||
// replaces the sealed -p run the check made before (the seal flags in -p with
|
||||
// --no-session and no --skill), so it adds no run; that plain shape is not run on
|
||||
// its own any more.
|
||||
// missing -e a missing -e file, in rpc and in -p, stops the start: exit non-zero, no answer,
|
||||
// and no session_start for the -e extension given after it
|
||||
//
|
||||
// Every run gets a fresh scratch directory with the sources planted again, so no run sees what
|
||||
// another one left. The directory's name carries the pid, start time and pid namespace of the
|
||||
// process that made it, and each check first stops the processes and removes the directories a
|
||||
// process no longer running left (sweepScratch below). Every run dies with the process that runs
|
||||
// the check (checkArgv in packages/seat/src/sandbox.mjs), at once when unshare runs here and at
|
||||
// the next check's sweep when it doesn't.
|
||||
// The runs share no state: up to FIT_CONCURRENCY of them run at once,
|
||||
// each a child process the check awaits, so the process that runs the check (the bus) keeps
|
||||
// answering while it runs. --version and --help go first; the rest start in the order above and
|
||||
// are judged in that order, so the first failure is the one a refusal names, and the runs still
|
||||
// going are killed. Each run passes the same -e and --system-prompt; the other runs differ only by
|
||||
// their seal flags, their mode, the -p message and the missing -e file. Each run starts the binary
|
||||
// through /bin/sh, as the adapter does, with fitEnv's variables: the environment a bus session's pi
|
||||
// gets, built by the code that builds it (the launcher's ENV_ALLOW and sessionEnv, the sandbox's
|
||||
// sessionSetenv, the runner's adapterEnv and the pi module's harnessEnv) from the calling process's
|
||||
// own environment, less the provider variables. So a fit run has a name only when a session in that
|
||||
// process has it (TERM, TZ and LC_ALL only when the bus has them), no run sets a variable a session
|
||||
// lacks, such as PI_CODING_AGENT_DIR, and a test holds the two together.
|
||||
//
|
||||
// A check that cannot tell refuses: a sandbox that fails, a run that times out or prints more
|
||||
// than 4 MB, an answer that is missing or doesn't parse, a kind of source the control doesn't
|
||||
// show, or the kind a one-out run should show. A one-out run that shows another kind, or a
|
||||
// session-shaped run that shows any, is a leak. A --version that fails or hangs past 3 s only
|
||||
// leaves no label. A pass is cached in memory by a digest of the files that run (the package's
|
||||
// package.json, every file under dist/bundle/, every file in the directory tree that holds the
|
||||
// binary's real file, and, for a copy mounted with the node_modules it sits in, npm's lock files
|
||||
// there), the mount layout and the names in the fit runs' environment, so a process with other
|
||||
// names checks again. Callers that ask while a check for the same key is running share it.
|
||||
// A refusal line names the found binary by its label (MOSAIC_PI_BIN, the pi on PATH, the
|
||||
// repository's pi), never a host path.
|
||||
//
|
||||
// Known limit: pi 0.85.1 appends the agent directory's APPEND_SYSTEM.md whatever the flags. The
|
||||
// check doesn't plant one; a session's agent directory is the run's own. Not run: --fork and
|
||||
// the interactive TUI, which only worker containers and scripts/agent.sh pass; -p with
|
||||
// --no-session and no --skill (a task launch's shape; every bus session passes --session-dir);
|
||||
// --skill beside --tools, --session-dir, -c, --thinking or --mode json, or in rpc (the TUI
|
||||
// launch passes the first three; no bus session passes --skill); --skill with no -e (every fit
|
||||
// run needs its -e extension to see what loaded); one or three or more --skill directories; the
|
||||
// session branches three or four at a time beyond the session-shaped
|
||||
// runs; -c over a session directory that holds nothing for the project (the adapter passes -c
|
||||
// whenever the directory isn't empty), since one more run costs about 340 ms cold; and a
|
||||
// session's own values: its tool names beyond read and bash, thinking levels beyond low,
|
||||
// provider, model, key, -e files and request. The runs are offline with no key, so nothing
|
||||
// past the start is tried. A pi built to act differently with those is outside what a start-time
|
||||
// check can catch.
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { BWRAP, SETPRIV, UNSHARE, checkArgv, outerArgv, sessionSetenv } from "../../seat/src/sandbox.mjs";
|
||||
import { isProviderVariable, sessionEnv } from "../../seat/src/session.mjs";
|
||||
import { adapterEnv } from "./runner.mjs";
|
||||
import { FIT_ROUTE, harnessEnv } from "../../plugins/harness/pi/session-env.mjs";
|
||||
|
||||
// The flags adapters/pi/adapter.sh and the conversation engine pass.
|
||||
export const FIT_FLAGS = Object.freeze(["--mode", "--session", "--no-session", "--session-dir", "--fork", "-c", "--no-extensions", "-e", "--no-skills", "--skill", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-approve", "--offline", "--tools", "--no-tools", "--provider", "--model", "--thinking", "--system-prompt", "-p"]);
|
||||
// The adapter's seal flags, as it passes them in an ephemeral session with no tools.
|
||||
const SEAL = ["--offline", "--no-approve", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-tools", "--no-session"];
|
||||
// The loader flags: each keeps one kind of planted source out. --no-mcp counts when --help lists it.
|
||||
const LOADERS = [["--no-approve", "trusted project file"], ["--no-extensions", "extension"], ["--no-skills", "skill"], ["--no-prompt-templates", "prompt template"], ["--no-context-files", "context file"]];
|
||||
// The session-shaped runs' fixed values: a two-tool list, a thinking level, a provider and model.
|
||||
// Offline with no key, pi stops before any model call. The provider and model are the pi module's
|
||||
// (session-env.mjs FIT_ROUTE), so no core source names them.
|
||||
export const SESSION_SHAPE = Object.freeze({ tools: "read,bash", thinking: "low", provider: FIT_ROUTE.provider, model: FIT_ROUTE.model });
|
||||
// The branches adapters/pi/adapter.sh takes for a bus session, each run once or not: a tool list or
|
||||
// --no-tools, -c over a stored session or a fresh one, --thinking or none, --mode json (the model
|
||||
// event monitor) or none. The five runs pass every pair of those together; pi-fit.test.mjs drives
|
||||
// the adapter through all sixteen and fails on a pair no run passes.
|
||||
const T = SESSION_SHAPE.tools;
|
||||
const L = SESSION_SHAPE.thinking;
|
||||
export const SESSION_RUNS = Object.freeze([
|
||||
{ tools: "", cont: false, thinking: "", json: false },
|
||||
{ tools: "", cont: true, thinking: L, json: true },
|
||||
{ tools: T, cont: false, thinking: L, json: true },
|
||||
{ tools: T, cont: true, thinking: "", json: true },
|
||||
{ tools: T, cont: true, thinking: L, json: false },
|
||||
].map((r) => Object.freeze(r)));
|
||||
// The arguments adapters/pi/adapter.sh builds for a bus session: the given -e files, a tool list
|
||||
// or none, a persistent session directory with -c when it holds a session, a thinking level or
|
||||
// none, the --system-prompt file, -p and the request, and --mode json when the model event monitor
|
||||
// runs pi. No --skill and no --fork: a bus session never passes them. Keep its order:
|
||||
// pi-fit.test.mjs runs the adapter through every branch and fails when the two differ.
|
||||
export function sessionShape({ noMcp, extensions, prompt, sessionDir, tools, cont, thinking, json, message }) {
|
||||
return [
|
||||
"--offline", "--no-approve", "--no-extensions", ...(noMcp ? ["--no-mcp"] : []), ...extensions.flatMap((e) => ["-e", e]),
|
||||
"--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files",
|
||||
...(tools ? ["--tools", tools] : ["--no-tools"]), "--session-dir", sessionDir, ...(cont ? ["-c"] : []),
|
||||
"--provider", SESSION_SHAPE.provider, "--model", SESSION_SHAPE.model, ...(thinking ? ["--thinking", thinking] : []),
|
||||
"--system-prompt", prompt, "-p", message, ...(json ? ["--mode", "json"] : []),
|
||||
];
|
||||
}
|
||||
// pi-skills: the arguments adapters/pi/adapter.sh builds in -p with MOSAIC_SKILLS, no tools and no
|
||||
// session: the given -e files, --no-skills and then a --skill per directory, --no-tools,
|
||||
// --no-session, the --provider and --model, the --system-prompt file, -p and the request. Only
|
||||
// the interactive launch sets MOSAIC_SKILLS today, in the TUI; this is the nearest headless form. Keep its order: pi-fit.test.mjs runs the adapter with MOSAIC_SKILLS and
|
||||
// fails when the two differ.
|
||||
export function workerShape({ noMcp, extensions, skills, prompt, message }) {
|
||||
return [
|
||||
"--offline", "--no-approve", "--no-extensions", ...(noMcp ? ["--no-mcp"] : []), ...extensions.flatMap((e) => ["-e", e]),
|
||||
"--no-skills", ...skills.flatMap((s) => ["--skill", s]), "--no-prompt-templates", "--no-themes", "--no-context-files",
|
||||
"--no-tools", "--no-session", "--provider", SESSION_SHAPE.provider, "--model", SESSION_SHAPE.model,
|
||||
"--system-prompt", prompt, "-p", message,
|
||||
];
|
||||
}
|
||||
// What a session-shaped run is named by in a refusal line.
|
||||
const shapeName = ({ tools, cont, thinking, json }) => `in a session's shape with ${[tools ? "--tools" : "--no-tools", ...(cont ? ["-c"] : []), ...(thinking ? ["--thinking"] : []), ...(json ? ["--mode json"] : [])].join(", ")}`;
|
||||
const RUN_TIMEOUT = 20000;
|
||||
// --version gives only a label, so a hang costs this much and leaves no label.
|
||||
const VERSION_TIMEOUT = 3000;
|
||||
const OUTPUT_MAX = 4 * 1024 * 1024;
|
||||
// How long a run's pipes may stay open after it exits or is killed (spawned).
|
||||
const PIPE_GRACE = 1000;
|
||||
const DIGEST_FILES_MAX = 20000;
|
||||
|
||||
// At most this many fit runs at once. Each run is one sandboxed pi start in its own scratch
|
||||
// directory.
|
||||
export const FIT_CONCURRENCY = 4;
|
||||
|
||||
const passed = new Map();
|
||||
const running = new Map();
|
||||
|
||||
// #1873 re-check 9: each run's scratch directory is named for the process that makes it, by its
|
||||
// pid and its start time (field 22 of /proc/<pid>/stat), so a pid used again later is not taken
|
||||
// for it. A process killed mid-check can't remove its own directories. So a check removes, before
|
||||
// it starts, every directory here that a process no longer running made: its pid is gone, or now
|
||||
// belongs to a process that started at another time. A directory whose process can't be read, or
|
||||
// one this uid doesn't own, or a symlink, is left alone.
|
||||
//
|
||||
// #1873 re-check 10: the name also carries the maker's pid namespace (the inode of
|
||||
// /proc/<pid>/ns/pid), and a sweep leaves alone every directory made in another one, since it
|
||||
// can't read that process. And before it removes a directory, the sweep stops the processes that
|
||||
// name it on their command line: a run's every layer does (the setpriv, shell, unshare and bwrap
|
||||
// argv, bwrap's child before its exec, pi's own -e and --system-prompt), and so do the sandbox
|
||||
// probes. Without unshare's outer layer a bwrap child killed in its setup waits for good (see
|
||||
// checkArgv in sandbox.mjs), and this is what stops it. A process is stopped only when an argument
|
||||
// is that directory or a path in it, its real and effective uid are this process's, and its start
|
||||
// time is the same before and after its command line is read. Never by name, never another uid's,
|
||||
// never one whose directory's maker still runs.
|
||||
const SCRATCH = /^mosaic-pi-fit-(\d+)-(\d+)-(\d+)-/;
|
||||
const startTime = (pid) => readFileSync(`/proc/${pid}/stat`, "utf8").split(") ").pop().split(" ")[19];
|
||||
const pidNamespace = (pid) => /^pid:\[(\d+)\]$/.exec(readlinkSync(`/proc/${pid}/ns/pid`))[1];
|
||||
let ownName = null;
|
||||
const scratchPrefix = () => `mosaic-pi-fit-${ownName ??= `${process.pid}-${startTime(process.pid)}-${pidNamespace("self")}`}-`;
|
||||
function sweepScratch(dir = tmpdir()) {
|
||||
let names;
|
||||
try {
|
||||
names = readdirSync(dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const uid = process.getuid();
|
||||
const ns = pidNamespace("self");
|
||||
const stale = [];
|
||||
for (const name of names) {
|
||||
const m = SCRATCH.exec(name);
|
||||
if (!m || m[3] !== ns) continue;
|
||||
try {
|
||||
let alive;
|
||||
try {
|
||||
alive = startTime(m[1]) === m[2];
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT") continue;
|
||||
alive = false;
|
||||
}
|
||||
if (alive) continue;
|
||||
const at = join(dir, name);
|
||||
const st = lstatSync(at);
|
||||
if (st.isDirectory() && st.uid === uid) stale.push(at);
|
||||
} catch {}
|
||||
}
|
||||
if (!stale.length) return;
|
||||
stopNaming(stale, uid);
|
||||
for (const at of stale) {
|
||||
try {
|
||||
rmSync(at, { recursive: true, force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// SIGKILL to every process of uid (real and effective) with an argument that is one of dirs or a
|
||||
// path in one, other than this one.
|
||||
function stopNaming(dirs, uid) {
|
||||
let pids;
|
||||
try {
|
||||
pids = readdirSync("/proc").filter((p) => /^\d+$/.test(p) && Number(p) !== process.pid);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const names = (arg) => dirs.some((d) => arg === d || arg.startsWith(`${d}/`));
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
const start = startTime(pid);
|
||||
const ids = /^Uid:\s+(\d+)\s+(\d+)\s/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"));
|
||||
if (!ids || Number(ids[1]) !== uid || Number(ids[2]) !== uid) continue;
|
||||
if (!readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").some(names)) continue;
|
||||
if (startTime(pid) !== start) continue;
|
||||
process.kill(Number(pid), "SIGKILL");
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// The provider variables never reach a fit run: no key is passed, since no model is called.
|
||||
const withoutProviders = (host) => Object.fromEntries(Object.entries(host ?? {}).filter(([k, v]) => typeof v === "string" && !isProviderVariable(k)));
|
||||
// The names a fit run's host part holds: sessionEnv's answer for the process's environment.
|
||||
export const fitNames = (host = process.env) => Object.keys(sessionEnv(withoutProviders(host), "fit")).sort();
|
||||
const fitKey = (found, { levels, bwrap, unshare, node, host }) => JSON.stringify([filesDigest(found), found.root, found.dest ?? null, found.view, bwrap, unshare, node, levels, fitNames(host)]);
|
||||
|
||||
// found: binary.mjs's answer ({ bin, label, root, dest, view, pkg }). levels: the thinking levels
|
||||
// the module applies. host: the environment of the process sessions launch from (the bus's own),
|
||||
// which a fit run's environment is built from as a session's is. bwrap and unshare: where those
|
||||
// tools are (tests pass stand-ins). Returns a promise of { ok: true, version, noMcp, digest, outer }
|
||||
// or { ok: false, message }. outer: { used: true } when the runs had unshare's outer layer, else
|
||||
// { used: false, why } with why naming unshare and how it failed (sandboxLayers below). A call
|
||||
// while a check with the same key runs gets that check's promise. A check that throws (a scratch directory it can't
|
||||
// make, say) can't tell, so it gives { ok: false, message } too and keeps nothing.
|
||||
export function piFit(found, { levels = [], bwrap = BWRAP, unshare = UNSHARE, node = process.execPath, host = process.env } = {}) {
|
||||
const who = (version) => `pi${version ? ` ${version}` : ""} (${found.label})`;
|
||||
let key;
|
||||
try {
|
||||
key = fitKey(found, { levels, bwrap, unshare, node, host });
|
||||
} catch {
|
||||
return Promise.resolve({ ok: false, message: `${who(null)} can't be checked: its files can't be read` });
|
||||
}
|
||||
if (passed.has(key)) return Promise.resolve(passed.get(key));
|
||||
if (running.has(key)) return running.get(key);
|
||||
const job = (async () => {
|
||||
try {
|
||||
sweepScratch();
|
||||
// The sandbox's own error text can name a host path, so the line keeps only what failed.
|
||||
const layers = await sandboxLayers({ bwrap, unshare, node });
|
||||
if (layers.problem) return { ok: false, message: `${who(null)} can't be checked: ${layers.problem}` };
|
||||
const result = await check(found, { levels, bwrap, unshare: layers.outer, node, who, digest: JSON.parse(key)[0], host });
|
||||
if (!result.ok) return result;
|
||||
const passing = { ...result, outer: layers.outer ? { used: true } : { used: false, why: layers.why } };
|
||||
passed.set(key, passing);
|
||||
return passing;
|
||||
} catch {
|
||||
// #1873 re-check 8: refused as a fit that failed. The error's text can name a host path, so
|
||||
// the line keeps none of it.
|
||||
return { ok: false, message: `${who(null)} can't be checked: the check could not run` };
|
||||
}
|
||||
})().finally(() => { if (running.get(key) === job) running.delete(key); });
|
||||
running.set(key, job);
|
||||
return job;
|
||||
}
|
||||
|
||||
// The passed check for found as piFit would key it now, or null: none passed, or its files can't
|
||||
// be read. Nothing is run.
|
||||
export function fitVerdict(found, { levels = [], bwrap = BWRAP, unshare = UNSHARE, node = process.execPath, host = process.env } = {}) {
|
||||
try {
|
||||
return passed.get(fitKey(found, { levels, bwrap, unshare, node, host })) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function check(found, { levels, bwrap, unshare, node, who, digest, host }) {
|
||||
// At most FIT_CONCURRENCY runs at once, started in the order they are asked for. stop kills the
|
||||
// runs still going and keeps queued ones from starting; the check waits for every run it began,
|
||||
// so no scratch directory or child outlives it.
|
||||
const stop = new AbortController();
|
||||
const begun = [];
|
||||
let active = 0;
|
||||
const waiting = [];
|
||||
const slot = () => active < FIT_CONCURRENCY ? (active++, Promise.resolve()) : new Promise((resolve) => waiting.push(resolve));
|
||||
const free = () => { const next = waiting.shift(); if (next) next(); else active--; };
|
||||
// args: the arguments, or a function of the run's scratch directory that returns them (it may
|
||||
// plant more first). The answer is read before the scratch directory goes: the rpc answers,
|
||||
// whether each -e extension loaded, what the first one saw at session_start (the system prompt,
|
||||
// the command names, the session id), and the planted sources that showed, through the rpc
|
||||
// get_commands answer or through the -e extension's command list (listed: through that alone).
|
||||
// shape: a session-shaped run's branches, which set its tools, thinking level and monitor
|
||||
// variables as a session's would. A run that stop kept from starting gives null.
|
||||
const once = async (args, input, { timeout, noMcp, shape }) => {
|
||||
await slot();
|
||||
try {
|
||||
if (stop.signal.aborted) return null;
|
||||
const scratch = mkdtempSync(join(tmpdir(), scratchPrefix()));
|
||||
let ran = null;
|
||||
try {
|
||||
plant(scratch);
|
||||
const env = fitEnv(scratch, { view: found.view, noMcp, shape, host });
|
||||
const r = ran = await runIn(found, { bwrap, unshare, node, scratch, env, args: typeof args === "function" ? args(scratch) : args, input, timeout, signal: stop.signal });
|
||||
const answer = answered(r.stdout);
|
||||
const start = started(scratch);
|
||||
const listed = start?.commands ?? [];
|
||||
return { ...r, answer, explicit: marked(scratch, EXPLICIT), second: marked(scratch, SECOND), prompt: start?.prompt ?? null, session: start?.session ?? null, listed: named(listed), skills: GIVEN_SKILLS.every((n) => names(listed, n)), seen: seen(scratch, [...(answer.commands ?? []), ...listed], start) };
|
||||
} finally {
|
||||
// #1873 re-check 10: a run this check killed (a timeout, or stop) may have had bwrap in its
|
||||
// setup, and without unshare's outer layer bwrap's child then waits for good. The run is
|
||||
// over, so whatever still names its directory is left from it.
|
||||
if (ran?.stopped) stopNaming([scratch], process.getuid());
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
} finally {
|
||||
free();
|
||||
}
|
||||
};
|
||||
const run = (args, input = "", { timeout = RUN_TIMEOUT, noMcp = false, shape = null } = {}) => {
|
||||
const p = once(args, input, { timeout, noMcp, shape });
|
||||
// Judged in order, a later run can fail before an earlier one is awaited: this keeps that
|
||||
// failure from counting as unhandled. Awaiting p still throws it.
|
||||
p.catch(() => {});
|
||||
begun.push(p);
|
||||
return p;
|
||||
};
|
||||
try {
|
||||
return await judge(found, { levels, who, digest, run });
|
||||
} finally {
|
||||
stop.abort();
|
||||
await Promise.allSettled(begun);
|
||||
}
|
||||
}
|
||||
|
||||
async function judge(found, { levels, who, digest, run }) {
|
||||
const helped = run(["--help"]);
|
||||
const versioned = run(["--version"], "", { timeout: VERSION_TIMEOUT });
|
||||
const help = await helped;
|
||||
const v = await versioned;
|
||||
const version = v.status === 0 ? versionLabel(v.stdout) : null;
|
||||
const refuse = (why) => ({ ok: false, message: `${who(version)} ${why}` });
|
||||
if (help.status !== 0) return refuse("can't be checked: --help failed");
|
||||
const lines = help.stdout.split("\n");
|
||||
const has = (flag) => lines.some((l) => optionsIn(l).includes(flag));
|
||||
const line = (flag) => lines.find((l) => optionsIn(l).includes(flag)) ?? "";
|
||||
const missing = FIT_FLAGS.filter((f) => !has(f));
|
||||
if (has("--mode") && !word(line("--mode"), "rpc")) missing.push("--mode rpc");
|
||||
if (has("--thinking")) for (const l of levels) if (!word(line("--thinking"), l)) missing.push(`--thinking ${l}`);
|
||||
if (missing.length) return refuse(`lacks ${missing.join(", ")}`);
|
||||
const noMcp = has("--no-mcp");
|
||||
|
||||
const ask = '{"id":"fit-state","type":"get_state"}\n{"id":"fit-commands","type":"get_commands"}\n';
|
||||
// Every run passes the same -e and --system-prompt, so the runs differ only by the seal flags.
|
||||
const given = (scratch) => ["-e", join(scratch, "explicit", "fit.ts"), "--system-prompt", join(scratch, "prompt.md")];
|
||||
const seal = [...SEAL, ...(noMcp ? ["--no-mcp"] : [])];
|
||||
const loaders = [...LOADERS, ...(noMcp ? [["--no-mcp", "MCP server"]] : [])];
|
||||
const without = (...flags) => seal.filter((f) => !flags.includes(f));
|
||||
const rpcRun = (flags) => run((s) => ["--mode", "rpc", ...flags, ...given(s)], ask, { noMcp });
|
||||
|
||||
// Every run is asked for now, in the order they are judged below; none depends on another.
|
||||
// The control keeps the seal flags no planted source tells apart (--offline, --no-themes,
|
||||
// --no-tools, --no-session), so one of those can't stand in for a loader flag either.
|
||||
const controlRun = rpcRun(without(...loaders.map(([f]) => f)));
|
||||
const rpcSealed = rpcRun(seal);
|
||||
const oneOut = loaders.map(([flag, kind]) => [flag, kind, rpcRun(without(flag))]);
|
||||
// A bus session's shapes, in -p as its turns run: --session-dir in place of --no-session, two -e
|
||||
// as a session passes, and each pair of the adapter's session branches in one run. A -c run gets
|
||||
// a stored session for the project first and must resume it, since -c with none starts afresh.
|
||||
const shaped = SESSION_RUNS.map((shape) => [shape, run((s) => {
|
||||
if (shape.cont) plantSession(s);
|
||||
return sessionShape({ noMcp, extensions: [join(s, "explicit", "fit.ts"), join(s, "explicit", "second.ts")], prompt: join(s, "prompt.md"), sessionDir: join(s, "sessions"), message: "fit check", ...shape });
|
||||
}, "", { noMcp, shape })]);
|
||||
// -p takes a message; offline with no key, pi stops before any model call. The adapter's -p argv
|
||||
// with MOSAIC_SKILLS: two --skill directories right after --no-skills, as the adapter puts them.
|
||||
const pRun = run((s) => workerShape({ noMcp, extensions: [join(s, "explicit", "fit.ts")], skills: GIVEN_SKILLS.map((n) => join(s, "given", n)), prompt: join(s, "prompt.md"), message: "fit check" }), "", { noMcp });
|
||||
// A missing -e file stops the start. pi 0.85.1 loads the -e files in order and still loads the
|
||||
// one after the missing one, then exits 1 before session_start, so only session_start tells.
|
||||
const missingRuns = [["rpc", ["--mode", "rpc"], ask], ["-p", ["-p"], ""]].map(([mode, args, input]) =>
|
||||
[mode, run((s) => [...args, ...seal, "-e", join(s, "missing", "extension.ts"), ...given(s), ...(mode === "-p" ? ["fit check"] : [])], input, { noMcp })]);
|
||||
|
||||
const control = await controlRun;
|
||||
if (control.stopped) return refuse(`can't be checked: the start without the seal flags ${control.stopped}`);
|
||||
if (!control.answer.state) return refuse("can't be checked: it didn't answer get_state");
|
||||
if (!control.answer.commands) return refuse("can't be checked: it didn't answer get_commands");
|
||||
if (!control.explicit || control.prompt === null) return refuse("can't be checked: its -e extension didn't see the system prompt without the seal flags");
|
||||
// A kind counts only through a source outside the project, except the trusted project files
|
||||
// themselves: a project source can wait on project trust, and then --no-approve alone would keep
|
||||
// it out of the sealed runs and hide a seal flag of its kind that the binary ignores.
|
||||
const shown = new Set(control.seen.filter((s) => s.kind === "trusted project file" || !s.source.startsWith("project ")).map((s) => s.kind));
|
||||
const unshown = KINDS.filter((k) => (k !== "MCP server" || noMcp) && !shown.has(k));
|
||||
if (unshown.length) return refuse(`can't be checked: it didn't load a planted ${unshown.join(", ")} without the seal flags`);
|
||||
// -p answers no get_commands, so the -p runs see skills and prompt templates only through the -e
|
||||
// extension's command list, which must show them here.
|
||||
const listed = new Set(control.listed.filter((s) => !s.source.startsWith("project ")).map((s) => s.kind));
|
||||
const unlisted = ["skill", "prompt template"].filter((k) => !listed.has(k));
|
||||
if (unlisted.length) return refuse(`can't be checked: its -e extension didn't list a planted ${unlisted.join(", ")} without the seal flags`);
|
||||
|
||||
const rpc = await rpcSealed;
|
||||
if (rpc.stopped) return refuse(`can't be checked: the start with the seal flags ${rpc.stopped}`);
|
||||
if (!rpc.answer.state) return refuse("can't be checked: it didn't answer get_state with the seal flags on");
|
||||
if (!rpc.answer.commands) return refuse("can't be checked: it didn't answer get_commands with the seal flags on");
|
||||
if (!rpc.explicit) return refuse("didn't load an -e extension with the seal flags on");
|
||||
if (rpc.prompt === null) return refuse("can't be checked: its -e extension didn't see the system prompt with the seal flags on");
|
||||
if (!rpc.prompt.includes(GIVEN)) return refuse("didn't use the --system-prompt file with the seal flags on");
|
||||
if (rpc.seen.length) return refuse(`loaded a planted ${rpc.seen.map((s) => s.source).join(", ")} with the seal flags on`);
|
||||
|
||||
// Each loader flag on its own: with every other seal flag on, its kind must show.
|
||||
for (const [flag, kind, pending] of oneOut) {
|
||||
const r = await pending;
|
||||
const but = `with every seal flag but ${flag}`;
|
||||
if (r.stopped) return refuse(`can't be checked: the start ${but} ${r.stopped}`);
|
||||
if (!r.answer.state || !r.answer.commands) return refuse(`can't be checked: it didn't answer get_state and get_commands ${but}`);
|
||||
if (r.prompt === null) return refuse(`can't be checked: its -e extension didn't see the system prompt ${but}`);
|
||||
if (!r.seen.some((s) => s.kind === kind)) return refuse(`can't be checked: it didn't load a planted ${kind} ${but}`);
|
||||
const others = r.seen.filter((s) => s.kind !== kind && !(flag === "--no-extensions" && !noMcp && s.kind === "MCP server"));
|
||||
if (others.length) return refuse(`loaded a planted ${others.map((s) => s.source).join(", ")} ${but}`);
|
||||
}
|
||||
|
||||
for (const [shape, pending] of shaped) {
|
||||
const r = await pending;
|
||||
const name = shapeName(shape);
|
||||
if (r.stopped) return refuse(`can't be checked: the start ${name} ${r.stopped}`);
|
||||
if (r.prompt === null) return refuse(`can't be checked: its -e extension didn't see the system prompt ${name}`);
|
||||
if (!r.explicit || !r.second) return refuse(`didn't load every -e extension ${name}`);
|
||||
if (!r.prompt.includes(GIVEN)) return refuse(`didn't use the --system-prompt file ${name}`);
|
||||
if (shape.cont && r.session !== PLANTED_SESSION) return refuse(`can't be checked: it didn't resume the planted session with -c ${name}`);
|
||||
if (r.seen.length) return refuse(`loaded a planted ${r.seen.map((x) => x.source).join(", ")} with the seal flags ${name}`);
|
||||
}
|
||||
|
||||
const p = await pRun;
|
||||
if (p.stopped) return refuse(`can't be checked: the start in a worker's shape ${p.stopped}`);
|
||||
if (p.prompt === null) return refuse("can't be checked: its -e extension didn't see the system prompt in a worker's shape");
|
||||
if (p.seen.length) return refuse(`loaded a planted ${p.seen.map((x) => x.source).join(", ")} in a worker's shape with --skill`);
|
||||
if (!p.skills) return refuse("didn't load every --skill directory with --no-skills on in a worker's shape");
|
||||
|
||||
for (const [mode, pending] of missingRuns) {
|
||||
const r = await pending;
|
||||
if (r.stopped) return refuse(`can't be checked: a ${mode} start with a missing -e extension ${r.stopped}`);
|
||||
if (r.status === 0 || r.answer.state || r.prompt !== null) return refuse("starts with a missing -e extension");
|
||||
}
|
||||
return { ok: true, version, noMcp, digest };
|
||||
}
|
||||
|
||||
// Whether bwrap runs here, as sandbox.mjs's sandboxProblem asks, but as child processes the caller
|
||||
// awaits: the system part, the network unshared, an empty environment, then /usr/bin/true. And,
|
||||
// once per check, whether unshare's outer layer runs (checkArgv in sandbox.mjs): first on its own,
|
||||
// then with bwrap inside it. Returns { problem } when the check can't run, naming the tool that
|
||||
// failed without its own text, else { outer, why }: outer is the unshare to pass checkArgv, or null
|
||||
// when the layer can't run here, and why then names unshare and how it failed. A missing,
|
||||
// too old or refused unshare drops only that layer and is no refusal: bwrap's sandbox is the same
|
||||
// either way. The probes run in a scratch directory of their own and name it on their command
|
||||
// line, so a probe process a killed owner leaves is one the next sweep finds.
|
||||
async function sandboxLayers({ bwrap, unshare, node }) {
|
||||
if (!existsSync(bwrap)) return { problem: "the sandbox (bwrap) is missing" };
|
||||
if (!existsSync(SETPRIV)) return { problem: "the sandbox's parent-death tool (setpriv) is missing" };
|
||||
const scratch = mkdtempSync(join(tmpdir(), scratchPrefix()));
|
||||
let stopped = false;
|
||||
try {
|
||||
const probe = async (argv) => {
|
||||
const r = await spawned(argv, { input: "", timeout: 10000, signal: new AbortController().signal });
|
||||
stopped ||= Boolean(r.stopped);
|
||||
return r.status === 0;
|
||||
};
|
||||
const sandboxed = (outer) => checkArgv([{ kind: "ro", src: scratch }], ["/usr/bin/true"], { chdir: scratch, node, bwrap, unshare: outer });
|
||||
let why = "unshare is missing";
|
||||
if (existsSync(unshare)) {
|
||||
if (!await probe(outerArgv(["/usr/bin/true", scratch], { unshare }))) why = "unshare failed";
|
||||
else if (await probe(sandboxed(unshare))) return { outer: unshare, why: null };
|
||||
else why = "unshare failed with bwrap inside it";
|
||||
}
|
||||
if (!await probe(sandboxed(null))) return { problem: "the sandbox (bwrap) failed" };
|
||||
return { outer: null, why };
|
||||
} finally {
|
||||
// As for a run (once, in piFit): a probe killed at its timeout may leave what names its directory.
|
||||
if (stopped) stopNaming([scratch], process.getuid());
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// The binary, inside the sandbox: the system part, the found package where a session sees it, the
|
||||
// scratch directory read-write, and its tmp/ as /tmp, as a session has it. The environment is
|
||||
// fitEnv's. The binary starts through /bin/sh, as the adapter starts it, so it also gets the
|
||||
// variables the shell sets. The run is a child process the caller awaits; nothing here blocks.
|
||||
// stopped: why the run was killed ("timed out", "printed more than 4 MB", "was stopped"), or null.
|
||||
function runIn(found, { bwrap, unshare, node, scratch, env, args, input, timeout, signal }) {
|
||||
const list = [
|
||||
{ kind: "ro", src: found.root, ...(found.dest ? { dest: found.dest } : {}) },
|
||||
{ kind: "rw", src: scratch },
|
||||
{ kind: "rw", src: join(scratch, "tmp"), dest: "/tmp" },
|
||||
];
|
||||
return spawned(checkArgv(list, ["/bin/sh", "-c", 'exec "$0" "$@"', found.view, ...args], { env, chdir: join(scratch, "project"), node, bwrap, unshare }), { input, timeout, signal });
|
||||
}
|
||||
|
||||
// One child process with an empty environment, awaited: its exit status, its stdout, and why it was
|
||||
// killed, or null. It settles PIPE_GRACE after the child exits or is killed even if its pipes stay
|
||||
// open: a process left behind can hold them (a kill of bwrap's outer process while its child still
|
||||
// sets up leaves that child waiting until the pid namespace checkArgv makes is killed, or, without
|
||||
// that layer, until the next check's sweep), and no wait here is unbounded.
|
||||
function spawned(argv, { input, timeout, signal }) {
|
||||
return new Promise((resolve) => {
|
||||
const out = [];
|
||||
const size = { stdout: 0, stderr: 0 };
|
||||
let stopped = null;
|
||||
let done = false;
|
||||
let child;
|
||||
let timer = null;
|
||||
let grace = null;
|
||||
let exited = null;
|
||||
const finish = (status, sig) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(grace);
|
||||
child?.stdout?.destroy();
|
||||
child?.stderr?.destroy();
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (!stopped && sig === "SIGKILL") stopped = "timed out";
|
||||
resolve({ status, stdout: Buffer.concat(out).toString("utf8"), stopped });
|
||||
};
|
||||
const settleSoon = () => { if (!grace) grace = setTimeout(() => finish(exited?.status ?? null, exited?.sig ?? "SIGKILL"), PIPE_GRACE); };
|
||||
const kill = (why) => {
|
||||
if (!stopped) stopped = why;
|
||||
try { child?.kill("SIGKILL"); } catch {}
|
||||
settleSoon();
|
||||
};
|
||||
const onAbort = () => kill("was stopped");
|
||||
try {
|
||||
child = spawn(argv[0], argv.slice(1), { env: {}, stdio: ["pipe", "pipe", "pipe"] });
|
||||
} catch {
|
||||
finish(null, null);
|
||||
return;
|
||||
}
|
||||
timer = setTimeout(() => kill("timed out"), timeout);
|
||||
if (signal.aborted) onAbort();
|
||||
else signal.addEventListener("abort", onAbort, { once: true });
|
||||
const count = (stream) => (chunk) => {
|
||||
size[stream] += chunk.length;
|
||||
if (size[stream] > OUTPUT_MAX) kill(`printed more than ${OUTPUT_MAX / 1024 / 1024} MB`);
|
||||
else if (stream === "stdout") out.push(chunk);
|
||||
};
|
||||
child.stdout.on("data", count("stdout"));
|
||||
child.stderr.on("data", count("stderr"));
|
||||
child.stdin.on("error", () => {});
|
||||
child.on("error", () => finish(null, null));
|
||||
child.on("exit", (status, sig) => { exited = { status, sig }; settleSoon(); });
|
||||
child.on("close", (status, sig) => finish(status, sig));
|
||||
child.stdin.end(input);
|
||||
});
|
||||
}
|
||||
|
||||
// A fit run's environment: what a bus session's pi gets, built the same way from host, the
|
||||
// environment of the process sessions launch from (the bus's own). The launcher passes host's
|
||||
// ENV_ALLOW names that are set through sessionEnv (less the provider variables here, since no key
|
||||
// is passed: no model is called), with host's PATH behind the repository's .bin; the sandbox sets
|
||||
// sessionSetenv's (HOME is the scratch home, so pi's agent directory is $HOME/.pi/agent); the
|
||||
// runner adds adapterEnv's with the pi module's harnessEnv, and MOSAIC_REQUEST for each turn. No
|
||||
// name is added that a session in that process would lack: a bus started by its unit has no TERM,
|
||||
// TZ or LC_ALL, and then no fit run has them either. shape: a session-shaped run's branches (its
|
||||
// tool list, thinking level and --mode json, which a proxy session's first turn takes with the
|
||||
// model event monitor's variables), else none: no tools, no thinking, one -e. noMcp: --help lists
|
||||
// --no-mcp. pi-fit.test.mjs fails when these names, or the values the code sets, differ from a bus
|
||||
// session's, for a login shell's host and a unit's.
|
||||
export function fitEnv(scratch, { view, noMcp = false, shape = null, host = process.env }) {
|
||||
const runner = { ...sessionEnv(withoutProviders(host), "fit"), ...sessionSetenv(scratch, { business: "fit", role: "fit" }) };
|
||||
const { tools = "", thinking = "", json = false } = shape ?? {};
|
||||
const session = { provider: SESSION_SHAPE.provider, model: SESSION_SHAPE.model, thinking };
|
||||
const extensions = [join(scratch, "explicit", "fit.ts"), ...(shape ? [join(scratch, "explicit", "second.ts")] : [])];
|
||||
const env = adapterEnv({
|
||||
...session,
|
||||
bundle: { prompt: join(scratch, "prompt.md"), policy: join(scratch, "policy.json"), tools: join(scratch, "tools.json") },
|
||||
workspace: join(scratch, "project"), sessionDir: join(scratch, "sessions"), toolSocket: join(scratch, "tools.sock"), turnMarker: join(scratch, "turn"),
|
||||
harnessEnv: harnessEnv({ bin: view, noMcp, tools: tools ? tools.split(",") : [], extensions, session }),
|
||||
runDir: scratch, proxyFirstTurn: json,
|
||||
}, runner);
|
||||
return { ...env, MOSAIC_REQUEST: "fit check" };
|
||||
}
|
||||
|
||||
// The options one help line lists in its option column: a line that starts with "-" (after its
|
||||
// indent), up to the first run of two spaces or a tab, split at commas; the first word of each
|
||||
// part. " --extension, -e <path> Load an extension" lists --extension and -e. A flag named in a
|
||||
// sentence is not listed.
|
||||
function optionsIn(line) {
|
||||
const t = line.trim();
|
||||
if (!t.startsWith("-")) return [];
|
||||
return t.split(/ {2,}|\t/)[0].split(",").map((part) => part.trim().split(/[ =<[]/)[0]).filter((o) => /^--?[A-Za-z0-9]/.test(o));
|
||||
}
|
||||
const word = (line, w) => line.split(/[^A-Za-z0-9-]+/).includes(w);
|
||||
|
||||
// The version a refusal line may carry: a version-shaped first line, else none. Anything else the
|
||||
// binary prints stays out of the line.
|
||||
function versionLabel(stdout) {
|
||||
const first = String(stdout).split("\n")[0].trim();
|
||||
return /^v?[0-9]+(\.[0-9]+){0,3}([-+][0-9A-Za-z.-]{1,32})?$/.test(first) ? first : null;
|
||||
}
|
||||
|
||||
// The rpc answers in the output: whether get_state succeeded, and the command names get_commands
|
||||
// listed, or null when it didn't answer with a { commands: [...] } list.
|
||||
function answered(stdout) {
|
||||
let state = false;
|
||||
let commands = null;
|
||||
for (const l of String(stdout).split("\n")) {
|
||||
let m;
|
||||
try { m = JSON.parse(l); } catch { continue; }
|
||||
if (!m || m.type !== "response" || m.success !== true) continue;
|
||||
if (m.id === "fit-state" && m.command === "get_state" && m.data && typeof m.data === "object") state = true;
|
||||
if (m.id === "fit-commands" && m.command === "get_commands" && Array.isArray(m.data?.commands)) {
|
||||
commands = m.data.commands.filter((c) => typeof c?.name === "string").map((c) => c.name);
|
||||
}
|
||||
}
|
||||
return { state, commands };
|
||||
}
|
||||
|
||||
// The planted sources, each with the kind the control must show. Each extension and each MCP
|
||||
// server touches its own marker; each skill and prompt template has a name get_commands lists;
|
||||
// each context and system prompt file holds a word the -e extension's view of the system prompt
|
||||
// shows. "user" sources sit in the agent directory, $HOME/.pi/agent: no fit run sets
|
||||
// PI_CODING_AGENT_DIR, as no bus session does. "settings" sources are listed by a settings.json;
|
||||
// "package" sources come from a local package a settings.json lists. "parent" is a directory above
|
||||
// the project.
|
||||
const KINDS = ["extension", "MCP server", "skill", "prompt template", "context file", "trusted project file"];
|
||||
const MARKED = {
|
||||
"user extension": "extension", "user settings extension": "extension", "user package extension": "extension",
|
||||
"project extension": "extension", "project settings extension": "extension", "project package extension": "extension",
|
||||
"user mcp.json": "MCP server", "project mcp.json": "MCP server", "project .mcp.json": "MCP server",
|
||||
};
|
||||
const NAMED = {
|
||||
"fit-user-skill": ["user skill", "skill"], "fit-user-set-skill": ["user settings skill", "skill"], "fit-user-pkg-skill": ["user package skill", "skill"],
|
||||
"fit-project-skill": ["project skill", "skill"], "fit-project-set-skill": ["project settings skill", "skill"],
|
||||
"fit-project-pkg-skill": ["project package skill", "skill"], "fit-agents-skill": ["project .agents skill", "skill"], "fit-home-skill": ["home .agents skill", "skill"],
|
||||
"fit-user-prompt": ["user prompt template", "prompt template"], "fit-user-set-prompt": ["user settings prompt template", "prompt template"],
|
||||
"fit-user-pkg-prompt": ["user package prompt template", "prompt template"],
|
||||
"fit-project-prompt": ["project prompt template", "prompt template"], "fit-project-set-prompt": ["project settings prompt template", "prompt template"],
|
||||
"fit-project-pkg-prompt": ["project package prompt template", "prompt template"],
|
||||
};
|
||||
// Planted file (under the scratch directory), the word it holds, the source, the kind. A project
|
||||
// SYSTEM.md or APPEND_SYSTEM.md loads only in a trusted project: the saved trust makes it trusted,
|
||||
// and only --no-approve undoes that with the seal flags on.
|
||||
const TEXTS = [
|
||||
["home/.pi/agent/SYSTEM.md", "FITUSERSYSTEM", "user SYSTEM.md", "context file"],
|
||||
["home/.pi/agent/AGENTS.md", "FITUSERAGENTS", "user AGENTS.md", "context file"],
|
||||
["project/.pi/SYSTEM.md", "FITPROJECTSYSTEM", "project SYSTEM.md", "trusted project file"],
|
||||
["project/.pi/APPEND_SYSTEM.md", "FITPROJECTAPPEND", "project APPEND_SYSTEM.md", "trusted project file"],
|
||||
["project/AGENTS.md", "FITPROJECTAGENTS", "project AGENTS.md", "context file"],
|
||||
["project/CLAUDE.md", "FITPROJECTCLAUDE", "project CLAUDE.md", "context file"],
|
||||
["CLAUDE.md", "FITPARENTCLAUDE", "parent CLAUDE.md", "context file"],
|
||||
];
|
||||
// The --system-prompt file's word, which the sealed runs must show.
|
||||
const GIVEN = "FITGIVENPROMPT";
|
||||
// The -e extension every run passes, which must load, and the second one the session-shaped runs
|
||||
// pass after it.
|
||||
const EXPLICIT = "explicit extension";
|
||||
const SECOND = "second explicit extension";
|
||||
// The skills the worker-shaped run passes with --skill (scratch/given/<name>), outside every place
|
||||
// pi looks for skills, so they show only through --skill. Not planted ambient: not in NAMED.
|
||||
const GIVEN_SKILLS = ["fit-given-skill", "fit-second-given-skill"];
|
||||
// The id of the session a -c run must resume.
|
||||
const PLANTED_SESSION = "fit-planted-session";
|
||||
const markerName = (source) => source.replace(/[^a-z]/g, "-");
|
||||
const marked = (scratch, source) => { try { return readdirSync(join(scratch, "marks")).includes(markerName(source)); } catch { return false; } };
|
||||
// What the -e extension saw at session_start ({ prompt, commands, session }), or null when it wrote
|
||||
// nothing that parses into that shape.
|
||||
function started(scratch) {
|
||||
let m;
|
||||
try { m = JSON.parse(readFileSync(join(scratch, "marks", "start.json"), "utf8")); } catch { return null; }
|
||||
if (!m || typeof m.prompt !== "string" || !Array.isArray(m.commands)) return null;
|
||||
return { prompt: m.prompt, commands: m.commands.filter((c) => typeof c === "string"), session: typeof m.session === "string" ? m.session : null };
|
||||
}
|
||||
// Whether command names hold name, bare or after a prefix such as "skill:".
|
||||
const names = (commands, name) => commands.some((c) => c === name || c.endsWith(`:${name}`));
|
||||
// The planted skills and prompt templates among command names, as { source, kind }.
|
||||
const named = (commands) => Object.entries(NAMED).filter(([name]) => names(commands, name)).map(([, [source, kind]]) => ({ source, kind }));
|
||||
|
||||
function plant(scratch) {
|
||||
const marks = join(scratch, "marks");
|
||||
const put = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };
|
||||
const ext = (source) => `import { writeFileSync } from "node:fs";\nexport default function (): void { writeFileSync(${JSON.stringify(join(marks, markerName(source)))}, ""); }\n`;
|
||||
const mcp = (source) => JSON.stringify({ mcpServers: { fit: { command: "/bin/sh", args: ["-c", `: > ${join(marks, markerName(source))}`] } } });
|
||||
const skill = (name) => `---\nname: ${name}\ndescription: a planted skill\n---\nA planted skill.\n`;
|
||||
const prompt = "A planted prompt template.\n";
|
||||
const agent = join(scratch, "home", ".pi", "agent");
|
||||
const project = join(scratch, "project");
|
||||
mkdirSync(marks, { recursive: true });
|
||||
mkdirSync(join(scratch, "tmp"), { recursive: true });
|
||||
mkdirSync(project, { recursive: true });
|
||||
// The session-shaped runs' --session-dir, made as the adapter makes it.
|
||||
mkdirSync(join(scratch, "sessions"), { recursive: true });
|
||||
// Each settings.json lists an extension, a skill directory, a prompt template and a local
|
||||
// package holding one of each.
|
||||
const listed = (who) => {
|
||||
const dir = join(scratch, "listed", who);
|
||||
put(join(dir, "fit.ts"), ext(`${who} settings extension`));
|
||||
put(join(dir, `fit-${who}-set-skill`, "SKILL.md"), skill(`fit-${who}-set-skill`));
|
||||
put(join(dir, `fit-${who}-set-prompt.md`), prompt);
|
||||
const pkg = join(dir, "package");
|
||||
put(join(pkg, "package.json"), JSON.stringify({ name: `fit-${who}-package`, version: "1.0.0" }));
|
||||
put(join(pkg, "extensions", "fit.ts"), ext(`${who} package extension`));
|
||||
put(join(pkg, "skills", `fit-${who}-pkg-skill`, "SKILL.md"), skill(`fit-${who}-pkg-skill`));
|
||||
put(join(pkg, "prompts", `fit-${who}-pkg-prompt.md`), prompt);
|
||||
return { extensions: [join(dir, "fit.ts")], skills: [join(dir, `fit-${who}-set-skill`)], prompts: [join(dir, `fit-${who}-set-prompt.md`)], packages: [pkg] };
|
||||
};
|
||||
// A saved trust for the project, so the control loads its trust-gated files without --approve.
|
||||
put(join(agent, "settings.json"), JSON.stringify({ ...listed("user"), defaultProjectTrust: "always" }));
|
||||
put(join(agent, "trust.json"), JSON.stringify({ [realpathSync(project)]: true }));
|
||||
put(join(agent, "extensions", "fit.ts"), ext("user extension"));
|
||||
put(join(agent, "mcp.json"), mcp("user mcp.json"));
|
||||
put(join(agent, "skills", "fit-user-skill", "SKILL.md"), skill("fit-user-skill"));
|
||||
put(join(agent, "prompts", "fit-user-prompt.md"), prompt);
|
||||
put(join(project, ".pi", "settings.json"), JSON.stringify(listed("project")));
|
||||
put(join(project, ".pi", "extensions", "fit.ts"), ext("project extension"));
|
||||
put(join(project, ".pi", "mcp.json"), mcp("project mcp.json"));
|
||||
put(join(project, ".mcp.json"), mcp("project .mcp.json"));
|
||||
put(join(project, ".pi", "skills", "fit-project-skill", "SKILL.md"), skill("fit-project-skill"));
|
||||
put(join(project, ".agents", "skills", "fit-agents-skill", "SKILL.md"), skill("fit-agents-skill"));
|
||||
put(join(project, ".pi", "prompts", "fit-project-prompt.md"), prompt);
|
||||
put(join(scratch, "home", ".agents", "skills", "fit-home-skill", "SKILL.md"), skill("fit-home-skill"));
|
||||
for (const n of GIVEN_SKILLS) put(join(scratch, "given", n, "SKILL.md"), skill(n));
|
||||
for (const [file, text] of TEXTS) put(join(scratch, file), `${text}\n`);
|
||||
put(join(scratch, "explicit", "fit.ts"), `import { writeFileSync } from "node:fs";\nexport default function (pi: any): void {\n writeFileSync(${JSON.stringify(join(marks, markerName(EXPLICIT)))}, "");\n pi.on("session_start", (_event: any, ctx: any) => { writeFileSync(${JSON.stringify(join(marks, "start.json"))}, JSON.stringify({ prompt: ctx.getSystemPrompt(), commands: pi.getCommands().map((c: any) => c.name), session: ctx.sessionManager.getSessionId() })); });\n}\n`);
|
||||
put(join(scratch, "explicit", "second.ts"), ext(SECOND));
|
||||
put(join(scratch, "prompt.md"), `${GIVEN}\n`);
|
||||
}
|
||||
|
||||
// A stored session for the project, as pi 0.85.1 writes one: a header whose cwd is the project's
|
||||
// real path (pi's -c takes only a session for its own cwd) and one user message.
|
||||
function plantSession(scratch) {
|
||||
const at = new Date().toISOString();
|
||||
writeFileSync(join(scratch, "sessions", `${PLANTED_SESSION}.jsonl`), [
|
||||
{ type: "session", version: 3, id: PLANTED_SESSION, timestamp: at, cwd: realpathSync(join(scratch, "project")) },
|
||||
{ type: "message", id: "f17e0001", parentId: null, timestamp: at, message: { role: "user", content: [{ type: "text", text: "an earlier turn" }], timestamp: Date.now() } },
|
||||
].map((e) => `${JSON.stringify(e)}\n`).join(""));
|
||||
}
|
||||
|
||||
// The planted sources a run loaded, as { source, kind }: markers present, planted names among the
|
||||
// command names, and planted words in the system prompt the -e extension saw.
|
||||
function seen(scratch, commands, start) {
|
||||
let marks = [];
|
||||
try { marks = readdirSync(join(scratch, "marks")); } catch { marks = []; }
|
||||
const out = Object.entries(MARKED).filter(([s]) => marks.includes(markerName(s))).map(([source, kind]) => ({ source, kind }));
|
||||
out.push(...named(commands));
|
||||
const text = start?.prompt ?? "";
|
||||
for (const [, word, source, kind] of TEXTS) if (text.includes(word)) out.push({ source, kind });
|
||||
return out;
|
||||
}
|
||||
|
||||
// sha256 over the sorted (path, sha256) list of the package's package.json, every regular file
|
||||
// under dist/bundle/ (design section 4), every regular file in the directory tree that holds the
|
||||
// binary's real file, so a bin outside dist/bundle/ can't import a file the digest skips, and npm's
|
||||
// lock files for a copy mounted with its node_modules. A symlink there is read through.
|
||||
function filesDigest(found) {
|
||||
const pkg = found.pkg;
|
||||
const bin = realpathSync(found.bin);
|
||||
const files = new Set([join(pkg, "package.json"), bin]);
|
||||
const walk = (dir) => {
|
||||
let entries;
|
||||
try { entries = readdirSync(dir, { withFileTypes: true }); } catch (e) { if (e.code === "ENOENT") return; throw e; }
|
||||
for (const e of entries) {
|
||||
const p = join(dir, e.name);
|
||||
if (e.isDirectory()) walk(p);
|
||||
else if (e.isFile() || (e.isSymbolicLink() && lstatSync(realpathSync(p)).isFile())) files.add(p);
|
||||
if (files.size > DIGEST_FILES_MAX) throw new Error("too many files");
|
||||
}
|
||||
};
|
||||
walk(join(pkg, "dist", "bundle"));
|
||||
const binDir = dirname(bin);
|
||||
if (binDir !== pkg && binDir.startsWith(`${pkg}/`)) walk(binDir);
|
||||
// A copy mounted with the node_modules it sits in imports packages beside it: npm's lock files
|
||||
// there stand for them.
|
||||
if (found.root !== pkg) for (const f of [join(found.root, ".package-lock.json"), join(dirname(found.root), "package-lock.json")]) {
|
||||
try { lstatSync(f); } catch (e) { if (e.code === "ENOENT") continue; throw e; }
|
||||
files.add(f);
|
||||
}
|
||||
const h = createHash("sha256");
|
||||
for (const f of [...files].sort()) {
|
||||
h.update(relative(pkg, f)).update("\0").update(createHash("sha256").update(readFileSync(f)).digest("hex")).update("\n");
|
||||
}
|
||||
return h.digest("hex");
|
||||
}
|
||||
@@ -41,7 +41,7 @@ import { createServer, connect } from "node:net";
|
||||
import { basename, join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
import { LENGTH_FAILURE_NOTICE_PREFIX } from "./failure-notice.mjs";
|
||||
import { LENGTH_FAILURE_NOTICE_PREFIX, failureBody, secretValues, turnCause } from "./failure-notice.mjs";
|
||||
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
|
||||
import { firstOutputMarker, firstTurnMarker } from './first-output.mjs';
|
||||
import { GUARD_CODES, FIXED_TEXTS } from "../../library/src/reply-protocol.mjs";
|
||||
@@ -508,7 +508,12 @@ function runTurn({ session, request, n, env, onChild }) {
|
||||
const missing = missingCommand(stderrTail(errPath));
|
||||
return resolve({ ok: false, reason: `adapter exited 127${missing ? ` (command not found: ${missing})` : ""}` });
|
||||
}
|
||||
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
|
||||
if (signal) return resolve({ ok: false, reason: `adapter killed by ${signal}` });
|
||||
if (code !== 0) {
|
||||
// #1873 chat-fail F1: an adapter that ends on an error result prints it on stdout.
|
||||
const cause = turnCause(out, secretValues(env));
|
||||
return resolve({ ok: false, reason: `adapter exited ${code}`, ...(cause ? { cause } : {}) });
|
||||
}
|
||||
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
|
||||
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
|
||||
resolve({ ok: true, text: out.trim() });
|
||||
@@ -801,11 +806,11 @@ export async function main(runDir, { stdin = process.stdin, env = process.env, l
|
||||
catch (e) { log(`runner: failure record for ${m.id} failed: ${e.code ?? e.message}`); if (ended(e, false)) break loop; }
|
||||
continue;
|
||||
}
|
||||
if (!turn.ok) log(`runner: turn ${n} for message ${m.id} failed: ${turn.reason}`);
|
||||
if (!turn.ok) log(`runner: turn ${n} for message ${m.id} failed: ${turn.reason}${turn.cause ? ` (${turn.cause})` : ""}`);
|
||||
try {
|
||||
if (!isLengthFailureNotice(m) && m.class !== "RESULT" && (m.class === "REQUEST" || ["human", "tester", "user"].includes(m.from_role) || m.in_reply_to_class !== "RESULT")) {
|
||||
if (!library) {
|
||||
const body = turn.ok ? turn.text || "(the session gave no answer)" : `The turn failed: ${turn.reason}`;
|
||||
const body = turn.ok ? turn.text || "(the session gave no answer)" : failureBody(turn);
|
||||
await client.call("message.send", { to: m.from_role, body: clip(body) + unslop.note(), class: "RESULT", in_reply_to: m.id });
|
||||
unslop.sent();
|
||||
} else {
|
||||
@@ -858,7 +863,7 @@ export async function main(runDir, { stdin = process.stdin, env = process.env, l
|
||||
await client.call("message.read", { id: m.id });
|
||||
continue;
|
||||
}
|
||||
if (!retry.ok) log(`runner: retry turn ${n} for message ${m.id} failed: ${retry.reason}`);
|
||||
if (!retry.ok) log(`runner: retry turn ${n} for message ${m.id} failed: ${retry.reason}${retry.cause ? ` (${retry.cause})` : ""}`);
|
||||
try { await send(retry); }
|
||||
catch (again) {
|
||||
if (!GUARD_CODES.includes(again.code) && again.code !== "request-too-large") throw again;
|
||||
|
||||
@@ -4,7 +4,8 @@ import { createHash } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { BundleError, buildBundle, sessionModel, SOURCES } from "../src/bundle.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from "./helpers.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch, harnessReady } from "./helpers.mjs";
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
import { decide } from "../src/gate.mjs";
|
||||
import { resolveInstance, validateBusinessDocument } from "../../organization/src/index.mjs";
|
||||
import { businessDoc, REPO_ROLES, systemFor } from "../../organization/tests/helpers.mjs";
|
||||
|
||||
@@ -205,3 +205,14 @@ test('a library continuation that succeeds sends the cited RESULT once', async t
|
||||
assert.equal(f.count(),2);
|
||||
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='coder'").n,1);
|
||||
});
|
||||
|
||||
// #1873 chat-fail review round 1: a failed citation retry logs its plain cause, as the first turn does.
|
||||
test('a failed citation retry logs the plain cause of the failure', async t => {
|
||||
let sends = 0;
|
||||
const f = await setup(t, commit => [{ text: citedBody([fixtureCite(commit)]) }, { text: 'Claude AI usage limit reached', exitCode: 1 }], {
|
||||
guard: async () => { if (sends++ === 0) throw new GuardError('citation-unavailable', 'The library is busy.'); return null; },
|
||||
});
|
||||
await f.call(f.human, 'message.send', { to: 'coder', body: 'Fixture question.', class: 'REQUEST' });
|
||||
await until(() => /runner: retry turn \d+ for message \S+ failed: /.test(f.log()));
|
||||
assert.match(f.log(), /runner: retry turn \d+ for message \S+ failed: adapter exited 1 \(the model account is out of usage/);
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { fixtureCacheEnv } from '../../../scripts/testing/lane-fixtures.mjs';
|
||||
// #1873 harness-matrix: claude-code runs a proxy model that is not a Claude model. The host's claude
|
||||
// CLI runs through adapters/claude with the bundle and env a z.ai or codex selection gives, against a
|
||||
// local stand-in for the proxy's Anthropic-format route. The stand-in records the path, the model
|
||||
// name claude sends and the hash of the key it carries. Scratch CLAUDE_CONFIG_DIR and HOME, a fixture
|
||||
// key, nonessential traffic off: nothing reaches a real model or account. Whether the real proxy
|
||||
// turns that request into a z.ai or codex call is proved only on the dev instance.
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createServer as createHttp } from 'node:http';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { mkdirSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { buildBundle, checkedTransport } from '../src/bundle.mjs';
|
||||
import { adapterEnv } from '../src/runner.mjs';
|
||||
import { fakeToolSocket, HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
|
||||
import * as cliproxy from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
const ADAPTER = join(REPO, 'adapters', 'claude', 'adapter.sh');
|
||||
const which = spawnSync('sh', ['-c', 'command -v claude'], { encoding: 'utf8' });
|
||||
const CLAUDE = which.status === 0 ? which.stdout.trim() : null;
|
||||
const skip = CLAUDE ? false : 'claude is not on PATH';
|
||||
const sha = (s) => createHash('sha256').update(s).digest('hex');
|
||||
|
||||
// The proxy's Anthropic-format route, as a stand-in: every /v1/messages answers with one text block.
|
||||
async function standIn(t, text) {
|
||||
const seen = [];
|
||||
const server = createHttp((req, res) => {
|
||||
let raw = '';
|
||||
req.on('data', (c) => (raw += c));
|
||||
req.on('end', () => {
|
||||
const auth = String(req.headers.authorization ?? '').replace(/^Bearer /, '');
|
||||
const apiKey = String(req.headers['x-api-key'] ?? '');
|
||||
if (req.method !== 'POST' || !/^\/v1\/messages(\?|$)/.test(req.url)) {
|
||||
seen.push({ path: req.url, method: req.method, authSha: auth ? sha(auth) : null, apiKeySha: apiKey ? sha(apiKey) : null });
|
||||
res.writeHead(req.url.includes('count_tokens') ? 200 : 404, { 'content-type': 'application/json' });
|
||||
return res.end(JSON.stringify(req.url.includes('count_tokens') ? { input_tokens: 10 } : { type: 'error', error: { type: 'not_found_error', message: 'stand-in' } }));
|
||||
}
|
||||
const body = JSON.parse(raw || '{}');
|
||||
seen.push({ path: req.url.split('?')[0], method: req.method, model: body.model, authSha: auth ? sha(auth) : null, apiKeySha: apiKey ? sha(apiKey) : null });
|
||||
const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`);
|
||||
if (!body.stream) {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
return res.end(JSON.stringify({ id: 'msg_si', type: 'message', role: 'assistant', model: body.model, content: [{ type: 'text', text }], stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 10, output_tokens: 5 } }));
|
||||
}
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
||||
send('message_start', { message: { id: 'msg_si', type: 'message', role: 'assistant', model: body.model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } } });
|
||||
send('content_block_start', { index: 0, content_block: { type: 'text', text: '' } });
|
||||
send('content_block_delta', { index: 0, delta: { type: 'text_delta', text } });
|
||||
send('content_block_stop', { index: 0 });
|
||||
send('message_delta', { delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 5 } });
|
||||
send('message_stop', {});
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
t.after(() => server.close());
|
||||
return { url: `http://127.0.0.1:${server.address().port}`, seen };
|
||||
}
|
||||
|
||||
function turn(env, request, cwd) {
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn('/bin/sh', [ADAPTER], { cwd, env: { ...env, ...fixtureCacheEnv(env.CLAUDE_CONFIG_DIR), MOSAIC_REQUEST: request }, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
||||
let stdout = '', stderr = '';
|
||||
child.stdout.on('data', (b) => (stdout += b));
|
||||
child.stderr.on('data', (b) => (stderr += b));
|
||||
const clock = setTimeout(() => process.kill(-child.pid, 'SIGKILL'), 120_000);
|
||||
child.on('close', (code) => { clearTimeout(clock); resolve({ code, stdout, stderr }); });
|
||||
});
|
||||
}
|
||||
|
||||
const SELECTIONS = {
|
||||
zai: { provider: 'zai', model: 'glm-fixture', module: 'cliproxy', upstream: 'zai' },
|
||||
codex: { provider: 'codex', model: 'gpt-fixture', module: 'cliproxy', upstream: 'codex' },
|
||||
};
|
||||
|
||||
// The route's api and endpoint describe pi's wire. claude-code ignores them: its env is the proxy
|
||||
// root and the key, and it always posts Anthropic Messages there, whatever the upstream.
|
||||
test('#1873 the catalogue offers a z.ai and a codex model to claude-code and pi, and the route admits both harnesses', async () => {
|
||||
const c = await cliproxy.catalogue({
|
||||
listAccounts: async () => ({ files: [{ provider: 'codex', name: 'codex-fixture.json', status: 'active' }] }),
|
||||
listModels: async () => ({ models: [{ id: 'gpt-fixture' }] }),
|
||||
listGroups: async () => [{ 'base-url': cliproxy.ZAI_URL, keys: [{}], models: [{ name: 'glm-fixture' }] }],
|
||||
now: () => 1,
|
||||
});
|
||||
assert.equal(c.status, 'ready');
|
||||
for (const [name, entry] of Object.entries(SELECTIONS)) {
|
||||
const row = c.models.find((m) => m.upstream === entry.upstream && m.model === entry.model);
|
||||
assert.deepEqual(row?.harnesses, ['claude-code', 'pi'], name);
|
||||
for (const harness of ['claude-code', 'pi']) {
|
||||
assert.deepEqual(cliproxy.preflight({ selection: entry, harness, catalogue: c }), { allow: true }, `${name} ${harness}`);
|
||||
assert.equal(checkedTransport(entry, harness).piProvider, `mosaic-proxy-${entry.upstream === 'zai' ? 'glm' : 'codex'}`, `${name} ${harness}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const [name, entry] of Object.entries(SELECTIONS)) {
|
||||
test(`#1873 claude-code sends the ${name} model name to the proxy's Anthropic-format route with the session key`, { skip }, async (t) => {
|
||||
const dir = scratch(t, 'mosaic-claude-proxy-');
|
||||
const workspace = join(dir, 'ws'); mkdirSync(workspace);
|
||||
const runDir = join(dir, 'run'); mkdirSync(runDir, { mode: 0o700 });
|
||||
const api = await standIn(t, `stand-in answer for ${entry.model}`);
|
||||
const key = `fx1873-claude-${name}`;
|
||||
const resolved = resolvedFor(t, 'coder', (d) => {
|
||||
d.launch.models.proxied = entry;
|
||||
d.roles.coder.vars = { harness: 'claude-code', model: 'proxied', thinking: 'low', 'limits.tools': ['read'] };
|
||||
});
|
||||
const sock = await fakeToolSocket(t, dir, (tool, args) => ({ tool, args }));
|
||||
const session = { workspace, sessionDir: join(dir, 'session'), toolSocket: sock.path, turnMarker: join(dir, 'turn.done'), runDir };
|
||||
const bundle = buildBundle({
|
||||
dir: join(runDir, 'bundle'), resolved, models: { proxied: entry }, contract: '# Coder\n',
|
||||
harness: HARNESS['claude-code'], skillsDir: REPO_SKILLS, proxy: { baseUrl: api.url, key },
|
||||
session: { ...session, run: 'r1873', launchedBy: 'pm' },
|
||||
});
|
||||
// The proxy's names come from the harness module's env, and nothing on disk holds the key.
|
||||
assert.equal(bundle.env.ANTHROPIC_BASE_URL, api.url);
|
||||
assert.equal(bundle.env.ANTHROPIC_AUTH_TOKEN, key);
|
||||
assert.equal(Object.hasOwn(bundle.env, 'ANTHROPIC_API_KEY'), false);
|
||||
for (const file of Object.values(bundle.files)) if (typeof file === 'string') {
|
||||
let text = ''; try { text = readFileSync(file, 'utf8'); } catch {}
|
||||
assert.equal(text.includes(key), false, file);
|
||||
}
|
||||
const s = { ...session, harness: 'claude-code', provider: entry.provider, model: entry.model, bundle: bundle.files, harnessEnv: bundle.env };
|
||||
const env = adapterEnv(s, {
|
||||
PATH: `${dirname(CLAUDE)}:${dirname(process.execPath)}:/usr/bin:/bin`,
|
||||
HOME: join(dir, 'home'), CLAUDE_CONFIG_DIR: join(dir, 'claude-config'),
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_TELEMETRY: '1', DISABLE_AUTOUPDATER: '1', DISABLE_ERROR_REPORTING: '1',
|
||||
});
|
||||
const r = await turn(env, 'Message 1 from pm, class ASSIGNMENT:\n\nsay hello', workspace);
|
||||
assert.equal(r.code, 0, r.stderr.replaceAll(key, '<key>'));
|
||||
assert.match(r.stdout, new RegExp(`stand-in answer for ${entry.model}`));
|
||||
const messages = api.seen.filter((x) => x.path === '/v1/messages');
|
||||
assert.ok(messages.length >= 1, JSON.stringify(api.seen));
|
||||
// The main turn names the selected model. Claude Code may add its own small background
|
||||
// requests; every request carries the session key as a bearer token and none uses x-api-key.
|
||||
assert.ok(messages.some((x) => x.model === entry.model), JSON.stringify(messages.map((x) => x.model)));
|
||||
for (const x of api.seen) { assert.equal(x.authSha, sha(key), x.path); assert.equal(x.apiKeySha, null, x.path); }
|
||||
assert.equal(r.stdout.includes(key) || r.stderr.includes(key), false);
|
||||
});
|
||||
}
|
||||
@@ -12,7 +12,8 @@ import { join, relative } from "node:path";
|
||||
import { buildBundle, PERSONA_CHARS } from "../src/bundle.mjs";
|
||||
import { decide } from "../src/gate.mjs";
|
||||
import { adapterEnv } from "../src/runner.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from "./helpers.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch, harnessReady } from "./helpers.mjs";
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
|
||||
const sha = (data) => createHash("sha256").update(data).digest("hex");
|
||||
const CREATIVE = ["companion", "ideas", "research", "proofreader", "fact-checker", "continuity"];
|
||||
@@ -177,7 +178,8 @@ function runAdapter(t, harness, b, { prompt = b.files.prompt, cwd } = {}) {
|
||||
writeFileSync(cli, '#!/bin/sh\nprintf "%s\\0" "$@" > "$ARGV_OUT"\necho \'{"type":"result","subtype":"success","result":"ok"}\'\n');
|
||||
chmodSync(cli, 0o755);
|
||||
const s = { harness, provider: harness === "pi" ? "probe" : null, model: "claude-sonnet-5-5", workspace: b.workspace, sessionDir: join(b.dir, "session"), toolSocket: join(b.dir, "tools.sock"), turnMarker: join(b.dir, "turn.done"), bundle: { ...b.files, prompt }, harnessEnv: b.env };
|
||||
const env = { ...adapterEnv(s, { PATH: `${bin}:/usr/bin:/bin`, HOME: join(b.dir, "home") }), ARGV_OUT: join(b.dir, "argv"), MOSAIC_REQUEST: "x" };
|
||||
// #1873 S2: the pi adapter runs MOSAIC_PI_BIN, which the bundle sets to the pi it found.
|
||||
const env = { ...adapterEnv(s, { PATH: `${bin}:/usr/bin:/bin`, HOME: join(b.dir, "home") }), ARGV_OUT: join(b.dir, "argv"), MOSAIC_REQUEST: "x", ...(harness === "pi" ? { MOSAIC_PI_BIN: cli } : {}) };
|
||||
const r = spawnSync("/bin/sh", [join(REPO, "adapters", harness === "pi" ? "pi" : "claude", "adapter.sh")], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env });
|
||||
const argv = existsSync(env.ARGV_OUT) ? readFileSync(env.ARGV_OUT, "utf8").split("\0") : null;
|
||||
return { ...r, argv };
|
||||
|
||||
@@ -31,6 +31,12 @@ async function harnessModule(name) {
|
||||
return loader.modules("harness")[0];
|
||||
}
|
||||
export const HARNESS = Object.freeze({ pi: await harnessModule("pi"), "claude-code": await harnessModule("claude-code") });
|
||||
// #1873 re-check 7: a module whose fit check runs async has ready(), which the launcher's preflight
|
||||
// stands for. A test that calls buildBundle directly awaits this first. It is not run on import:
|
||||
// request-agent.mjs imports this file in every tool-call process, which builds no bundle.
|
||||
export async function harnessReady() {
|
||||
for (const mod of Object.values(HARNESS)) if (typeof mod.ready === "function") await mod.ready();
|
||||
}
|
||||
|
||||
// A session's route is its own three vars (row 65); a role the test doesn't route runs pi on the
|
||||
// test system's old execution.model at thinking high, so the bundle tests keep their models.
|
||||
|
||||
@@ -6,7 +6,8 @@ import { join } from 'node:path';
|
||||
import { typedTools } from '../src/tools.mjs';
|
||||
import { buildBundle } from '../src/bundle.mjs';
|
||||
import { TYPES } from '../../library/src/mapping.mjs';
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch, harnessReady } from './helpers.mjs';
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
|
||||
const LOOKUPS = ['library_find', 'library_get', 'library_search', 'library_manuscript', 'library_universe'];
|
||||
const CREATIVE = ['companion', 'research', 'ideas', 'proofreader', 'fact-checker', 'continuity'];
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,8 @@ import { join } from "node:path";
|
||||
import { buildBundle } from "../src/bundle.mjs";
|
||||
import { adapterEnv, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
|
||||
import { REPLY_CAP } from "../src/tools.mjs";
|
||||
import { fakeToolSocket, HARNESS, mockAnthropic, REPO, REPO_SKILLS, resolvedFor, scratch } from "./helpers.mjs";
|
||||
import { fakeToolSocket, HARNESS, mockAnthropic, REPO, REPO_SKILLS, resolvedFor, scratch, harnessReady } from "./helpers.mjs";
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
|
||||
const ADAPTER = join(REPO, "adapters", "pi", "adapter.sh");
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
// #1873 pi-unpin S3: a stand-in pi that the fit check (src/pi-fit.mjs) can run. It is one sh
|
||||
// script with its knobs written into it, because the fit check runs it with an empty
|
||||
// environment. Put it at dist/bundle/cli.js in a package named @earendil-works/pi-coding-agent.
|
||||
//
|
||||
// What it does, in order:
|
||||
// --version prints `version` (default 9.9.9), or exits `versionExit` when that is set, or
|
||||
// hangs for a minute with `versionHang`
|
||||
// $ARGV_OUT set: a session. Writes its argv there, prints `sessionOut`, exits 0. This part is
|
||||
// sh, so it runs in a sandbox that holds no node.
|
||||
// otherwise runs node (the absolute path, since the fit check gives it no PATH) on the rest:
|
||||
// --help lists every flag the fit check wants, less `dropFlags`, plus `extraFlags`, then
|
||||
// the `helpProse` lines as they are
|
||||
// -e <file> a file that doesn't exist stops it with exit 1, unless `missingExtOk` is true or
|
||||
// names the mode ("rpc" or "print") it starts in anyway
|
||||
// --mode rpc loads the planted sources the way pi 0.85.1 finds them, honouring the seal flags,
|
||||
// or -p runs each -e extension's session_start (one that writes JSON.stringify(...) gets
|
||||
// the prompt this stand-in builds, the command names and the session id), then
|
||||
// answers get_state and get_commands
|
||||
// (rpc), or prints `sessionOut` and exits 0 (-p).
|
||||
// An -e file that exists loads even with --no-extensions, unless `dropExplicit`
|
||||
// (then it loads only without --no-extensions). `printNoStart`: -p runs no
|
||||
// session_start. MCP servers stay out with --no-mcp when `extraFlags` lists it, else
|
||||
// with --no-extensions.
|
||||
// `ignoreAll` loads no planted source. `sealLeak` lists kinds (extensions, mcp,
|
||||
// skills, prompts, context, approve) loaded even when their seal flag is on.
|
||||
// `ignoreSystemPrompt` drops the --system-prompt file. `ignoreAppend` drops every
|
||||
// APPEND_SYSTEM.md. `sysReplacesAll`: a --system-prompt file also drops every
|
||||
// APPEND_SYSTEM.md and context file. `trustExtOnly`: the only extensions are the
|
||||
// project's .pi/extensions, loaded in a trusted project whatever --no-extensions
|
||||
// says. `trustCtxOnly`: the only context file is the project's AGENTS.md, loaded the
|
||||
// same way whatever --no-context-files says. `flood`: prints 8 MB first.
|
||||
// `hideWhen`: a cue, a flag or "order" (--offline before --no-session). With the cue
|
||||
// it loads no planted source; without it, every kind even with its seal flag on.
|
||||
// `standIn`: [flag, other]: it ignores flag, and other keeps flag's kind out instead.
|
||||
// `remember`: the first run in a scratch directory (it leaves a marker beside the
|
||||
// -e file's directory) loads every kind whatever the seal flags; a later run loads
|
||||
// none. `needs`: a flag the loader flags work only with; without it they do
|
||||
// nothing. `leakWithout`: flags; when any of them is absent, every kind loads.
|
||||
// `leakWith`: flags; when all of them are given, every kind loads (with
|
||||
// `leakWithout` too, both must hold). `mcpAlso`: a flag that keeps MCP servers out
|
||||
// as well as their own flag does. `leakNoAgentDir`: every kind loads when
|
||||
// PI_CODING_AGENT_DIR is unset, as in a bus session. `leakNoVar`: names; every
|
||||
// kind loads when any of them is unset (TERM, TZ, LC_ALL in a unit-started bus).
|
||||
// `leakNoMatch`: with -c, every
|
||||
// kind loads when no .jsonl in --session-dir names the working directory.
|
||||
// `leakEnv`: { json, other }, the variable names a run with --mode json and any
|
||||
// other run should get; every kind loads when the environment holds a name not in
|
||||
// the list or lacks one, apart from the names /bin/sh sets (PWD, OLDPWD, SHLVL, _).
|
||||
// An -e extension that writes JSON.stringify({...}) at session_start gets the
|
||||
// prompt, the command names, the session id (with -c, the id in the header of a
|
||||
// .jsonl in --session-dir whose cwd is the working directory, else a new one) and
|
||||
// the --thinking level (else "medium"). `noResume`: -c always starts a new
|
||||
// session. `oneExt`: only the first -e loads. `extNoCommands`: the extension sees
|
||||
// no commands.
|
||||
// `commands` "fail" answers get_commands with success false; "list" answers
|
||||
// with a bare list.
|
||||
// --skill <dir> loads that skill (its directory's name) whatever --no-skills says,
|
||||
// as pi 0.85.1 does. `skillLeak`: with a --skill given, the planted skills load too
|
||||
// whatever --no-skills says (discovery comes back with --skill). `ignoreSkill`: a
|
||||
// --skill directory loads only without --no-skills.
|
||||
// otherwise a session with no $ARGV_OUT: prints `sessionOut` and exits 0.
|
||||
//
|
||||
// Trust, as pi 0.85.1 has it: the project is trusted with --approve, or with a saved trust and
|
||||
// no --no-approve. Only the project SYSTEM.md and APPEND_SYSTEM.md wait on it here. The user
|
||||
// APPEND_SYSTEM.md is appended whatever the flags, as 0.85.1 does when the project has none.
|
||||
import { FIT_FLAGS } from "../src/pi-fit.mjs";
|
||||
|
||||
const BODY = String.raw`
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const cp = require("node:child_process");
|
||||
const argv = process.argv.slice(1);
|
||||
const has = (f) => argv.includes(f);
|
||||
const val = (f) => { const i = argv.indexOf(f); return i === -1 ? undefined : argv[i + 1]; };
|
||||
if (argv[0] === "--help") {
|
||||
const drop = new Set(K.dropFlags || []);
|
||||
const lines = ["Usage: pi [options] [messages...]", "", "Options:"];
|
||||
for (const f of FLAGS) {
|
||||
if (drop.has(f)) continue;
|
||||
if (f === "--mode") lines.push(" --mode <mode> Output mode: " + (K.modes || ["text", "json", "rpc"]).join(", "));
|
||||
else if (f === "--thinking") lines.push(" --thinking <level> Thinking level: " + (K.levels || ["off", "minimal", "low", "medium", "high", "xhigh", "max"]).join(", "));
|
||||
else lines.push(" " + f);
|
||||
}
|
||||
for (const f of K.extraFlags || []) lines.push(" " + f);
|
||||
for (const l of K.helpProse || []) lines.push(l);
|
||||
process.stdout.write(lines.join("\n") + "\n");
|
||||
process.exit(0);
|
||||
}
|
||||
const rpc = val("--mode") === "rpc";
|
||||
const print = !rpc && has("-p");
|
||||
const startsAnyway = K.missingExtOk === true || (rpc && K.missingExtOk === "rpc") || (print && K.missingExtOk === "print");
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
if (argv[i] === "-e" && !fs.existsSync(argv[i + 1]) && !startsAnyway) {
|
||||
process.stderr.write("Failed to load extension: it does not exist\n");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
if (rpc || print) {
|
||||
if (K.flood) {
|
||||
const chunk = Buffer.alloc(1024 * 1024, "x");
|
||||
for (let n = 0; n < 8; n++) for (let off = 0; off < chunk.length;) {
|
||||
try { off += fs.writeSync(1, chunk, off); } catch (e) { if (e.code !== "EAGAIN") throw e; }
|
||||
}
|
||||
}
|
||||
const ALL = ["extensions", "mcp", "skills", "prompts", "context", "approve"];
|
||||
// The id in the header of the last .jsonl in dir whose cwd is the working directory, or null.
|
||||
const storedFor = (dir) => {
|
||||
let id = null;
|
||||
if (dir) for (const n of (() => { try { return fs.readdirSync(dir); } catch { return []; } })()) {
|
||||
if (!n.endsWith(".jsonl")) continue;
|
||||
let h = null;
|
||||
try { h = JSON.parse(fs.readFileSync(path.join(dir, n), "utf8").split("\n")[0]); } catch { h = null; }
|
||||
if (h && h.type === "session" && h.cwd === process.cwd()) id = h.id;
|
||||
}
|
||||
return id;
|
||||
};
|
||||
let ignoreAll = K.ignoreAll;
|
||||
let leak = new Set(K.sealLeak || []);
|
||||
if (K.hideWhen) {
|
||||
const cued = K.hideWhen === "order" ? argv.indexOf("--offline") !== -1 && argv.indexOf("--offline") < argv.indexOf("--no-session") : has(K.hideWhen);
|
||||
if (cued) ignoreAll = true;
|
||||
else leak = new Set(ALL);
|
||||
}
|
||||
if (K.remember) {
|
||||
const marker = path.join(path.dirname(path.dirname(val("-e"))), "seen-before");
|
||||
if (fs.existsSync(marker)) ignoreAll = true;
|
||||
else { fs.writeFileSync(marker, ""); leak = new Set(ALL); }
|
||||
}
|
||||
if ((K.leakWith || K.leakWithout) && (K.leakWith || []).every(has) && (!K.leakWithout || K.leakWithout.some((f) => !has(f)))) leak = new Set(ALL);
|
||||
if (K.leakNoAgentDir && !process.env.PI_CODING_AGENT_DIR) leak = new Set(ALL);
|
||||
if (K.leakNoVar && K.leakNoVar.some((n) => process.env[n] === undefined)) leak = new Set(ALL);
|
||||
if (K.leakNoMatch && has("-c") && !storedFor(val("--session-dir"))) leak = new Set(ALL);
|
||||
if (K.leakEnv) {
|
||||
const want = new Set(K.leakEnv[val("--mode") === "json" ? "json" : "other"]);
|
||||
const got = Object.keys(process.env).filter((n) => !["PWD", "OLDPWD", "SHLVL", "_"].includes(n));
|
||||
if (got.length !== want.size || got.some((n) => !want.has(n))) leak = new Set(ALL);
|
||||
}
|
||||
// Whether a seal flag is on: with standIn, its flag reads as the other flag; with needs, only
|
||||
// when that flag is given too.
|
||||
const sealed = (flag) => has(K.standIn && K.standIn[0] === flag ? K.standIn[1] : flag) && (!K.needs || has(K.needs));
|
||||
const on = (kind, flag) => !ignoreAll && (!sealed(flag) || leak.has(kind));
|
||||
const agent = process.env.PI_CODING_AGENT_DIR || path.join(process.env.HOME || "/", ".pi", "agent");
|
||||
const cwd = process.cwd();
|
||||
const list = (dir, test) => { try { return fs.readdirSync(dir).filter(test).map((n) => path.join(dir, n)); } catch { return []; } };
|
||||
const json = (file) => { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } };
|
||||
const read = (file) => { try { return fs.readFileSync(file, "utf8"); } catch { return null; } };
|
||||
const settings = [json(path.join(agent, "settings.json")), json(path.join(cwd, ".pi", "settings.json"))].filter(Boolean);
|
||||
const trust = json(path.join(agent, "trust.json")) || {};
|
||||
const saved = settings.some((s) => s.defaultProjectTrust === "always") || trust[cwd] === true;
|
||||
const trusted = !ignoreAll && (has("--approve") || (saved && (!sealed("--no-approve") || leak.has("approve"))));
|
||||
const commands = [];
|
||||
// A planted extension writes one marker on load; an -e extension may also write what it saw at
|
||||
// session_start. Do what each would do.
|
||||
const starts = [];
|
||||
const load = (f) => {
|
||||
const text = read(f);
|
||||
if (text === null) return;
|
||||
for (const m of text.matchAll(/writeFileSync\(("(?:[^"\\]|\\.)*")(, JSON\.stringify\()?/g)) {
|
||||
if (m[2]) starts.push(JSON.parse(m[1]));
|
||||
else fs.writeFileSync(JSON.parse(m[1]), "");
|
||||
}
|
||||
};
|
||||
const given = argv.flatMap((a, i) => a === "-e" ? [argv[i + 1]] : []);
|
||||
if (!(K.dropExplicit && has("--no-extensions"))) for (const f of K.oneExt ? given.slice(0, 1) : given) load(f);
|
||||
const packages = settings.flatMap((s) => (s.packages || []).map((p) => typeof p === "string" ? p : p.source));
|
||||
if (K.trustExtOnly) {
|
||||
if (trusted) for (const f of list(path.join(cwd, ".pi", "extensions"), (n) => n.endsWith(".ts"))) load(f);
|
||||
} else if (on("extensions", "--no-extensions")) {
|
||||
const files = [...list(path.join(agent, "extensions"), (n) => n.endsWith(".ts")), ...list(path.join(cwd, ".pi", "extensions"), (n) => n.endsWith(".ts"))];
|
||||
for (const s of settings) files.push(...(s.extensions || []));
|
||||
for (const p of packages) files.push(...list(path.join(p, "extensions"), (n) => n.endsWith(".ts")));
|
||||
for (const f of files) load(f);
|
||||
}
|
||||
const mcpFlag = (K.extraFlags || []).includes("--no-mcp") ? "--no-mcp" : "--no-extensions";
|
||||
if (!ignoreAll && (!(sealed(mcpFlag) || (K.mcpAlso && has(K.mcpAlso))) || leak.has("mcp"))) {
|
||||
for (const f of [path.join(agent, "mcp.json"), path.join(cwd, ".pi", "mcp.json"), path.join(cwd, ".mcp.json")]) {
|
||||
for (const s of Object.values(json(f)?.mcpServers || {})) cp.spawnSync(s.command, s.args || [], { stdio: "ignore" });
|
||||
}
|
||||
}
|
||||
if (on("skills", "--no-skills") || (K.skillLeak && has("--skill") && !ignoreAll)) {
|
||||
const home = process.env.HOME || "/";
|
||||
const dirs = [path.join(agent, "skills"), path.join(cwd, ".pi", "skills"), path.join(cwd, ".agents", "skills"), path.join(home, ".agents", "skills"), ...packages.map((p) => path.join(p, "skills"))];
|
||||
for (const d of dirs) for (const p of list(d, () => true)) commands.push({ name: "skill:" + path.basename(p), source: "skill" });
|
||||
for (const s of settings) for (const p of s.skills || []) commands.push({ name: "skill:" + path.basename(p), source: "skill" });
|
||||
}
|
||||
if (!(K.ignoreSkill && has("--no-skills"))) for (const p of argv.flatMap((a, i) => a === "--skill" ? [argv[i + 1]] : [])) commands.push({ name: "skill:" + path.basename(p), source: "skill" });
|
||||
if (on("prompts", "--no-prompt-templates")) {
|
||||
const dirs = [path.join(agent, "prompts"), path.join(cwd, ".pi", "prompts"), ...packages.map((p) => path.join(p, "prompts"))];
|
||||
for (const d of dirs) for (const p of list(d, (n) => n.endsWith(".md"))) commands.push({ name: path.basename(p, ".md"), source: "prompt" });
|
||||
for (const s of settings) for (const p of s.prompts || []) commands.push({ name: path.basename(p, ".md"), source: "prompt" });
|
||||
}
|
||||
// The system prompt: the --system-prompt file, else SYSTEM.md; then APPEND_SYSTEM.md; then the
|
||||
// context files, from the agent directory and from / down to the working directory.
|
||||
const sys = K.ignoreSystemPrompt ? null : val("--system-prompt");
|
||||
const own = (name) => (trusted && read(path.join(cwd, ".pi", name))) || (!ignoreAll && read(path.join(agent, name))) || "";
|
||||
const hide = K.sysReplacesAll && sys;
|
||||
const parts = [sys ? (read(sys) || "") : own("SYSTEM.md"), K.ignoreAppend || hide ? "" : own("APPEND_SYSTEM.md")];
|
||||
if (K.trustCtxOnly) {
|
||||
if (trusted) parts.push(read(path.join(cwd, "AGENTS.md")) || "");
|
||||
} else if (!hide && on("context", "--no-context-files")) {
|
||||
const dirs = [];
|
||||
for (let d = cwd; ; d = path.dirname(d)) { dirs.unshift(d); if (path.dirname(d) === d) break; }
|
||||
parts.push(read(path.join(agent, "AGENTS.md")) || "");
|
||||
for (const d of dirs) parts.push(read(path.join(d, "AGENTS.md")) || read(path.join(d, "CLAUDE.md")) || "");
|
||||
}
|
||||
// The session -c resumes: the newest .jsonl in --session-dir whose header names this cwd.
|
||||
let session = "stand-in-" + process.pid;
|
||||
const dir = val("--session-dir");
|
||||
if (has("-c") && dir && !K.noResume) session = storedFor(dir) || session;
|
||||
const start = { prompt: parts.join("\n"), commands: K.extNoCommands ? [] : commands.map((c) => c.name), session };
|
||||
if (!(print && K.printNoStart)) for (const f of starts) fs.writeFileSync(f, JSON.stringify(start));
|
||||
if (print) {
|
||||
if (K.sessionOut) process.stdout.write(K.sessionOut);
|
||||
process.exit(0);
|
||||
}
|
||||
let input = "";
|
||||
try { input = fs.readFileSync(0, "utf8"); } catch { input = ""; }
|
||||
for (const line of input.split("\n")) {
|
||||
let m;
|
||||
try { m = JSON.parse(line); } catch { continue; }
|
||||
if (m.type === "get_state") process.stdout.write(JSON.stringify({ id: m.id, type: "response", command: "get_state", success: true, data: { isStreaming: false } }) + "\n");
|
||||
if (m.type === "get_commands") {
|
||||
const answer = K.commands === "fail" ? { success: false, error: "no" } : { success: true, data: K.commands === "list" ? commands : { commands } };
|
||||
process.stdout.write(JSON.stringify({ id: m.id, type: "response", command: "get_commands", ...answer }) + "\n");
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
if (K.sessionOut) process.stdout.write(K.sessionOut);
|
||||
process.exit(0);
|
||||
`;
|
||||
|
||||
const quote = (text) => `'${String(text).replace(/'/g, "'\\''")}'`;
|
||||
|
||||
// The script text. node: the interpreter the fit part runs on (absolute, so it runs with no PATH).
|
||||
export function piStandIn(knobs = {}, { node = process.execPath } = {}) {
|
||||
const version = knobs.versionHang ? "sleep 60; exit 0" : knobs.versionExit != null ? `exit ${Number(knobs.versionExit)}` : `printf '%s\\n' ${quote(knobs.version ?? "9.9.9")}; exit 0`;
|
||||
const program = `"use strict";\nconst K = ${JSON.stringify(knobs)};\nconst FLAGS = ${JSON.stringify(FIT_FLAGS)};\n${BODY}`;
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
`[ "$1" = --version ] && { ${version}; }`,
|
||||
`if [ -n "\${ARGV_OUT:-}" ]; then printf '%s\\n' "$@" > "$ARGV_OUT"; printf '%s' ${quote(knobs.sessionOut ?? "")}; exit 0; fi`,
|
||||
`exec ${quote(node)} -e ${quote(program)} -- "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -4,12 +4,14 @@ import assert from 'node:assert/strict';
|
||||
import { mkdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { buildBundle } from '../src/bundle.mjs';
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch, harnessReady } from './helpers.mjs';
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
|
||||
const models = {
|
||||
a: { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' },
|
||||
z: { provider: 'proxy', model: 'glm-fixture', route: 'glm' },
|
||||
g: { provider: 'proxy', model: 'gpt-fixture', route: 'codex' },
|
||||
o: { provider: 'other', model: 'fixture-other', module: 'cliproxy', upstream: 'other' },
|
||||
};
|
||||
function build(t, selection, proxy, declared) {
|
||||
const root = scratch(t, 'p332-'), runDir = join(root, 'run');
|
||||
@@ -32,14 +34,22 @@ function assertSafe(value) {
|
||||
else if (value && typeof value === 'object') for (const item of Object.values(value)) assertSafe(item);
|
||||
}
|
||||
|
||||
test('P3 Anthropic route uses messages at proxy root and the declared model id', t => {
|
||||
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a });
|
||||
const { anthropic } = JSON.parse(b.text).providers;
|
||||
assert.equal(anthropic.api, 'anthropic-messages');
|
||||
assert.equal(anthropic.baseUrl, 'http://127.0.0.1:12345');
|
||||
assert.deepEqual(anthropic.models.map(m => m.id), ['claude-fixture']);
|
||||
assert.equal(b.env.PI_PROVIDER, 'anthropic');
|
||||
assert.equal(b.env.PI_MODEL, 'claude-fixture');
|
||||
// #1873 harness-matrix: a Claude account model runs on claude-code only, so a pi session on it
|
||||
// refuses before any file is written.
|
||||
test('a proxy Claude route on pi refuses model-harness-incompatible before model config generation', t => {
|
||||
for (const a of [models.a, { provider: 'anthropic', model: 'fixture-chat' }, { provider: 'anthropic', model: 'fixture-chat', module: 'cliproxy', upstream: 'claude' }])
|
||||
assert.throws(() => build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a }), { code: 'model-harness-incompatible' }, JSON.stringify(a));
|
||||
});
|
||||
|
||||
test('an other-upstream route uses messages at proxy root under its own pi provider, never pi\'s built-in anthropic', t => {
|
||||
const b = build(t, 'o', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { o: models.o });
|
||||
const providers = JSON.parse(b.text).providers;
|
||||
assert.deepEqual(Object.keys(providers), ['mosaic-proxy-other']);
|
||||
assert.equal(providers['mosaic-proxy-other'].api, 'anthropic-messages');
|
||||
assert.equal(providers['mosaic-proxy-other'].baseUrl, 'http://127.0.0.1:12345');
|
||||
assert.deepEqual(providers['mosaic-proxy-other'].models.map(m => m.id), ['fixture-other']);
|
||||
assert.equal(b.env.PI_PROVIDER, 'mosaic-proxy-other');
|
||||
assert.equal(b.env.PI_MODEL, 'fixture-other');
|
||||
});
|
||||
|
||||
test('P3 omitted route refuses proxy-route-missing before model config generation', t => {
|
||||
@@ -82,9 +92,11 @@ test('P3 a declared Codex route generates only the single build-time responses p
|
||||
|
||||
test('P3 models file is private, references the one session key, and stores no executable values or keys', t => {
|
||||
const key = 'fx332-agent-a';
|
||||
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key }, { a: models.a, z: models.z });
|
||||
const b = build(t, 'z', { baseUrl: 'http://127.0.0.1:12345', key }, { a: models.a, z: models.z, o: models.o });
|
||||
const document = JSON.parse(b.text);
|
||||
assert.deepEqual(Object.keys(document.providers).sort(), ['anthropic', 'mosaic-proxy-glm']);
|
||||
// #1873: the Claude account entry is left out of a pi session's file.
|
||||
assert.deepEqual(Object.keys(document.providers).sort(), ['mosaic-proxy-glm', 'mosaic-proxy-other']);
|
||||
assert.ok(!b.text.includes('claude-fixture'));
|
||||
for (const provider of Object.values(document.providers)) assert.equal(provider.apiKey, '$ANTHROPIC_API_KEY');
|
||||
assertSafe(document);
|
||||
assert.ok(!b.text.includes(key));
|
||||
@@ -96,20 +108,20 @@ test('P3 models file is private, references the one session key, and stores no e
|
||||
});
|
||||
|
||||
test('P3 every launch regenerates proxy port, declared models and own key without caching', t => {
|
||||
const first = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a, z: models.z });
|
||||
const second = build(t, 'a', { baseUrl: 'http://127.0.0.1:23456', key: 'fx332-agent-b' }, {
|
||||
a: { provider: 'proxy', model: 'changed-model-id', route: 'anthropic' },
|
||||
const first = build(t, 'z', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { g: models.g, z: models.z });
|
||||
const second = build(t, 'z', { baseUrl: 'http://127.0.0.1:23456', key: 'fx332-agent-b' }, {
|
||||
g: { provider: 'proxy', model: 'changed-model-id', route: 'codex' },
|
||||
z: { provider: 'proxy', model: 'changed-glm-id', route: 'glm' },
|
||||
});
|
||||
assert.equal(second.env.ANTHROPIC_API_KEY, 'fx332-agent-b');
|
||||
assert.ok(!JSON.stringify(second).includes('fx332-agent-a'));
|
||||
const { providers } = JSON.parse(second.text);
|
||||
assert.deepEqual(Object.keys(providers), ['anthropic', 'mosaic-proxy-glm']);
|
||||
assert.equal(providers.anthropic.baseUrl, 'http://127.0.0.1:23456');
|
||||
assert.deepEqual(providers.anthropic.models.map(m => m.id), ['changed-model-id']);
|
||||
assert.deepEqual(Object.keys(providers), ['mosaic-proxy-codex', 'mosaic-proxy-glm']);
|
||||
assert.equal(providers['mosaic-proxy-codex'].baseUrl, 'http://127.0.0.1:23456/v1');
|
||||
assert.deepEqual(providers['mosaic-proxy-codex'].models.map(m => m.id), ['changed-model-id']);
|
||||
assert.equal(providers['mosaic-proxy-glm'].baseUrl, 'http://127.0.0.1:23456/v1');
|
||||
assert.deepEqual(providers['mosaic-proxy-glm'].models.map(m => m.id), ['changed-glm-id']);
|
||||
assert.equal(JSON.parse(first.text).providers.anthropic.baseUrl, 'http://127.0.0.1:12345');
|
||||
assert.equal(JSON.parse(first.text).providers['mosaic-proxy-glm'].baseUrl, 'http://127.0.0.1:12345/v1');
|
||||
});
|
||||
|
||||
// Row 332 R2 (#1830, review F2): launch.models is open table data. An entry whose provider has no
|
||||
@@ -121,14 +133,14 @@ test('row 332 R2 an unroutable model table entry is left out of models.json and
|
||||
glm: { provider: 'zai', model: 'glm-fixture' },
|
||||
router: { provider: 'openrouter', model: 'x' },
|
||||
};
|
||||
const b = build(t, 'opus', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, declared);
|
||||
const b = build(t, 'glm', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, declared);
|
||||
const { providers } = JSON.parse(b.text);
|
||||
assert.deepEqual(Object.keys(providers).sort(), ['anthropic', 'mosaic-proxy-glm']);
|
||||
assert.deepEqual(providers.anthropic.models.map(m => m.id), ['claude-fixture']);
|
||||
// #1873: the Claude account entry is one a pi session can't run, so it is left out too.
|
||||
assert.deepEqual(Object.keys(providers).sort(), ['mosaic-proxy-glm']);
|
||||
assert.deepEqual(providers['mosaic-proxy-glm'].models.map(m => m.id), ['glm-fixture']);
|
||||
assert.ok(!Object.values(providers).some(p => p.models.some(m => m.id === 'x')), 'the openrouter entry is not written');
|
||||
assert.equal(b.env.PI_MODEL, 'claude-fixture');
|
||||
assert.throws(() => build(t, 'opus', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
|
||||
assert.equal(b.env.PI_MODEL, 'glm-fixture');
|
||||
assert.throws(() => build(t, 'glm', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
|
||||
...declared, broken: { provider: 'proxy', model: 'claude-fixture' },
|
||||
}), { code: 'proxy-route-missing' });
|
||||
});
|
||||
@@ -140,7 +152,7 @@ test('row 332 R2 a session proxy context without a key or loopback URL refuses i
|
||||
{ baseUrl: 'http://localhost:12345', key: 'fx332-agent-a' },
|
||||
{ baseUrl: 'http://127.0.0.1:12345' },
|
||||
]) {
|
||||
assert.throws(() => build(t, 'a', proxy, { a: models.a }),
|
||||
assert.throws(() => build(t, 'z', proxy, { z: models.z }),
|
||||
{ code: 'invalid-proxy-context', message: 'invalid session proxy context' }, JSON.stringify(proxy));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,12 +3,12 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { sessionModel } from '../src/bundle.mjs';
|
||||
const resolved = { instance: 'fixture', vars: { harness: 'pi', model: 'selected', thinking: 'low' } };
|
||||
for (const [provider, model, expected] of [
|
||||
['anthropic', 'glm-looking-id', 'anthropic'],
|
||||
['zai', 'gpt-looking-id', 'glm'],
|
||||
for (const [provider, model, expected, harness] of [
|
||||
['anthropic', 'glm-looking-id', 'anthropic', 'claude-code'],
|
||||
['zai', 'gpt-looking-id', 'glm', 'pi'],
|
||||
]) {
|
||||
test(`joined proxy context maps provider ${provider} by identity, not model name`, () => {
|
||||
const selected = sessionModel(resolved, { selected: { provider, model } }, 'primary', { proxy: true });
|
||||
const selected = sessionModel({ ...resolved, vars: { ...resolved.vars, harness } }, { selected: { provider, model } }, 'primary', { proxy: true });
|
||||
assert.equal(selected.proxyRoute, expected);
|
||||
assert.equal(selected.provider, provider, 'public/accounting provider identity is retained');
|
||||
assert.equal(selected.model, model);
|
||||
@@ -31,7 +31,7 @@ test('provider proxy still requires an explicit route inside joined context', ()
|
||||
assert.throws(() => sessionModel(resolved, { selected: { provider: 'proxy', model: 'fixture', route: 'custom' } }, 'primary', { proxy: true }), {
|
||||
code: 'proxy-route-unknown',
|
||||
});
|
||||
assert.equal(sessionModel(resolved, { selected: { provider: 'proxy', model: 'claude-looking-id', route: 'codex' } }, 'primary', { proxy: true }).proxyRoute, 'codex');
|
||||
assert.equal(sessionModel(resolved, { selected: { provider: 'proxy', model: 'fixture-codex-id', route: 'codex' } }, 'primary', { proxy: true }).proxyRoute, 'codex');
|
||||
});
|
||||
test('a module-backed selection carries the provider transport descriptor without changing accounting', () => {
|
||||
const selected = sessionModel(resolved, { selected: { provider: 'codex', model: 'fixture-codex', module: 'cliproxy', upstream: 'codex' } }, 'primary', { proxy: true });
|
||||
@@ -52,3 +52,23 @@ test('transport accepts bounded compatibility flags declared by a provider modul
|
||||
const resolver=()=>({provider:'fixture',model:'fixture-id',routeId:'fixture',endpoint:'v1',api:'openai-completions',piProvider:'fixture',compat:{supportsStore:false,thinkingFormat:'openai'}});
|
||||
assert.deepEqual(sessionModel(resolved,{selected:entry},'primary',{proxy:true,resolver}).proxyTransport.compat,{supportsStore:false,thinkingFormat:'openai'});
|
||||
});
|
||||
|
||||
// #1873 harness-matrix: the launch checks the route's own harness, so a stored OAuth Claude route on pi
|
||||
// is refused before any run, with or without a model-provider module switched on.
|
||||
test('a stored proxy Claude route on pi refuses model-harness-incompatible at launch', () => {
|
||||
for (const selected of [{ provider: 'anthropic', model: 'fixture-chat' }, { provider: 'proxy', route: 'anthropic', model: 'fixture-chat' },
|
||||
{ provider: 'anthropic', model: 'fixture-chat', module: 'cliproxy', upstream: 'claude' }])
|
||||
assert.throws(() => sessionModel(resolved, { selected }, 'primary', { proxy: true }), { code: 'model-harness-incompatible' }, JSON.stringify(selected));
|
||||
// Jason 2026-11-19: the rule keys on the account kind. A module entry, whose kind the catalogue
|
||||
// knows, runs on pi with a Claude name. A legacy entry carries no account data, so a Claude name
|
||||
// there is treated as OAuth.
|
||||
for (const selected of [{ provider: 'other', model: 'anthropic/claude-sonnet-5-5', module: 'cliproxy', upstream: 'other' },
|
||||
{ provider: 'zai', model: 'claude-looking-id', module: 'cliproxy', upstream: 'zai' }, { provider: 'zai', model: 'glm-fixture' }])
|
||||
assert.equal(sessionModel(resolved, { selected }, 'primary', { proxy: true }).model, selected.model, JSON.stringify(selected));
|
||||
for (const selected of [{ provider: 'proxy', route: 'codex', model: 'claude-looking-id' }, { provider: 'zai', model: 'claude-looking-id' }, { provider: 'proxy', route: 'glm', model: 'claude-opus-5-5' }])
|
||||
assert.throws(() => sessionModel(resolved, { selected }, 'primary', { proxy: true }), { code: 'model-harness-incompatible' }, JSON.stringify(selected));
|
||||
const claudeCode = { ...resolved, vars: { ...resolved.vars, harness: 'claude-code' } };
|
||||
assert.equal(sessionModel(claudeCode, { selected: { provider: 'anthropic', model: 'fixture-chat' } }, 'primary', { proxy: true }).proxyRoute, 'anthropic');
|
||||
for (const selected of [{ provider: 'zai', model: 'fixture-zai' }, { provider: 'codex', model: 'fixture-codex', module: 'cliproxy', upstream: 'codex' }])
|
||||
assert.equal(sessionModel(claudeCode, { selected }, 'primary', { proxy: true }).provider, selected.provider);
|
||||
});
|
||||
@@ -4,7 +4,8 @@ import { readFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { buildBundle } from '../src/bundle.mjs';
|
||||
import { typedTools } from '../src/tools.mjs';
|
||||
import { resolvedFor, scratch, HARNESS, REPO_SKILLS } from './helpers.mjs';
|
||||
import { resolvedFor, scratch, HARNESS, REPO_SKILLS, harnessReady } from './helpers.mjs';
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
import { ownRails, railsText, decisionAutonomy } from '../../organization/src/rails.mjs';
|
||||
|
||||
const SECRET = 'sk-test-NOT-A-SECRET-1234';
|
||||
|
||||
@@ -9,7 +9,8 @@ import { createServer } from 'node:net';
|
||||
import { buildBundle, SOURCES } from '../src/bundle.mjs';
|
||||
import { callTool, typedTools } from '../src/tools.mjs';
|
||||
import * as runner from '../src/runner.mjs';
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch, harnessReady } from './helpers.mjs';
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
import { Broker } from '../../bus/src/broker.mjs';
|
||||
import { Store } from '../../bus/src/store.mjs';
|
||||
import { createRequestStore } from '../../bus/src/request-store.mjs';
|
||||
|
||||
@@ -322,6 +322,63 @@ test("r127 an adapter exit 127 names the program that wasn't found, through the
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
// #1873 chat-fail F1: a turn that ended on the harness's error result showed only "adapter exited 1".
|
||||
// The real claude adapter prints the CLI's final error result on stdout and exits with the CLI's code.
|
||||
test("chat-fail F1 an error result from the harness reaches the chat line as a plain cause and next step", async t => {
|
||||
const ctx = await setup(t, {session:{harness:"claude-code", turnEnd:"exit", adapter:new URL("../../../adapters/claude/adapter.sh", import.meta.url).pathname}});
|
||||
const sessionFile = join(ctx.runDir, "session.json");
|
||||
const session = JSON.parse(readFileSync(sessionFile, "utf8"));
|
||||
const bin = join(ctx.dir, "model-fixture");
|
||||
const result = {type:"result", subtype:"success", is_error:true, result:"You've hit your limit \u00b7 resets 3pm (UTC)"};
|
||||
writeFileSync(bin, `#!${process.execPath}\nconsole.log(${JSON.stringify(JSON.stringify(result))});\nprocess.exit(1);\n`, {mode:0o755});
|
||||
session.harnessEnv = {MOSAIC_CLAUDE_BIN:bin, MOSAIC_THINKING:"low", MOSAIC_CLAUDE_SETTINGS:session.bundle.policy, MOSAIC_CLAUDE_MCP_CONFIG:session.bundle.tools};
|
||||
writeFileSync(sessionFile, JSON.stringify(session));
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
const sent = ctx.call(ctx.pm, "message.send", {to:"coder", body:"hello", class:"REQUEST"});
|
||||
const [reply] = await until(replies(ctx));
|
||||
await until(() => ctx.store.get("SELECT 1 FROM deliveries WHERE message=? AND op='read'", sent.id));
|
||||
assert.equal(reply.body, "The turn failed: the model account is out of usage. Check Settings > Model setup.\nDetails: adapter exited 1");
|
||||
assert.match(r.stderr(), /failed: adapter exited 1 \(the model account is out of usage/);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("chat-fail F1 error text is cleaned, redacted and capped; a held secret withholds it; no text keeps the bare reason", async t => {
|
||||
const secret = "fixture-secret-0123456789abcdef";
|
||||
const ctx = await setup(t, {session:{harnessEnv:{MOSAIC_FIXTURE_TOKEN:secret}}});
|
||||
const adapter = join(ctx.dir, "adapter.sh");
|
||||
// HOSTILE: ANSI, C0, C1, DEL, bidi and zero-width characters, a link with a query and userinfo, an
|
||||
// email, a path, a Bearer value, key prefixes, a JWT and a long text. LEAK: the turn's own secret,
|
||||
// split by a newline and a zero-width space. QUIET: nothing on stdout.
|
||||
writeFileSync(adapter, [
|
||||
'case "$MOSAIC_REQUEST" in',
|
||||
// The long text comes first: the harness prints its error result last, and only the tail is read.
|
||||
`*HOSTILE*) head -c 2000 /dev/zero | tr '\\0' 'w'; printf '\\n\\033[31mAPI Error: 500\\033[0m \\001\\177\\302\\205 boom \\342\\200\\256evil\\342\\200\\213 https://u:[email protected]/x?key=abc [email protected] /home/someone/.config/x Bearer abc.def sk-ant-api03-zzz msk-abcdef eyJhbGciOi.eyJzdWIi.sig AbCdEf0123456789XyZ\\n'; exit 1 ;;`,
|
||||
`*LEAK*) printf 'failed: fixture-secret-01234\\n5678\\342\\200\\2139abcdef\\n'; exit 1 ;;`,
|
||||
`*QUIET*) exit 1 ;;`,
|
||||
'esac',
|
||||
].join("\n") + "\n");
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
for (const body of ["HOSTILE", "LEAK", "QUIET"]) ctx.call(ctx.pm, "message.send", {to:"coder", body});
|
||||
await until(() => replies(ctx)() && ctx.inbox.length >= 3);
|
||||
const [hostile, leak, quiet] = ctx.inbox.map(m => m.body);
|
||||
const [cause, details] = hostile.slice("The turn failed: ".length).split("\nDetails: ");
|
||||
assert.equal(details, "adapter exited 1");
|
||||
// The long token before the error is redacted as a whole: it shows, if at all, as one [redacted].
|
||||
assert.match(cause, /^(?:\[redacted\] )?API Error: 500 boom evil /);
|
||||
assert.ok(Array.from(cause).length <= 300, cause.length);
|
||||
assert.equal(cause.includes("www"), false, "the long text before the error is not shown");
|
||||
assert.doesNotMatch(hostile, /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/u, "no control or format character but the one separating newline");
|
||||
for (const bad of ["pw@", "example.com", "key=abc", "mail@", "/home/someone", "abc.def", "sk-ant", "msk-abcdef", "eyJhbGciOi", "AbCdEf0123456789XyZ"]) assert.equal(hostile.includes(bad), false, bad);
|
||||
assert.equal(leak, "The turn failed: the error text held a secret, so it isn't shown. Check Settings > Model setup.\nDetails: adapter exited 1");
|
||||
assert.equal(quiet, "The turn failed: adapter exited 1");
|
||||
for (const line of [...ctx.inbox.map(m => m.body), r.stderr()]) assert.equal(line.replace(/\s|\u200b/g, "").includes(secret), false);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("r127 an adapter whose own command is missing names it; a 127 with no such line keeps the bare reason", async t => {
|
||||
const ctx = await setup(t);
|
||||
const adapter = join(ctx.dir, "adapter.sh");
|
||||
@@ -394,7 +451,8 @@ for (const [harness, exit, activity] of [['claude-code', 1, false], ['claude-cod
|
||||
const r = startRunner(ctx.runDir, ctx.cap, { MOSAIC_MODEL_ACTIVITY_SOURCE: 'adapter' });
|
||||
t.after(async () => { r.child.kill('SIGTERM'); await r.exited; });
|
||||
const reply = await ask(ctx);
|
||||
if (exit) assert.match(reply.body, /The turn failed: adapter exited 1/);
|
||||
// #1873 chat-fail F1: the error text on stdout is the turn's plain cause.
|
||||
if (exit) assert.equal(reply.body, 'The turn failed: API Error: 400 synthetic-result\nDetails: adapter exited 1');
|
||||
else assert.equal(reply.body, 'API Error: 400 synthetic-result');
|
||||
const marker = join(ctx.runDir, 'proxy-first-output');
|
||||
assert.equal(existsSync(marker), activity);
|
||||
|
||||
@@ -10,7 +10,8 @@ import { chmodSync, cpSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeF
|
||||
import { join } from "node:path";
|
||||
import { BundleError, buildBundle, readSkills, SKILL_BYTES } from "../src/bundle.mjs";
|
||||
import { adapterEnv } from "../src/runner.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from "./helpers.mjs";
|
||||
import { HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch, harnessReady } from "./helpers.mjs";
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
|
||||
const sha = (text) => createHash("sha256").update(text).digest("hex");
|
||||
const MARKED = /<skill-file skill="([^"]+)" path="([^"]+)">\n([\s\S]*?)\n<\/skill-file>/g;
|
||||
@@ -183,7 +184,8 @@ test("each adapter passes the skills only in the prompt file, with skill discove
|
||||
const b = buildBundle({ dir: join(dir, "bundle"), resolved, contract: "# Contract\n", harness: HARNESS[harness], models, skillsDir: REPO_SKILLS, session: { ...s, run: "run-1", launchedBy: "pm" } });
|
||||
s.bundle = b.files;
|
||||
s.harnessEnv = b.env;
|
||||
const env = { ...adapterEnv(s, { PATH: `${join(dir, "bin")}:/usr/bin:/bin`, HOME: join(dir, "home") }), ARGV_OUT: join(dir, "argv"), MOSAIC_REQUEST: "x" };
|
||||
// #1873 S2: the pi adapter runs MOSAIC_PI_BIN, which the bundle sets to the pi it found.
|
||||
const env = { ...adapterEnv(s, { PATH: `${join(dir, "bin")}:/usr/bin:/bin`, HOME: join(dir, "home") }), ARGV_OUT: join(dir, "argv"), MOSAIC_REQUEST: "x", ...(harness === "pi" ? { MOSAIC_PI_BIN: cli } : {}) };
|
||||
const r = spawnSync("/bin/sh", [join(REPO, "adapters", harness === "pi" ? "pi" : "claude", "adapter.sh")], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env });
|
||||
assert.equal(r.status, 0, `${harness}: ${r.stderr}`);
|
||||
const argv = readFileSync(join(dir, "argv"), "utf8").split("\0");
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// #1873 chat-fail F1: the plain cause of a failed turn, from the harness's error text.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { CAUSE_MAX, PLAIN, WITHHELD, cleanText, failureBody, secretValues, turnCause } from "../src/failure-notice.mjs";
|
||||
|
||||
test("the three recognised causes map to a fixed plain line that carries none of the error's words", () => {
|
||||
for (const text of ["Claude AI usage limit reached|1700000000", "You've hit your limit \u00b7 resets 3pm (UTC)",
|
||||
"5-hour limit reached \u2219 resets 9pm", "Credit balance is too low", '{"error":{"type":"insufficient_quota"}}', "Quota exceeded for this account"])
|
||||
assert.equal(turnCause(text), PLAIN.usage, text);
|
||||
for (const text of ["OAuth token has expired. Please obtain a new token or refresh your existing token.", "Invalid API key \u00b7 Please run /login",
|
||||
'API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}', "Not logged in"])
|
||||
assert.equal(turnCause(text), PLAIN.signin, text);
|
||||
for (const text of ["There's an issue with the selected model (some-model). It may not exist or you may not have access to it.",
|
||||
'{"error":{"type":"not_found_error","message":"model: some-model"}}', "model_not_found", "The model some-model does not exist"])
|
||||
assert.equal(turnCause(text), PLAIN.model, text);
|
||||
// Other limits are not the account's usage.
|
||||
for (const text of ["Context limit reached \u00b7 /compact or /clear to continue", "output limit reached"])
|
||||
assert.notEqual(turnCause(text), PLAIN.usage, text);
|
||||
for (const line of Object.values(PLAIN)) assert.doesNotMatch(line, /\u2014/, "no em dash in UI text");
|
||||
});
|
||||
|
||||
test("no text, or text that is only controls or one long token, gives no cause", () => {
|
||||
for (const text of [undefined, null, "", " \n\t", "\u0000\u001b[0m\u200b", "x".repeat(5000)]) assert.equal(turnCause(text), null, JSON.stringify(text));
|
||||
});
|
||||
|
||||
test("control, format and separator characters go and the cause is capped", () => {
|
||||
assert.equal(cleanText("a\u0000b\u0007c\u001b[1;31md\u001b]0;title\u0007e\u007ff\u0085g\u2028h\u2029i\u202ej\u2066k\u200bl\ufeffm\tn\r\no"), "a b cde f g h ijklm n o");
|
||||
const long = turnCause("word ".repeat(400));
|
||||
assert.ok(Array.from(long).length <= CAUSE_MAX && long.endsWith("..."), long.length);
|
||||
// Astral characters are cut whole, never into a lone surrogate.
|
||||
const astral = turnCause("\u{1f600}".repeat(400));
|
||||
assert.equal(/[\ud800-\udfff]/u.test(astral.replace(/\u{1f600}/gu, "")), false);
|
||||
});
|
||||
|
||||
test("secrets, links, emails, paths and key-like runs never reach the cause", () => {
|
||||
const secret = "s3cr3t-value-for-the-fixture";
|
||||
const secrets = secretValues({ MOSAIC_MODEL_KEY: secret, MOSAIC_PROXY_TOKEN: "tok-0123456789", PATH: "/usr/bin:/bin", SHORT_KEY: "abc" });
|
||||
assert.deepEqual(secrets, [secret, "tok-0123456789"]);
|
||||
for (const text of [`boom ${secret}`, `boom ${secret.slice(0, 9)}\n${secret.slice(9)}`, `boom ${secret.slice(0, 5)}\u200b${secret.slice(5)}`, `boom ${secret.slice(0, 5)}\u0000${secret.slice(5)}`])
|
||||
assert.equal(turnCause(text, secrets), WITHHELD, JSON.stringify(text));
|
||||
const shown = turnCause("API Error: 500 at https://user:[email protected]/a?token=zz and www.host.example/q, [email protected], /home/u/.config/mosaic-dev/x ~/x ./y "
|
||||
+ "Bearer abc.def Authorization: Basic Zm9v api_key=k1 token: k2 sk-ant-api03-k3 ghp_k4 xoxb-k5 eyJa.b.c " + "A1".repeat(10) + " " + "z".repeat(40), secrets);
|
||||
for (const bad of ["user:pw", "host.example", "token=zz", "ops@", "/home/u", "~/x", "./y", "abc.def", "Zm9v", "k1", "k2", "sk-ant", "ghp_", "xoxb", "eyJa", "A1A1", "zzzz"])
|
||||
assert.equal(shown.includes(bad), false, `${bad} in ${shown}`);
|
||||
assert.match(shown, /^API Error: 500 at \[redacted\]/);
|
||||
});
|
||||
|
||||
test("the chat body puts the plain cause first and the technical reason after", () => {
|
||||
assert.equal(failureBody({ reason: "adapter exited 1", cause: PLAIN.usage }), `The turn failed: ${PLAIN.usage}\nDetails: adapter exited 1`);
|
||||
assert.equal(failureBody({ reason: "adapter exited 1" }), "The turn failed: adapter exited 1");
|
||||
});
|
||||
|
||||
test("review round 1: quoted keys, short or letters-only values and a space separator are redacted", () => {
|
||||
for (const [text, value] of [['{"error":"bad","password":"hunter2hunte"}', "hunter2hunte"], ['{"api_key":"abcdefghijklmno"}', "abcdefghijklmno"],
|
||||
['auth failed for key "Zq8xPw2LmN4"', "Zq8xPw2LmN4"], ["token abcd1234efgh567 rejected", "abcd1234efgh567"],
|
||||
["secret qwertyuiopasdfghjklzxcvbnmqwer", "qwertyuiop"], ['{"access_token":"shortvalue1"}', "shortvalue1"], ["client_secret=abc", "abc"]]) {
|
||||
const shown = turnCause(text);
|
||||
assert.ok(shown === null || !shown.includes(value), `${value} in ${shown}`);
|
||||
}
|
||||
// Ordinary words after "key" or "session" are left alone.
|
||||
assert.equal(turnCause("API Error: 500 the key point is the session ended"), "API Error: 500 the key point is the session ended");
|
||||
});
|
||||
|
||||
test("review round 1: encoded emails, Windows and UNC paths and encoded env secrets never reach the cause", () => {
|
||||
for (const [text, bad] of [["mail jason%40example.com", "example"], ["mail jason%2540example.com", "example"], ["mail jason\uff20example.com", "example"],
|
||||
["mail jason@example.com", "example"], ["read C:\\Users\\jason\\.claude\\creds.json", "jason"], ["read \\\\server\\share\\creds", "server"]]) {
|
||||
const shown = turnCause(text);
|
||||
assert.ok(shown === null || !shown.includes(bad), `${bad} in ${shown}`);
|
||||
}
|
||||
const secrets = secretValues({ MOSAIC_PROXY_KEY: "pxy_0123456789abcd" });
|
||||
for (const text of ["boom pxy%5F0123456789abcd", "boom pxy_0123456789abcd", "boom pxy_0123456789abcd", "boom pxy_01234\u030156789abcd", "boom \uff50xy_0123456789abcd"])
|
||||
assert.equal(turnCause(text, secrets), WITHHELD, JSON.stringify(text));
|
||||
});
|
||||
|
||||
test("review round 1: a long output is read from its end, so an answer that talks about limits is not the cause", () => {
|
||||
const cause = turnCause("Here is how limits work: usage limit reached means wait. " + "x ".repeat(1500) + "Error: adapter crashed: segfault");
|
||||
assert.notEqual(cause, PLAIN.usage);
|
||||
assert.match(cause, /segfault$/);
|
||||
assert.equal(turnCause("y ".repeat(1500) + "Claude AI usage limit reached"), PLAIN.usage);
|
||||
});
|
||||
|
||||
// Review round 2: the tail cut can land between a key word and its value. Redaction runs
|
||||
// before the cut, so the value is still redacted with its key word gone.
|
||||
test("review round 2: a tail cut between a key word and its value never shows the value", () => {
|
||||
for (const [key, value] of [["password:", "Zq8xPw2LmN"], ["Bearer", "Zq8xPw2LmN"], ['"api_key":', '"Zq8xPw2LmN"'], ["token", "Zq8xPw2LmN4"]]) {
|
||||
// The last 2000 characters start just before the value, so the cut parts it from its key
|
||||
// word; a near miss on either side is checked too.
|
||||
for (let shift = -2; shift <= 2; shift++) {
|
||||
const end = " then the adapter crashed";
|
||||
const head = ` ${value} https://e.example/`;
|
||||
const tail = head + "a".repeat(2000 - head.length - end.length + shift) + end;
|
||||
const cause = turnCause("w ".repeat(300) + key + tail);
|
||||
assert.ok(cause !== null && !cause.includes("Zq8xPw2LmN"), `${key} shift ${shift}: ${cause}`);
|
||||
assert.match(cause, /then the adapter crashed$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Review round 3: redaction runs over the whole kept stdout (up to 128000 characters), so a long
|
||||
// run with no spaces (base64, a data URI, minified JSON) must not make it slow.
|
||||
test("review round 3: a 128000-character run with no spaces is redacted in well under a second", () => {
|
||||
const N = 128000;
|
||||
for (const run of ["a".repeat(N), "a.".repeat(N / 2), "a-".repeat(N / 2), "a/".repeat(N / 2), "a:".repeat(N / 2), 'a"'.repeat(N / 2)]) {
|
||||
const started = performance.now();
|
||||
const cause = turnCause(`${run} then the adapter crashed`);
|
||||
const took = performance.now() - started;
|
||||
assert.ok(took < 1000, `${run.slice(0, 4)}... took ${Math.round(took)} ms`);
|
||||
assert.match(cause, /then the adapter crashed$/);
|
||||
}
|
||||
});
|
||||
// Review round 3: a long text that redacts down below the read limit isn't cut, so its first word stays.
|
||||
test("review round 3: a long text that redaction makes short keeps its first word", () => {
|
||||
assert.equal(turnCause(`Crash: adapter died at https://e.example/${"a".repeat(2500)}`), "Crash: adapter died at [redacted]");
|
||||
});
|
||||
@@ -9,7 +9,8 @@ import { join } from "node:path";
|
||||
// A namespace import, so the red-before test runs (and fails on its assertion) on a base without
|
||||
// the section's exports.
|
||||
import * as bundleModule from "../src/bundle.mjs";
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch } from "./helpers.mjs";
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch, harnessReady } from "./helpers.mjs";
|
||||
await harnessReady(); // #1873 re-check 7: buildBundle reads a passed fit check
|
||||
import { REPO_ROLES } from "../../organization/tests/helpers.mjs";
|
||||
|
||||
const { buildBundle, sessionModel } = bundleModule;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"version": "8.0.42",
|
||||
"version": "8.0.79",
|
||||
"archive": {
|
||||
"asset": "CLIProxyAPI_8.0.42_linux_amd64.tar.gz",
|
||||
"url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v8.0.42/CLIProxyAPI_8.0.42_linux_amd64.tar.gz",
|
||||
"sha256": "1e10566fe0042ed5a9b80306cf296bf86a83de590cd967a8b177988b896c8d31"
|
||||
"asset": "CLIProxyAPI_8.0.79_linux_amd64.tar.gz",
|
||||
"url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v8.0.79/CLIProxyAPI_8.0.79_linux_amd64.tar.gz",
|
||||
"sha256": "7cbb9709ed939ff3684e10592a45cc538ee82d5da759daa7e18c7e1dc3b32acd"
|
||||
},
|
||||
"binary": {
|
||||
"sha256": "74661f8cf949977870231359e8bf4344e07946766a673c08fa25a3e5f72fc95e"
|
||||
"sha256": "4968bd27b04f813849add020b95a26dc7abf3e30810b97d291c0d88f495fe601"
|
||||
},
|
||||
"panel": {
|
||||
"version": "1.26.7",
|
||||
|
||||
@@ -56,8 +56,28 @@ uses a new temp root and private network namespace, with made-up credentials,
|
||||
and calls the page's bus verbs. If the page cannot pass against the new PIN,
|
||||
the upgrade stops; Sage takes Q46's fallback to Jason through Mos.
|
||||
|
||||
A running instance takes a new PIN in three steps, in this order. First run
|
||||
the new code: update the checkout or pinned copy the bus, Console and proxy
|
||||
unit start from. The proxy unit runs `run.mjs` and reads `PIN` from the tree
|
||||
it was installed from (`systemctl --user cat <unit>` shows it). If the new
|
||||
code is in that same tree, a restart picks it up. If it is in another tree,
|
||||
the unit keeps the old PIN until it is installed again from the new tree:
|
||||
stop it, remove its unit file, then `mosaic proxy unit install` from the new
|
||||
tree, because install never replaces a unit. Then run `mosaic proxy fetch` (or Fetch on the Console's
|
||||
Model setup page), which installs the new release beside the old one
|
||||
under `<dataRoot>/opt/cliproxyapi/<version>/`. Then restart the proxy with
|
||||
`mosaic proxy unit restart`. Before the fetch, the proxy fails to start with
|
||||
`proxy-install-missing`, and keeps failing until the fetch is done. Restart the bus and
|
||||
Console as well so their status and Fetch use the new PIN. `proxy.json` keeps
|
||||
the path from the PIN it was created under. That path stays valid, and the
|
||||
proxy always runs the hash-verified install for the current PIN. Signed-in
|
||||
accounts in `<dataRoot>/proxy/auth/` carry over. From 8.0.55 the proxy also
|
||||
keeps a `kv.db` file in that directory, and 8.0.79 adds a `.codex-refresh/`
|
||||
directory there once a Codex account renews. The old release directory can be
|
||||
removed once the new one runs.
|
||||
|
||||
The native `/proxy` page uses human-only bus verbs; only the bus holds the
|
||||
management client. On PIN 8.0.42, OAuth credentials are listed under
|
||||
management client. On PIN 8.0.79, OAuth credentials are listed under
|
||||
`/v8/management/credentials` and priority is patched as `{name, priority}`.
|
||||
API-key groups are absent from that list: z.ai keys use the Claude-compatible
|
||||
provider configuration at `/v8/management/config/api-keys/claude`, whose keys
|
||||
@@ -128,7 +148,7 @@ follow-up; do not run those writers concurrently with organization buses.
|
||||
|
||||
### Setup from the Console (#1873)
|
||||
|
||||
Settings > Model proxy has a Proxy setup panel for the instance owner: the
|
||||
Settings > Model setup (route `#/settings/model-proxy`) has a Proxy setup panel for the instance owner: the
|
||||
`--dev-local-owner` owner on a dev Console, or the root owner under `--sso`.
|
||||
Agents, testers and grant holders get `human-required` on every setup route,
|
||||
read or write. The panel shows the release (pinned version, hashes verified),
|
||||
|
||||
@@ -2,18 +2,85 @@
|
||||
// `mosaic proxy status|unit|init-lock|fence clear --restart`. Host actions run here; init and
|
||||
// the fence clear go to the bus, which decides them. Results and receipts carry labels, key IDs
|
||||
// and process ids only: never a key, token, absolute path or upstream text.
|
||||
import fs from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { fetchPinned } from './fetch.mjs';
|
||||
import { PIN } from './common.mjs';
|
||||
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, createUnitControl, FILE_LABELS } from './admin.mjs';
|
||||
import { localRide, riddenOrgs } from './ride.mjs';
|
||||
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, receiptsText, createUnitControl, FILE_LABELS, LOG_LINES, receiptHistory, serviceKeyState } from './admin.mjs';
|
||||
import { secretValues } from './redact.mjs';
|
||||
import { discoverModules, hasModule } from '../../plugins/src/loader.mjs';
|
||||
import { readPluginLock } from '../../plugins/src/pinned.mjs';
|
||||
import { PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
|
||||
const failure = code => Object.assign(new Error(code), { code });
|
||||
|
||||
// #1873 settings-backend A2: the harness programs installed on this instance, from the plugin tree
|
||||
// through the plugins loader and from the instance's plugin lock, the way the bus lists them
|
||||
// (runtime.mjs harnessLevels). No name list here. A tree that cannot be read answers null; a lock
|
||||
// that cannot be read adds nothing, so a pinned program is then not offered.
|
||||
export function installedHarnesses(dataRoot = null) {
|
||||
let names;
|
||||
try { names = discoverModules('harness').names.filter(name => hasModule('harness', name)); } catch { return null; }
|
||||
if (dataRoot !== null) {
|
||||
try { names = [...new Set([...names, ...Object.keys(readPluginLock(dataRoot).plugins).filter(name => hasModule('harness', name, dataRoot))])]; } catch { /* the tree's list */ }
|
||||
}
|
||||
return names.sort();
|
||||
}
|
||||
|
||||
// #1873 settings-backend A2: every harness an organization document names for an agent: each
|
||||
// `harness` or `fallback.harness` string anywhere in it (role vars, project agent vars, or any
|
||||
// later place), outside its plugins list. Broader than the routes view on purpose: a program is
|
||||
// never turned off where anything in the file still names it.
|
||||
export function harnessesNamed(document) {
|
||||
const named = new Set();
|
||||
const walk = (value, depth) => {
|
||||
if (depth > 32 || value === null || typeof value !== 'object') return;
|
||||
if (Array.isArray(value)) { for (const item of value) walk(item, depth + 1); return; }
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if ((key === 'harness' || key === 'fallback.harness') && typeof item === 'string') named.add(item);
|
||||
else walk(item, depth + 1);
|
||||
}
|
||||
};
|
||||
if (document === null || typeof document !== 'object' || Array.isArray(document)) return null;
|
||||
for (const [key, value] of Object.entries(document)) if (key !== 'plugins') walk(value, 1);
|
||||
return named;
|
||||
}
|
||||
|
||||
// #1873 settings-backend A2 (review P1-1): the harnesses the root agents an organization takes name.
|
||||
// `root` is what loadRootAgents answered ({state, agents, assistant, definitions?}). An organization
|
||||
// takes every root agent except the root assistant and the ones that exclude it, the way
|
||||
// materializeCopies copies them at bus boot. Anything not in that shape answers null (unreadable).
|
||||
export function rootHarnessesNamed(root, orgId) {
|
||||
if (root === null || typeof root !== 'object' || root.agents === null || typeof root.agents !== 'object' || Array.isArray(root.agents)) return null;
|
||||
const taken = {};
|
||||
for (const [name, entry] of Object.entries(root.agents)) {
|
||||
if (entry === null || typeof entry !== 'object' || !Array.isArray(entry.excludeOrgs)) return null;
|
||||
if (entry.definition === 'assistant' || entry.excludeOrgs.includes(orgId)) continue;
|
||||
taken[name] = entry.vars ?? {};
|
||||
}
|
||||
return harnessesNamed({ agents: taken, definitions: root.definitions ?? {} });
|
||||
}
|
||||
// A key id is the first 12 hex of the key's sha256. A label is a short plain name; anything that
|
||||
// looks like a Mosaic key prefix is dropped, so an answer can never carry key text.
|
||||
const KEY_ID = /^[a-f0-9]{12}$/;
|
||||
const plainLabel = value => (typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(value) && !/ms[kotp][-_]/i.test(value) ? value : null);
|
||||
const isoTime = value => (typeof value === 'string' && /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]{1,18}Z$/.test(value) ? value : null);
|
||||
|
||||
// `buses()` proves the init-lock condition "bus stopped" ({stopped, running:[label]}).
|
||||
// `orgs()` lists the organizations this proxy serves: [{id, catalogue}]. `unit` and `fetch` are
|
||||
// (and `pin`) seams for tests; the defaults run the real proxy-service.sh, systemctl and pinned fetch.
|
||||
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], now = () => new Date(), env = process.env, pin = PIN }) {
|
||||
// #1873 ride-default: `riders()` lists the owner's active organizations for Ride all, read locally:
|
||||
// [{id, fixture, cliproxy, changes, call, status}] where `changes` is the text of the organization's
|
||||
// change log, `call(verb, args)` reaches its bus as the owner and `status()` is its bus status. `ownerModels()` answers
|
||||
// {proxy, riding, models} from the riding buses' catalogues. `move(id, models, principal)` moves a
|
||||
// stopped fixture organization to the owner's models through the organization service.
|
||||
// #1873 settings-backend A2: a rider may also have `file()`, its organization file as the writer
|
||||
// reads it ({document, revision}), read only. `harnesses()` lists the installed harness programs.
|
||||
// `rootAgents()` reads the root agent file (loadRootAgents); with none given, or one that throws,
|
||||
// no organization that has the program on is written (unreadable).
|
||||
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN, providers = PROVIDERS }) {
|
||||
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
|
||||
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
|
||||
let job = { state: 'idle', step: null, receipt: null, error: null };
|
||||
@@ -30,6 +97,143 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
async function unitStatus() {
|
||||
try { return await control.status(); } catch (error) { return { unit: control.unit, installed: false, active: 'unknown', healthy: false, error: proxyCode(error, 'proxy-unit-failed') }; }
|
||||
}
|
||||
// The organizations this proxy's own receipts show cliproxy was or may have been on (riddenOrgs).
|
||||
// No receipt file yet is none; a file that fails receiptsText's check, or holds a line that does
|
||||
// not parse, is null, and localRide skips every organization without cliproxy as unreadable.
|
||||
function ridden() {
|
||||
const ids = riddenOrgs(receiptsText(dataRoot));
|
||||
return id => (ids === null ? null : ids.has(id));
|
||||
}
|
||||
const decide = (rider, wasRidden) => localRide({ ...rider, ridden: wasRidden(rider.id) });
|
||||
// Stopped is the organization admin page's test (org-admin bus stop): a bus status with no
|
||||
// process id. A status that cannot be read, or a rider with no status, is not stopped.
|
||||
async function stopped(rider) {
|
||||
if (typeof rider.status !== 'function') return false;
|
||||
try { return !Number.isSafeInteger((await rider.status())?.pid); } catch { return false; }
|
||||
}
|
||||
const failCode = error => (/^[a-z][a-z-]{0,63}$/.test(error?.code ?? '') ? error.code : 'failed');
|
||||
// Ride all, one organization: the local rules first, then the organization's bus, which must
|
||||
// answer and must hold the proxy client. The bus decides the write (plugins.set) as it would
|
||||
// for the owner on the Settings page. The answer names a reason, never bus or upstream text.
|
||||
// A ride-intent receipt is on disk before plugins.set is sent; with no receipt there is no write.
|
||||
// When plugins.set fails and the bus then shows no cliproxy, a ride-not-added receipt clears that
|
||||
// intent. Any other failure leaves it: the add may have happened.
|
||||
async function rideOne(rider, wasRidden) {
|
||||
const id = rider.id, local = decide(rider, wasRidden);
|
||||
// settings-p3 (R2): with no bus status (the single-business Console) whether its bus runs is unknown (null).
|
||||
if (local === 'fixture') return { id, outcome: 'fixture', running: typeof rider.status === 'function' ? !(await stopped(rider)) : null };
|
||||
if (local !== 'ready') return { id, outcome: local === 'already' ? 'already' : 'skipped', reason: local };
|
||||
let current;
|
||||
try { current = await rider.call('plugins'); } catch { return { id, outcome: 'skipped', reason: 'bus-down' }; }
|
||||
try { await rider.call('proxy.accounts'); } catch (error) { return { id, outcome: 'skipped', reason: error?.code === 'not-configured' ? 'no-proxy-client' : 'proxy-check-failed' }; }
|
||||
const providers = Array.isArray(current?.plugins?.['model-provider']) ? current.plugins['model-provider'] : [];
|
||||
if (providers.includes('cliproxy')) return { id, outcome: 'already' };
|
||||
// The organization (its file and change log) and the receipts are read again here: an add and
|
||||
// remove saved on its Settings page, or a removal saved while this run worked on earlier
|
||||
// organizations, is on file now, and the decision above came from the run's first read
|
||||
// (settings-p3 R1). A read that fails, or an organization no longer listed, is skipped as unreadable.
|
||||
let fresh;
|
||||
try { fresh = (await riders()).find(r => r?.id === id); } catch { fresh = null; }
|
||||
if (!fresh) return { id, outcome: 'skipped', reason: 'unreadable' };
|
||||
const again = decide(fresh, ridden());
|
||||
if (again === 'already') return { id, outcome: 'already' };
|
||||
if (again !== 'ready') return { id, outcome: 'skipped', reason: again };
|
||||
try { receipt({ op: 'ride-intent', org: id }); } catch { return { id, outcome: 'skipped', reason: 'not-recorded' }; }
|
||||
try { await rider.call('plugins.set', { revision: current.revision, plugins: { 'model-provider': [...providers, 'cliproxy'] } }); }
|
||||
catch (error) {
|
||||
try {
|
||||
const after = await rider.call('plugins');
|
||||
if (Array.isArray(after?.plugins?.['model-provider']) && !after.plugins['model-provider'].includes('cliproxy')) receipt({ op: 'ride-not-added', org: id });
|
||||
} catch { /* unknown outcome: the intent stands */ }
|
||||
return { id, outcome: 'failed', reason: failCode(error) };
|
||||
}
|
||||
return { id, outcome: 'added' };
|
||||
}
|
||||
async function rideSummary() {
|
||||
// settings-p3 (review P3-3): a stand-in organization with no bus status (the single-business
|
||||
// Console) can't be moved; running null says so before any Ride all run.
|
||||
try {
|
||||
const wasRidden = ridden();
|
||||
return (await riders()).map(r => { const state = decide(r, wasRidden); return state === 'fixture' && typeof r.status !== 'function' ? { id: r.id, state, running: null } : { id: r.id, state }; });
|
||||
} catch { return null; }
|
||||
}
|
||||
// #1873 settings-backend A2, item 5: which harness programs each organization has on, from its
|
||||
// bus's plugins read as the owner. null when the read fails, its answer has no harness list, or
|
||||
// any entry is not a plugin name (review P3-3: no bus text reaches the page).
|
||||
const harnessList = value => (Array.isArray(value?.plugins?.harness) && value.plugins.harness.every(n => typeof n === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(n)) ? [...value.plugins.harness] : null);
|
||||
async function programsSummary() {
|
||||
let installed = null;
|
||||
try { installed = harnesses(); if (!Array.isArray(installed)) installed = null; } catch { installed = null; }
|
||||
let list;
|
||||
try { list = await riders(); } catch { return { installed, organizations: null }; }
|
||||
const organizations = await Promise.all(list.map(async rider => {
|
||||
try { return { id: rider.id, on: harnessList(await rider.call('plugins')) }; } catch { return { id: rider.id, on: null }; }
|
||||
}));
|
||||
return { installed, organizations };
|
||||
}
|
||||
// Item 5, one organization: turn `name` off unless something still uses it or it is the only one.
|
||||
// Three reads (the plugins read, the routes view and the organization file) must show one revision;
|
||||
// the write carries it, so a change after them is refused by the writer (revision-conflict) and
|
||||
// reported, never retried. Every skip writes nothing. `root` is the root agent file read once per
|
||||
// call (undefined when it could not be read): the root agents this organization takes count too.
|
||||
async function offOne(rider, name, root) {
|
||||
const id = rider.id;
|
||||
let current;
|
||||
try { current = await rider.call('plugins'); } catch { return { id, outcome: 'bus-down' }; }
|
||||
const on = harnessList(current);
|
||||
if (on === null || typeof current?.revision !== 'string' || !/^[a-f0-9]{64}$/.test(current.revision)) return { id, outcome: 'unreadable' };
|
||||
if (!on.includes(name)) return { id, outcome: 'already-off' };
|
||||
let routes = null;
|
||||
try { routes = await rider.call('routes'); } catch (error) { if (error?.code !== 'launch-not-configured') return { id, outcome: 'unreadable' }; }
|
||||
let file;
|
||||
try { file = typeof rider.file === 'function' ? await rider.file() : null; } catch { file = null; }
|
||||
const named = harnessesNamed(file?.document);
|
||||
const fromRoot = root === undefined ? null : rootHarnessesNamed(root, id);
|
||||
if (named === null || fromRoot === null || typeof file?.revision !== 'string') return { id, outcome: 'unreadable' };
|
||||
for (const harness of fromRoot) named.add(harness);
|
||||
if (file.revision !== current.revision || (routes !== null && routes?.revision !== current.revision)) return { id, outcome: 'failed:revision-conflict' };
|
||||
// The routes view must be readable when there is one; each instance's route and fallback count.
|
||||
if (routes !== null) {
|
||||
if (!routes || typeof routes.instances !== 'object' || routes.instances === null) return { id, outcome: 'unreadable' };
|
||||
for (const route of Object.values(routes.instances)) {
|
||||
if (typeof route?.harness === 'string') named.add(route.harness);
|
||||
if (typeof route?.fallback?.harness === 'string') named.add(route.fallback.harness);
|
||||
}
|
||||
}
|
||||
// The harness rule: any route on this program, whatever account its model uses, keeps it on.
|
||||
if (named.has(name)) return { id, outcome: 'in-use' };
|
||||
if (on.length === 1) return { id, outcome: 'last-program' };
|
||||
try { await rider.call('plugins.set', { revision: current.revision, plugins: { harness: on.filter(n => n !== name) } }); }
|
||||
catch (error) { return { id, outcome: `failed:${failCode(error)}` }; }
|
||||
return { id, outcome: 'off' };
|
||||
}
|
||||
// Item 8, one organization: its proxy client keys by key id, from proxy.keys as the owner. Never
|
||||
// the usage queue. A key value never reaches here: proxy.keys answers ids, and every other field
|
||||
// is checked against a plain pattern before it is passed on.
|
||||
async function accessOne(rider) {
|
||||
const id = rider.id;
|
||||
if (typeof rider.fixture !== 'boolean' || typeof rider.cliproxy !== 'boolean') return { id, health: 'unreadable', reason: 'unreadable', keys: [] };
|
||||
if (rider.fixture || !rider.cliproxy) return { id, health: 'not-riding', keys: [] };
|
||||
let answer;
|
||||
try { answer = await rider.call('proxy.keys'); }
|
||||
catch (error) {
|
||||
const code = error?.code;
|
||||
if (code === 'proxy-uncertain') return { id, health: 'attention', reason: 'proxy-uncertain', keys: [] };
|
||||
const reason = code === 'not-configured' ? 'no-proxy-client' : code === 'outcome-unknown' || code === 'no-bus-host' ? 'bus-down' : 'unreadable';
|
||||
return { id, health: 'unreadable', reason, keys: [] };
|
||||
}
|
||||
if (!Array.isArray(answer?.keys)) return { id, health: 'unreadable', reason: 'unreadable', keys: [] };
|
||||
const keys = [];
|
||||
let other = 0, sentinel = 0;
|
||||
for (const key of answer.keys) {
|
||||
if (!key || typeof key !== 'object' || !KEY_ID.test(key.keyId ?? '')) return { id, health: 'unreadable', reason: 'unreadable', keys: [] };
|
||||
if (key.management === 'sentinel') sentinel++;
|
||||
else if (key.management === 'stack-managed') keys.push({ keyId: key.keyId, agent: plainLabel(key.agent), state: plainLabel(key.state), issuedAt: isoTime(key.issuedAt) });
|
||||
else other++;
|
||||
}
|
||||
const health = keys.length === 0 ? 'missing' : keys.every(k => k.state === 'active') ? 'ok' : 'attention';
|
||||
return { id, health, keys, other, sentinel };
|
||||
}
|
||||
function nextSteps({ release, init, unitState, fence, lock }) {
|
||||
if (!release.fetched || release.problem) return ['fetch'];
|
||||
if (lock.present) return lock.clearable ? ['init-lock-clear'] : ['init-lock-wait'];
|
||||
@@ -54,6 +258,11 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
const lock = init.lock ? initLockStatus({ configDir, dataRoot, buses: await buses() }) : { present: false, clearable: false, blockers: [] };
|
||||
let organizations = null;
|
||||
try { organizations = await orgs(); } catch { organizations = null; }
|
||||
const ride = await rideSummary();
|
||||
const programs = await programsSummary();
|
||||
const next = nextSteps({ release, init, unitState, fence, lock });
|
||||
// Ride all comes after the proxy runs with no fence, while an organization can still ride.
|
||||
if (next[0] === 'accounts' && ride?.some(r => r.state === 'ready' || r.state === 'fixture')) next.push('ride-all');
|
||||
return {
|
||||
release: { version: release.version, panelVersion: release.panelVersion, fetched: release.fetched, verified: release.verified, problem: release.problem },
|
||||
init: {
|
||||
@@ -65,13 +274,17 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
initLock: lock,
|
||||
fetch: fetchJob,
|
||||
restart: restarted ? { confirmed: true, observedAt: restarted.observedAt, pid: restarted.after.pid } : null,
|
||||
// #1873 settings-backend-a3: the page's provider select, from the plugin. Id, label and sign-in kind only.
|
||||
providers: publicProviders(providers),
|
||||
busy,
|
||||
receipts: recentReceipts(dataRoot),
|
||||
organizations,
|
||||
// Ruling 8: the system config holds one proxy per instance; an organization's own proxy
|
||||
// needs a config format that does not exist yet.
|
||||
ownProxy: { available: false, state: 'not built', reason: 'This instance has one shared proxy. A separate proxy per organization is not built yet.' },
|
||||
next: nextSteps({ release, init, unitState, fence, lock }),
|
||||
ride,
|
||||
programs,
|
||||
next,
|
||||
};
|
||||
},
|
||||
// Runs in the background; the page polls status for its step and receipt.
|
||||
@@ -133,6 +346,114 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
return { cleared: result.cleared === true, receipt: receipt({ op: 'fence.clear', cleared: result.cleared === true, evidence: result.evidence ?? null }) };
|
||||
});
|
||||
},
|
||||
// Ride all: adds cliproxy to each organization that can take it, and names every one it skips.
|
||||
// Fixture organizations are listed, not changed: moving one spends real tokens, so it is a
|
||||
// separate confirmed action (rideMove).
|
||||
async rideAll() {
|
||||
return exclusive('ride-all', async () => {
|
||||
const list = await riders(), wasRidden = ridden();
|
||||
const results = [];
|
||||
for (const rider of list) results.push(await rideOne(rider, wasRidden));
|
||||
const added = results.filter(r => r.outcome === 'added').map(r => r.id);
|
||||
const skipped = results.filter(r => r.outcome === 'skipped' || r.outcome === 'failed').map(r => ({ id: r.id, reason: r.reason }));
|
||||
const fixtures = results.filter(r => r.outcome === 'fixture').map(r => ({ id: r.id, running: r.running }));
|
||||
const already = results.filter(r => r.outcome === 'already').map(r => r.id);
|
||||
// Each add already left its ride-intent receipt, so a summary that cannot be written still
|
||||
// answers what happened, with no receipt.
|
||||
let summary = null;
|
||||
try { summary = receipt({ op: 'ride-all', added, skipped, fixtures: fixtures.map(f => f.id) }); } catch { summary = null; }
|
||||
return { added, already, skipped, fixtures, receipt: summary };
|
||||
});
|
||||
},
|
||||
// Moves one stopped fixture organization to the owner's models. Its bus is refused at start
|
||||
// beside a real proxy, so the organization service writes its document (the same whole-document
|
||||
// update the organization's admin page uses); the owner starts its bus afterwards.
|
||||
async rideMove({ org, principal } = {}) {
|
||||
return exclusive('ride-move', async () => {
|
||||
const rider = (await riders()).find(r => r.id === org);
|
||||
if (!rider) return { org, moved: false, reason: 'unknown' };
|
||||
const local = decide(rider, ridden());
|
||||
if (local !== 'fixture') return { org, moved: false, reason: local };
|
||||
// settings-p3 (R2): with no bus status (the single-business Console) its bus can't be shown
|
||||
// stopped, so stopping it would not help: moving is not available there.
|
||||
if (typeof rider.status !== 'function') return { org, moved: false, reason: 'not-available' };
|
||||
if (!(await stopped(rider))) return { org, moved: false, reason: 'bus-running' };
|
||||
if (typeof move !== 'function') return { org, moved: false, reason: 'not-available' };
|
||||
const owner = await ownerModels();
|
||||
if (owner?.proxy !== true) return { org, moved: false, reason: 'no-proxy' };
|
||||
if (owner.riding !== true) return { org, moved: false, reason: 'no-riding-bus' };
|
||||
let result;
|
||||
try { result = await move(org, owner.models, principal); }
|
||||
catch (error) { result = { moved: false, reason: failCode(error) }; }
|
||||
if (!result?.moved) return { org, moved: false, reason: result?.reason ?? 'failed' };
|
||||
return { org, moved: true, model: result.model, receipt: receipt({ op: 'ride-move', org, model: result.model }) };
|
||||
});
|
||||
},
|
||||
// The organization admin page calls this before it saves a document that drops cliproxy from
|
||||
// the model providers, and saves nothing when it throws. Ride all then leaves that organization off.
|
||||
rideRemoved(org) {
|
||||
if (typeof org !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(org)) throw failure('proxy-org-invalid');
|
||||
return receipt({ op: 'ride-removed', org });
|
||||
},
|
||||
// #1873 settings-backend A1: three reads for the instance owner's setup page.
|
||||
// The proxy unit's last journal lines, redacted. A unit that is not installed is not-configured;
|
||||
// a unit state that cannot be read is outcome-unknown, as is a journal that cannot be read.
|
||||
async log({ lines = LOG_LINES.default } = {}) {
|
||||
if (typeof control.log !== 'function') throw failure('not-configured');
|
||||
const state = await unitStatus();
|
||||
if (state.error) throw failure('outcome-unknown');
|
||||
if (!state.installed) throw failure('not-configured');
|
||||
return control.log(lines, { secrets: secretValues(env) });
|
||||
},
|
||||
// When the service key was made, from proxy.json's mtime; never the key or any part of it.
|
||||
serviceKey() { return serviceKeyState(configDir); },
|
||||
// The setup history, a page at a time (receiptHistory).
|
||||
history({ limit, before = null } = {}) { return receiptHistory(dataRoot, { limit, before, secrets: secretValues(env) }); },
|
||||
// An account change made through /api/proxy/* or an organization's /api/orgs/<id>/proxy/*,
|
||||
// recorded after its bus call answered. Labels only: the provider id, a 12-hex account id, a
|
||||
// priority or a model count, the organization whose route carried it, and the signed-in name.
|
||||
// Never a key, a login state, a callback URL, a model list or a body. Answers null when the verb
|
||||
// is not an account change, true when recorded and false when the append failed.
|
||||
recordAccount({ verb, args = {}, result = null, user = null, org = null } = {}) {
|
||||
const label = value => (typeof value === 'string' && /^[a-z0-9][a-z0-9._-]{0,31}$/.test(value) ? value : null);
|
||||
const account = value => (typeof value === 'string' && /^[a-f0-9]{12}$/.test(value) ? value : null);
|
||||
let record;
|
||||
if (verb === 'proxy.apikey.add') record = { op: 'account.proxy.apikey.add', provider: label(args.provider) };
|
||||
else if (verb === 'proxy.login.status' && result?.status === 'ok') record = { op: 'account.proxy.login.complete' };
|
||||
else if (verb === 'proxy.priority.set') record = { op: 'account.proxy.priority.set', accountId: account(args.accountId), priority: Number.isSafeInteger(args.priority) ? args.priority : null };
|
||||
else if (verb === 'proxy.group.models.set') record = { op: 'account.proxy.group.models.set', accountId: account(args.accountId), models: Array.isArray(args.models) ? args.models.length : null };
|
||||
else return null;
|
||||
if (typeof org === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(org)) record.org = org;
|
||||
if (typeof user === 'string' && user) record.user = user.slice(0, 64);
|
||||
try { receipt(record); return true; } catch { return false; }
|
||||
},
|
||||
// #1873 settings-backend A2, item 5: turns one harness program off for every current
|
||||
// organization that can do without it, through each organization's bus as the owner (the way
|
||||
// Ride all writes). Sequential, one organization at a time; one receipt names the outcome ids.
|
||||
async programsOff({ name, user = null } = {}) {
|
||||
return exclusive('programs', async () => {
|
||||
let installed;
|
||||
try { installed = harnesses(); } catch { installed = null; }
|
||||
if (typeof name !== 'string' || !Array.isArray(installed) || !installed.includes(name)) throw failure('invalid-request');
|
||||
const list = await riders();
|
||||
let root;
|
||||
try { root = typeof rootAgents === 'function' ? await rootAgents() : undefined; } catch { root = undefined; }
|
||||
const results = [];
|
||||
for (const rider of list) results.push(await offOne(rider, name, root));
|
||||
const record = { op: 'programs.off', name, results: results.map(r => ({ id: r.id, outcome: r.outcome })) };
|
||||
if (typeof user === 'string' && user) record.user = user.slice(0, 64);
|
||||
// Each write is the organization's own change log entry, so a receipt that cannot be
|
||||
// written still answers what happened, with no receipt.
|
||||
let written = null;
|
||||
try { written = receipt(record); } catch { written = null; }
|
||||
return { name, results, receipt: written };
|
||||
});
|
||||
},
|
||||
// #1873 settings-backend A2, item 8: each organization's proxy client keys and their health.
|
||||
async access() {
|
||||
const list = await riders();
|
||||
return { organizations: await Promise.all(list.map(rider => accessOne(rider).catch(() => ({ id: rider.id, health: 'unreadable', reason: 'unreadable', keys: [] })))) };
|
||||
},
|
||||
async initLockClear() {
|
||||
return exclusive('init-lock-clear', async () => ({ receipt: clearInitLock({ configDir, dataRoot, buses: await buses(), now }) }));
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ import { execFile } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { PIN, refuse } from './common.mjs';
|
||||
import { installPaths, loadProxy, verifyInstall } from './settings.mjs';
|
||||
import { holdsSecret, redactLine, redactValue } from './redact.mjs';
|
||||
|
||||
const REPO = fileURLToPath(new URL('../../../', import.meta.url)).replace(/\/$/, '');
|
||||
export const INSTANCE_NAME = /^[a-z][a-z0-9]{1,15}$/;
|
||||
@@ -107,6 +108,26 @@ export function appendReceipt(dataRoot, record) {
|
||||
return record;
|
||||
}
|
||||
|
||||
// A file's text, read the way fenceState checks the fence file: opened without following a symlink
|
||||
// (and without blocking on a FIFO), a regular file the Console's own user owns, with none of the
|
||||
// `mask` permission bits. A missing file throws its ENOENT; any other failure throws
|
||||
// proxy-file-refused. `uid` is a test seam.
|
||||
export function ownedText(file, { mask = 0o077, uid = process.getuid() } = {}) {
|
||||
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
||||
try {
|
||||
const stat = fs.fstatSync(fd);
|
||||
if (!stat.isFile() || stat.uid !== uid || (stat.mode & mask)) throw Object.assign(new Error('proxy-file-refused'), { code: 'proxy-file-refused' });
|
||||
return fs.readFileSync(fd, 'utf8');
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
// The whole receipt file's text for Ride all, which decides from it (ownedText, no group or other
|
||||
// bits). No file yet answers ''; anything else that fails answers null, and the caller treats every
|
||||
// organization without cliproxy as unreadable.
|
||||
export function receiptsText(dataRoot, { uid = process.getuid() } = {}) {
|
||||
try { return ownedText(receiptFile(dataRoot), { uid }); } catch (error) { return error?.code === 'ENOENT' ? '' : null; }
|
||||
}
|
||||
|
||||
// The last few receipts, oldest first, for the page after a reload. Reads only the file's tail and
|
||||
// skips a line that does not parse (a torn last write). Receipts never hold a key or a body.
|
||||
export function recentReceipts(dataRoot, limit = 10) {
|
||||
@@ -122,6 +143,135 @@ export function recentReceipts(dataRoot, limit = 10) {
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
// #1873 settings-backend A1 (item 9): the setup history, one page at a time, newest page first and
|
||||
// oldest first within a page. `before` is a byte offset the previous page answered as `next`: the
|
||||
// start of a line. The file is read the way ownedText reads (no symlink, no FIFO, owned by the
|
||||
// Console's user, no group or other bits) and backward from `before` in 64 KB chunks. A partial
|
||||
// last line (a write in progress) waits for a later read; a line that does not parse, or is longer
|
||||
// than 64 KB, is skipped. Each entry is redacted (redact.mjs) before it is answered, so a receipt
|
||||
// that ever held key text shows none. An entry whose redacted values read together, or whose keys
|
||||
// and values read together, still hold an environment secret split across them is answered as
|
||||
// { withheld: true }; pieces kept apart by another whole field are not seen (known limit). A missing
|
||||
// file is an empty history; any other failure to read refuses outcome-unknown. `uid` is a test seam.
|
||||
export const HISTORY_LIMIT = Object.freeze({ min: 1, max: 100, default: 25 });
|
||||
const HISTORY_CHUNK = 65536, HISTORY_LINE_MAX = 65536, HISTORY_SCAN_MAX = 2000;
|
||||
// A redacted entry's values joined in order, with each object key before its value when `keys`.
|
||||
const entryText = (value, keys) => (value !== null && typeof value === 'object'
|
||||
? Object.entries(value).map(([key, item]) => (keys && !Array.isArray(value) ? key : '') + entryText(item, keys)).join('')
|
||||
: String(value));
|
||||
export function receiptHistory(dataRoot, { limit = HISTORY_LIMIT.default, before = null, uid = process.getuid(), secrets = [] } = {}) {
|
||||
if (!Number.isSafeInteger(limit)) refuse('invalid-request');
|
||||
const n = Math.min(HISTORY_LIMIT.max, Math.max(HISTORY_LIMIT.min, limit));
|
||||
if (before !== null && !(Number.isSafeInteger(before) && before >= 0)) refuse('invalid-request');
|
||||
let fd;
|
||||
try { fd = fs.openSync(receiptFile(dataRoot), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
|
||||
catch (error) {
|
||||
if (error.code !== 'ENOENT') refuse('outcome-unknown');
|
||||
if (before !== null && before !== 0) refuse('invalid-request');
|
||||
return { entries: [], next: null };
|
||||
}
|
||||
try {
|
||||
let stat;
|
||||
try { stat = fs.fstatSync(fd); } catch { refuse('outcome-unknown'); }
|
||||
if (!stat.isFile() || stat.uid !== uid || (stat.mode & 0o077)) refuse('outcome-unknown');
|
||||
const size = stat.size;
|
||||
if (before !== null && before > size) refuse('invalid-request');
|
||||
// A window over the file: `buf` holds bytes [start, start + buf.length).
|
||||
let start = 0, buf = Buffer.alloc(0);
|
||||
const readAt = (offset, length) => {
|
||||
const out = Buffer.alloc(length);
|
||||
let got;
|
||||
try { got = fs.readSync(fd, out, 0, length, offset); } catch { refuse('outcome-unknown'); }
|
||||
if (got !== length) refuse('outcome-unknown');
|
||||
return out;
|
||||
};
|
||||
// The offset of the last newline in [0, from), or -1.
|
||||
const lastNewline = from => {
|
||||
let pos = from;
|
||||
while (pos > 0) {
|
||||
if (!(pos > start && pos <= start + buf.length)) { start = Math.max(0, pos - HISTORY_CHUNK); buf = readAt(start, pos - start); }
|
||||
const i = buf.lastIndexOf(0x0a, pos - start - 1);
|
||||
if (i >= 0) return start + i;
|
||||
pos = start;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
const bytes = (from, to) => (from >= start && to <= start + buf.length ? buf.subarray(from - start, to - start) : readAt(from, to - from));
|
||||
// `cursor` is always 0 or the offset just after a newline: the end of the next line to read.
|
||||
let cursor;
|
||||
if (before === null) cursor = lastNewline(size) + 1;
|
||||
else if (before > 0 && bytes(before - 1, before)[0] !== 0x0a) refuse('invalid-request');
|
||||
else cursor = before;
|
||||
const entries = [];
|
||||
for (let scanned = 0; cursor > 0 && entries.length < n && scanned < HISTORY_SCAN_MAX; scanned++) {
|
||||
const lineStart = lastNewline(cursor - 1) + 1, lineEnd = cursor - 1;
|
||||
if (lineEnd - lineStart <= HISTORY_LINE_MAX) {
|
||||
let value = null;
|
||||
try { value = JSON.parse(bytes(lineStart, lineEnd).toString('utf8')); } catch { /* torn line */ }
|
||||
if (value && typeof value === 'object' && !Array.isArray(value) && typeof value.op === 'string') {
|
||||
const safe = redactValue(value, secrets);
|
||||
const split = holdsSecret(entryText(safe, false), secrets) || holdsSecret(entryText(safe, true), secrets);
|
||||
entries.push(split ? { withheld: true } : safe);
|
||||
}
|
||||
}
|
||||
cursor = lineStart;
|
||||
}
|
||||
entries.reverse();
|
||||
return { entries, next: cursor > 0 ? cursor : null };
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
// #1873 settings-backend A1 (item 7): when the service key was made. proxy.json is created in the
|
||||
// same init step as the management key, with exclusive create, and is never rewritten, so its
|
||||
// mtime is the key's creation time. Only proxy.json is lstat'ed: the key file is never opened or
|
||||
// stat'ed, and nothing is read. A missing proxy.json is `missing`; a symlink, a non-file, one owned
|
||||
// by another user or one that cannot be examined is `unreadable`, with no date. There is no
|
||||
// renewal yet (proxy-scope: no rotation in the MVP), so renewedAt is null and renewal 'not-built'.
|
||||
export function serviceKeyState(configDir, { uid = process.getuid() } = {}) {
|
||||
const out = { madeAt: null, renewedAt: null, renewal: 'not-built', problem: null };
|
||||
let stat;
|
||||
try { stat = fs.lstatSync(path.join(configDir, 'proxy.json')); }
|
||||
catch (error) { out.problem = error.code === 'ENOENT' ? 'missing' : 'unreadable'; return out; }
|
||||
if (!stat.isFile() || stat.uid !== uid || !Number.isFinite(stat.mtimeMs) || stat.mtimeMs <= 0) { out.problem = 'unreadable'; return out; }
|
||||
out.madeAt = new Date(stat.mtimeMs).toISOString();
|
||||
return out;
|
||||
}
|
||||
|
||||
// #1873 settings-backend A1 (item 3): the proxy unit's last journal lines, made safe to show. The
|
||||
// unit name is unitName()'s, never the caller's; `lines` is clamped to 1..200. journalctl runs
|
||||
// through `run` (defaultRun: its timeout and 1 MB cap). A missing journalctl, a nonzero exit or a
|
||||
// timeout refuses outcome-unknown, with no lines and no other source tried. Each line is redacted
|
||||
// (redact.mjs) and cut to 300 characters; a line that cannot be shown is dropped, never shown raw.
|
||||
// A secret from `secrets` found across the shown lines, though in no one line, drops every line.
|
||||
export const LOG_LINES = Object.freeze({ min: 1, max: 200, default: 50 });
|
||||
export async function unitLog({ run = defaultRun, unit, lines = LOG_LINES.default, env, secrets = [] } = {}) {
|
||||
if (typeof unit !== 'string' || !/^mosaic-proxy(-[a-z][a-z0-9]{1,15})?\.service$/.test(unit)) refuse('proxy-unit-usage');
|
||||
if (!Number.isSafeInteger(lines)) refuse('invalid-request');
|
||||
const n = Math.min(LOG_LINES.max, Math.max(LOG_LINES.min, lines));
|
||||
let result;
|
||||
try { result = await run('journalctl', ['--user', '-u', unit, '-n', String(n), '-o', 'cat', '--no-pager', '-q'], { env, timeout: 15000 }); }
|
||||
catch { refuse('outcome-unknown'); }
|
||||
if (!result || result.code !== 0 || typeof result.stdout !== 'string') refuse('outcome-unknown');
|
||||
const raw = result.stdout.split('\n');
|
||||
if (raw.at(-1) === '') raw.pop();
|
||||
const kept = raw.slice(-n);
|
||||
const out = [];
|
||||
let redacted = 0, dropped = 0;
|
||||
try {
|
||||
for (const line of kept) {
|
||||
const safe = redactLine(line, secrets);
|
||||
if (safe.text === null) { if (line.trim()) dropped++; continue; }
|
||||
if (safe.redacted) redacted++;
|
||||
out.push(safe.text);
|
||||
}
|
||||
// The lines that will be shown, read together: a secret split across them drops them all.
|
||||
// Only environment secrets are checked this way. A key pattern broken across two journal
|
||||
// lines, each part too short for the long-run rules, is a known limit shared with chat-fail.
|
||||
if (holdsSecret(out.join(''), secrets)) { dropped += out.length; out.length = 0; }
|
||||
} catch { refuse('outcome-unknown'); }
|
||||
return { unit, lines: out, redacted, dropped };
|
||||
}
|
||||
|
||||
export function unitName(instance) {
|
||||
if (instance !== null && instance !== undefined && instance !== 'dev' && !INSTANCE_NAME.test(instance)) refuse('proxy-unit-usage');
|
||||
return instance && instance !== 'dev' ? `mosaic-proxy-${instance}.service` : 'mosaic-proxy.service';
|
||||
@@ -195,6 +345,8 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
return {
|
||||
unit,
|
||||
status,
|
||||
// settings-backend A1: the unit's last journal lines, redacted (unitLog).
|
||||
log(lines, { secrets = [] } = {}) { return unitLog({ run, unit, lines, env, secrets }); },
|
||||
async render() { return (await service('render')).stdout; },
|
||||
async install() { await service('install'); return status(); },
|
||||
async start() {
|
||||
|
||||
@@ -3,17 +3,19 @@ import http from 'node:http';
|
||||
import { ProxyError, refuse, sha256, regularBytes, validManagementKey } from './common.mjs';
|
||||
import { lstatSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
const KEY_PATH = '/v8/management/config/access/api-keys';
|
||||
const validKeys = value => Array.isArray(value) && value.length <= 100000 && value.every(k => typeof k === 'string' && k.length > 0 && k.length <= 4096 && !/[\r\n\x00]/.test(k));
|
||||
export class ManagementClient {
|
||||
#base; #key; #receipt; #timeout;
|
||||
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000 }) {
|
||||
#base; #key; #receipt; #timeout; #providers;
|
||||
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
|
||||
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000, providers = PROVIDERS }) {
|
||||
let u; try { u = new URL(baseUrl); } catch { refuse('proxy-client-invalid'); }
|
||||
if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port || Number(u.port) < 1024 || u.port === '8317'
|
||||
|| u.username || u.password || u.pathname !== '/' || u.search || u.hash
|
||||
|| !validManagementKey(key)
|
||||
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0) refuse('proxy-client-invalid');
|
||||
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout;
|
||||
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0 || !Array.isArray(providers)) refuse('proxy-client-invalid');
|
||||
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout; this.#providers = providers;
|
||||
}
|
||||
#request(method, endpoint, payload, onStatus) {
|
||||
// node:http addresses the fixed numeric loopback directly. An ambient fetch
|
||||
@@ -107,7 +109,7 @@ export class ManagementClient {
|
||||
}
|
||||
patchCredential(name, priority) { return this.#page('PATCH', '/v8/management/credentials/fields', { name, priority }, 200); }
|
||||
oauthStart(provider) {
|
||||
if (!['claude', 'codex'].includes(provider)) refuse('proxy-client-invalid');
|
||||
if (!this.#providers.some(p => p.id === provider && p.signIn === 'oauth')) refuse('proxy-client-invalid');
|
||||
return this.#page('GET', `/v8/management/oauth/auth-url?provider=${provider}`);
|
||||
}
|
||||
oauthCallback(redirect_url) { return this.#page('POST', '/v8/management/oauth/callback', { redirect_url }); }
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// #1873 settings-backend A1: redaction for the model service's log lines and the setup history,
|
||||
// read by the instance owner on the setup page.
|
||||
//
|
||||
// It is the redaction chat-fail landed for a failed turn's cause (packages/harness/src/failure-notice.mjs,
|
||||
// its REDACT list), with Mosaic's own key prefixes added to the key-prefix line: mso- (an organization's
|
||||
// model key), mst- (the Triage key) and msp-, beside msk- (the owner's). One line is added after it:
|
||||
// those four Mosaic prefixes with no word boundary, so a key glued to a word (xmso-...) is caught
|
||||
// too. Over-redaction there is the safe side. failure-notice.mjs does not
|
||||
// export its list, and packages/harness/ belongs to another lane now, so the list is copied here.
|
||||
// tests/redact.test.mjs fails when a copied line no longer matches failure-notice.mjs.
|
||||
//
|
||||
// A text is decoded (%XX, HTML references, NFKC) and cleaned (ANSI, controls, whitespace) with
|
||||
// failure-notice's own exported helpers before it is redacted. A text that holds one of the
|
||||
// Console's environment secrets (secretValues), even split by spaces or controls, is withheld
|
||||
// whole. A text that redacts to nothing but [redacted] says nothing and is dropped.
|
||||
import { cleanText, decodeText } from '../../harness/src/failure-notice.mjs';
|
||||
|
||||
export { secretValues } from '../../harness/src/failure-notice.mjs';
|
||||
|
||||
export const LINE_MAX = 300;
|
||||
export const REDACTED = '[redacted]';
|
||||
|
||||
// Copied from failure-notice.mjs. The key-prefix line adds mso, mst and msp, and the line after
|
||||
// it is Mosaic's own; every other line is failure-notice's.
|
||||
const KEY_WORD = "(?:\\w*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization|cookie|session)";
|
||||
const REDACT = [
|
||||
/(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/\S*/gi, // any link, its userinfo and query included, from the run's start
|
||||
/\bwww\.\S+/gi,
|
||||
/(?<!\S)(?=\S*\S@\S)\S+/g, // email addresses and user@host: the whole run holding the @
|
||||
/(?:^|(?<=[\s("'=:]))(?:~|\.{1,2})?\/\S+/g, // absolute and home paths
|
||||
/\b[A-Za-z]:\\\S*/g, // Windows paths
|
||||
/\\\\\S+/g, // UNC paths
|
||||
/\b(?:bearer|basic)\s+\S+/gi,
|
||||
new RegExp(`\\b${KEY_WORD}["']?\\s*[:=]\\s*(?:"[^"]*"?|'[^']*'?|[^\\s,;}]+)`, "gi"),
|
||||
new RegExp(`\\b${KEY_WORD}["']?\\s+(?:"[^"]*"?|'[^']*'?|(?=[^\\s"',;}]*\\d)[^\\s"',;}]+|[^\\s"',;}]{8,})`, "gi"),
|
||||
/\b(?:sk|msk|mso|mst|msp|rk|pk|ghp|gho|ghs|glpat|xox[a-z])[-_]\S+/gi,
|
||||
/ms[kotp][-_]\S+/gi, // Mosaic's prefixes glued to a word: added here, not in failure-notice.mjs
|
||||
/\beyJ\S+/g, // JWT
|
||||
/[A-Za-z0-9_\-+/=.]{32,}/g,
|
||||
/(?<![A-Za-z0-9_\-+/=.])(?=[A-Za-z0-9_\-+/=.]*\d)(?=[A-Za-z0-9_\-+/=.]*[A-Za-z])[A-Za-z0-9_\-+/=.]{16,}/g,
|
||||
];
|
||||
|
||||
// The text with every space, mark and separator gone, after cleanText, for the secret check.
|
||||
// cleanText has already removed ANSI, format, surrogate and private-use characters and turned
|
||||
// controls into spaces, so this removes the same set failure-notice's compactText does.
|
||||
const compact = clean => clean.replace(/[\p{M}\p{Z}\s]/gu, '');
|
||||
|
||||
function cap(text, n = LINE_MAX) {
|
||||
const chars = Array.from(text);
|
||||
return chars.length <= n ? text : chars.slice(0, n - 3).join('') + '...';
|
||||
}
|
||||
|
||||
// One text made safe to show. Answers { text, redacted } where text is null when nothing can be
|
||||
// shown: an empty text, one holding a secret (withheld: true), or one that redacts to only
|
||||
// [redacted]. Redaction runs over the whole text before the cap, so the cut never parts a key word
|
||||
// from its value. `secrets` is secretValues(env).
|
||||
export function redactLine(line, secrets = []) {
|
||||
const clean = cleanText(decodeText(String(line)));
|
||||
if (!clean) return { text: null, redacted: false };
|
||||
if (secrets.length) {
|
||||
const flat = compact(clean);
|
||||
if (secrets.some(value => flat.includes(value))) return { text: null, redacted: true, withheld: true };
|
||||
}
|
||||
let shown = clean;
|
||||
for (const re of REDACT) shown = shown.replace(re, REDACTED);
|
||||
shown = shown.replace(/(?:\[redacted\]\s*){2,}/g, `${REDACTED} `).trim();
|
||||
if (!shown || shown === REDACTED) return { text: null, redacted: true };
|
||||
return { text: cap(shown), redacted: shown !== clean };
|
||||
}
|
||||
|
||||
// True when the whole text, joined with no spaces, holds a secret: one split across lines is seen.
|
||||
export function holdsSecret(text, secrets = []) {
|
||||
if (!secrets.length) return false;
|
||||
const flat = compact(cleanText(decodeText(String(text))));
|
||||
return secrets.some(value => flat.includes(value));
|
||||
}
|
||||
|
||||
// A stored value made safe to show: strings are redacted, and a string that cannot be shown
|
||||
// becomes [redacted]. Keys that redaction would change are dropped with their value. Depth and
|
||||
// size are bounded; anything past the bound becomes null.
|
||||
export function redactValue(value, secrets = [], depth = 0) {
|
||||
if (value === null || typeof value === 'number' || typeof value === 'boolean') return value;
|
||||
if (typeof value === 'string') return value === '' ? '' : redactLine(value, secrets).text ?? REDACTED;
|
||||
if (depth >= 4 || typeof value !== 'object') return null;
|
||||
if (Array.isArray(value)) return value.slice(0, 64).map(item => redactValue(item, secrets, depth + 1));
|
||||
const out = {};
|
||||
for (const [key, item] of Object.entries(value).slice(0, 64)) {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(key) || redactLine(key, secrets).text !== key) continue;
|
||||
out[key] = redactValue(item, secrets, depth + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// #1873 ride-default slice 1: the rules for "Ride all", which adds the instance's model proxy
|
||||
// (the cliproxy model provider) to the owner's existing organizations. Pure functions: the
|
||||
// Console wiring (webui cli.mjs) reads each organization and its bus, and admin-control runs them.
|
||||
import { usableModel } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export { usableModel };
|
||||
const has = (list, name) => Array.isArray(list) && list.includes(name);
|
||||
|
||||
// The model providers one change-log change shows before and after, by the change's path: the
|
||||
// list itself, the plugins object, or the whole document. Any other path shows none.
|
||||
function providersOf(change) {
|
||||
const at = value => change?.path === 'plugins.model-provider' ? value
|
||||
: change?.path === 'plugins' ? value?.['model-provider']
|
||||
: change?.path === '' ? value?.plugins?.['model-provider'] : undefined;
|
||||
return [at(change?.old), at(change?.new)];
|
||||
}
|
||||
const touchesProviders = path => path === '' || path === 'plugins' || path === 'plugins.model-provider';
|
||||
|
||||
// What the organization's change log shows of cliproxy, from its committed writes: `removed` when
|
||||
// a write took it off, `seen` when any write shows it on the organization before or after, or wrote
|
||||
// the providers without logging their values (a paths-only entry). A log that cannot be read
|
||||
// answers null, and the caller skips the organization as unreadable.
|
||||
export function cliproxyHistory(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
let removed = false, seen = false;
|
||||
try {
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
const event = JSON.parse(line);
|
||||
if (event?.state !== 'committed' || !Array.isArray(event.changes)) continue;
|
||||
for (const change of event.changes) {
|
||||
if (!touchesProviders(change?.path)) continue;
|
||||
if (!Object.hasOwn(change, 'old') && !Object.hasOwn(change, 'new')) { seen = true; continue; }
|
||||
const [before, after] = providersOf(change);
|
||||
if (has(before, 'cliproxy') && !has(after, 'cliproxy')) removed = true;
|
||||
if (has(before, 'cliproxy') || has(after, 'cliproxy')) seen = true;
|
||||
}
|
||||
}
|
||||
return { removed, seen };
|
||||
} catch { return null; }
|
||||
}
|
||||
export function cliproxyRemoved(text) { const h = cliproxyHistory(text); return h === null ? null : h.removed; }
|
||||
|
||||
// The organizations the proxy's own receipts (proxy-admin.jsonl) show cliproxy was or may have
|
||||
// been on: each ride-all receipt's added list, each ride-move's org, each ride-removed's org (the
|
||||
// organization admin page writes one before it saves a document without cliproxy), and each
|
||||
// ride-intent's org (Ride all writes one before each plugins.set) unless a later ride-not-added for
|
||||
// that organization shows the bus did not take it. Any line that does not parse, and any ride
|
||||
// record of the wrong shape, answers null: the caller then skips every organization without
|
||||
// cliproxy as unreadable. Text that is not a string answers null too.
|
||||
const RIDE_ORG = new Set(['ride-move', 'ride-removed', 'ride-intent', 'ride-not-added']);
|
||||
export function riddenOrgs(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const ids = new Set(), pending = new Set();
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
let r; try { r = JSON.parse(line); } catch { return null; }
|
||||
if (!r || typeof r !== 'object' || Array.isArray(r)) return null;
|
||||
if (r.op === 'ride-all') {
|
||||
if (!Array.isArray(r.added) || !r.added.every(id => typeof id === 'string')) return null;
|
||||
for (const id of r.added) ids.add(id);
|
||||
} else if (RIDE_ORG.has(r.op)) {
|
||||
if (typeof r.org !== 'string') return null;
|
||||
if (r.op === 'ride-intent') pending.add(r.org);
|
||||
else if (r.op === 'ride-not-added') pending.delete(r.org);
|
||||
else ids.add(r.org);
|
||||
}
|
||||
}
|
||||
for (const id of pending) ids.add(id);
|
||||
return ids;
|
||||
}
|
||||
|
||||
// The local part of the decision, with no bus call: what Ride all does with one organization
|
||||
// before it asks the organization's bus anything. An organization that uses cliproxy now (and is
|
||||
// not a fixture organization) is already riding, whatever its history. One without cliproxy now
|
||||
// that had it, or may have had it, is removed: its change log or the proxy's receipts show it
|
||||
// (`ridden` is true from the receipts, null when they cannot be read).
|
||||
export function localRide({ fixture, cliproxy, changes, ridden = false }) {
|
||||
if (typeof fixture !== 'boolean' || typeof cliproxy !== 'boolean') return 'unreadable';
|
||||
if (cliproxy && !fixture) return 'already';
|
||||
const history = cliproxyHistory(changes);
|
||||
if (history === null || (ridden === null && !cliproxy)) return 'unreadable';
|
||||
if (history.removed || (!cliproxy && (ridden === true || history.seen))) return 'removed';
|
||||
if (fixture) return 'fixture';
|
||||
return 'ready';
|
||||
}
|
||||
|
||||
// One organization as Ride all reads it, without its bus: `read()` gives its document and
|
||||
// `readLog()` the text of its change log. A document that cannot be read leaves `fixture` and
|
||||
// `cliproxy` undefined, a log that does not exist yet is empty, and any other log failure is null;
|
||||
// localRide names either as unreadable. `isFixture(doc)` is the CLI's own fixture test.
|
||||
export function readRider({ id, read, readLog, isFixture }) {
|
||||
let doc = null, changes = null;
|
||||
try { doc = read(); } catch {}
|
||||
try { changes = readLog(); } catch (e) { changes = e?.code === 'ENOENT' ? '' : null; }
|
||||
const ok = !!doc && typeof doc === 'object';
|
||||
return { id, fixture: ok ? isFixture(doc) === true : undefined,
|
||||
cliproxy: ok ? (Array.isArray(doc.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []).includes('cliproxy') : undefined, changes };
|
||||
}
|
||||
|
||||
// The owner's models: `proxy` is true when the instance's proxy.json names a port. Each organization
|
||||
// that lists cliproxy is asked for its routes at once, so a hung bus costs one timeout, not one each.
|
||||
// It rides when its bus answers a ready catalogue; the models are the cliproxy rows those
|
||||
// catalogues list, once each.
|
||||
export async function ownerModelsFrom({ proxy, riders }) {
|
||||
if (proxy !== true) return { proxy: false, riding: false, models: [] };
|
||||
const catalogues = await Promise.all((Array.isArray(riders) ? riders : []).filter(r => r?.cliproxy === true)
|
||||
.map(async r => { try { return (await r.call('routes'))?.catalogue; } catch { return null; } }));
|
||||
const models = new Map(); let riding = false;
|
||||
for (const catalogue of catalogues) {
|
||||
if (catalogue?.status !== 'ready' || !Array.isArray(catalogue.models)) continue;
|
||||
riding = true;
|
||||
// A key two buses list keeps the first usable row: one bus's stale row does not hide the model.
|
||||
for (const m of catalogue.models) {
|
||||
if (m?.module !== 'cliproxy' || typeof m.key !== 'string') continue;
|
||||
if (!models.has(m.key) || (!usableModel(models.get(m.key)) && usableModel(m))) models.set(m.key, m);
|
||||
}
|
||||
}
|
||||
return { proxy: true, riding, models: [...models.values()] };
|
||||
}
|
||||
|
||||
// The owner's model for an organization: the first usable catalogue model from claude, else
|
||||
// the first usable one, that serves every harness in `harnesses`.
|
||||
export function pickModel(models, harnesses = []) {
|
||||
const fits = (Array.isArray(models) ? models : []).filter(m => usableModel(m) && harnesses.every(h => m.harnesses.includes(h)));
|
||||
return fits.find(m => m.upstream === 'claude') ?? fits[0] ?? null;
|
||||
}
|
||||
|
||||
// A fixture organization moved to the owner's models: the fixture model provider becomes
|
||||
// cliproxy, each fixture model entry goes, and every role that used one uses the owner's model.
|
||||
// Answers { doc, model } or { reason } when no catalogue model serves the roles' harnesses.
|
||||
export function fixtureMove(doc, models) {
|
||||
const next = structuredClone(doc);
|
||||
const fixtureKeys = Object.entries(next.launch?.models ?? {}).filter(([, m]) => m?.module === 'fixture').map(([key]) => key);
|
||||
const uses = [];
|
||||
const visit = vars => {
|
||||
if (!vars || typeof vars !== 'object') return;
|
||||
for (const prefix of ['', 'fallback.']) if (fixtureKeys.includes(vars[prefix + 'model'])) uses.push({ vars, prefix });
|
||||
};
|
||||
// A model is an agent-layer var: an organization's roles and each project's own agents carry one.
|
||||
for (const role of Object.values(next.roles ?? {})) visit(role?.vars);
|
||||
for (const project of Object.values(next.projects ?? {})) for (const agent of Object.values(project?.agents ?? {})) visit(agent?.vars);
|
||||
const harnesses = [...new Set(uses.map(({ vars, prefix }) => vars[prefix + 'harness']).filter(h => typeof h === 'string'))];
|
||||
const model = pickModel(models, harnesses);
|
||||
if (!model) return { reason: 'no-model' };
|
||||
for (const key of fixtureKeys) delete next.launch.models[key];
|
||||
next.launch = next.launch ?? {}; next.launch.models = next.launch.models ?? {};
|
||||
next.launch.models[model.key] = { provider: model.provider, model: model.model, module: 'cliproxy', upstream: model.upstream };
|
||||
for (const { vars, prefix } of uses) vars[prefix + 'model'] = model.key;
|
||||
const providers = (next.plugins?.['model-provider'] ?? []).filter(n => n !== 'fixture');
|
||||
next.plugins = { ...(next.plugins ?? {}), 'model-provider': providers.includes('cliproxy') ? providers : [...providers, 'cliproxy'] };
|
||||
return { doc: next, model };
|
||||
}
|
||||
|
||||
// The move itself, through the organization service's existing whole-document update: read,
|
||||
// change, validate, then write only if the revision read is still current. Owner-only twice:
|
||||
// the Console route admits only the instance owner, and the service checks `ctx.principal`.
|
||||
export async function moveFixtureOrg({ service, ctx, id, models }) {
|
||||
const shown = await service.showOrg(ctx, id);
|
||||
const moved = fixtureMove(shown.doc, models);
|
||||
if (moved.reason) return { moved: false, reason: moved.reason };
|
||||
const checked = await service.validateOrg(moved.doc);
|
||||
if (!checked?.ok) return { moved: false, reason: 'invalid' };
|
||||
await service.updateOrg(ctx, id, moved.doc, { ifRevision: shown.revision });
|
||||
return { moved: true, model: moved.model.key };
|
||||
}
|
||||
@@ -7,12 +7,23 @@ export function installPaths(dataRoot, pin = PIN) {
|
||||
const dir = path.join(dataRoot, 'opt', 'cliproxyapi', pin.version);
|
||||
return { dir, binary: path.join(dir, 'cli-proxy-api'), panel: path.join(dir, 'static', 'management.html') };
|
||||
}
|
||||
// proxy.json records the install path from the PIN it was created under, and nothing
|
||||
// rewrites it. After a PIN bump an earlier release's path under this data root stays valid
|
||||
// and reads as the current pinned path. The runner executes only the hash-verified pinned
|
||||
// install, never the recorded path, so an old value selects nothing.
|
||||
const releasePath = (dataRoot, binary) => {
|
||||
const base = path.join(dataRoot, 'opt', 'cliproxyapi') + path.sep;
|
||||
if (typeof binary !== 'string' || !binary.startsWith(base)) return false;
|
||||
const [version, file, ...rest] = binary.slice(base.length).split(path.sep);
|
||||
return rest.length === 0 && file === 'cli-proxy-api' && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(version);
|
||||
};
|
||||
export function validateProxy(value, dataRoot, pin = PIN) {
|
||||
const pinned = installPaths(dataRoot, pin).binary;
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)
|
||||
|| Object.keys(value).some(k => !['binary', 'port', 'rotateGraceMinutes', 'firstOutputSeconds'].includes(k))
|
||||
|| !Number.isInteger(value.port) || value.port < 1024 || value.port > 65535 || value.port === 8317
|
||||
|| value.binary !== installPaths(dataRoot, pin).binary) refuse('proxy-config-invalid');
|
||||
return { port: value.port, binary: value.binary, ...proxyTiming(value) };
|
||||
|| (value.binary !== pinned && !releasePath(dataRoot, value.binary))) refuse('proxy-config-invalid');
|
||||
return { port: value.port, binary: pinned, ...proxyTiming(value) };
|
||||
}
|
||||
export function loadProxy(configDir, dataRoot) {
|
||||
const file = path.join(configDir, 'proxy.json');
|
||||
|
||||
@@ -7,7 +7,10 @@ import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createProxyAdmin } from '../src/admin-control.mjs';
|
||||
import { createProxyAdmin, installedHarnesses, harnessesNamed, rootHarnessesNamed } from '../src/admin-control.mjs';
|
||||
import { pluginHash } from '../../plugins/src/pinned.mjs';
|
||||
import { installPlugin } from '../../plugins/src/install.mjs';
|
||||
import { KINDS } from '../../plugins/src/kinds.mjs';
|
||||
import { initFiles, receiptFile } from '../src/admin.mjs';
|
||||
import { PIN } from '../src/common.mjs';
|
||||
|
||||
@@ -15,7 +18,7 @@ const code = name => error => error.code === name;
|
||||
const SENTINEL = 'pa-sentinel-management-key-0123456789';
|
||||
const stopped = async () => ({ stopped: true, running: [] });
|
||||
|
||||
function fixture(t, { unitState = { installed: false, active: 'inactive', healthy: false }, restart = null, fetch = null, pin = PIN, statusHook = null } = {}) {
|
||||
function fixture(t, { unitState = { installed: false, active: 'inactive', healthy: false }, restart = null, fetch = null, pin = PIN, statusHook = null, extra = {} } = {}) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pc-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
@@ -30,7 +33,7 @@ function fixture(t, { unitState = { installed: false, active: 'inactive', health
|
||||
stop: async () => { ops.push('stop'); return { ...unitState, active: 'inactive', pid: null }; },
|
||||
restart: async () => { ops.push('restart'); return restart ?? { state: unitState, evidence: { unit: 'mosaic-proxy-zz.service', confirmed: true, before: { pid: 10, since: 1, active: 'active' }, after: { pid: 11, since: 2, active: 'active', listening: true }, observedAt: new Date(0).toISOString() } }; },
|
||||
};
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: fetch ?? (async () => ({})), now: () => new Date(0), orgs: async () => [{ id: 'acme', catalogue: 'ready' }], pin });
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: fetch ?? (async () => ({})), now: () => new Date(0), orgs: async () => [{ id: 'acme', catalogue: 'ready' }], pin, ...extra });
|
||||
return { root, configDir, dataRoot, admin, ops, files: initFiles(configDir, dataRoot) };
|
||||
}
|
||||
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
|
||||
@@ -227,3 +230,340 @@ test('status carries the last receipts from proxy-admin.jsonl, so the page shows
|
||||
assert.equal(receipts.length, 10);
|
||||
assert.ok(receipts.every(r => r.op === 'unit.stop'));
|
||||
});
|
||||
|
||||
// #1873 settings-backend A1: the controller's three reads and the account-change record.
|
||||
function a1Fixture(t, { unitState = { installed: true, active: 'active', healthy: true }, log = undefined, statusError = false, env = {} } = {}) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pc-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const calls = [];
|
||||
const unit = {
|
||||
unit: 'mosaic-proxy-zz.service',
|
||||
status: async () => { if (statusError) throw Object.assign(new Error('systemctl gone'), { code: 'proxy-unit-failed' }); return { unit: 'mosaic-proxy-zz.service', ...unitState }; },
|
||||
...(log === undefined ? { log: async (lines, options) => { calls.push({ lines, options }); return { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 }; } } : log === null ? {} : { log }),
|
||||
};
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, now: () => new Date(0), env });
|
||||
return { admin, calls, configDir, dataRoot };
|
||||
}
|
||||
|
||||
test('log reads the unit journal with the env secrets; a missing unit or log reader is not-configured, an unreadable state outcome-unknown', async t => {
|
||||
const { admin, calls } = a1Fixture(t, { env: { MOSAIC_PROXY_KEY: 'plainwordsonly', PATH: '/usr/bin' } });
|
||||
assert.deepEqual(await admin.log(), { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 });
|
||||
assert.deepEqual(calls, [{ lines: 50, options: { secrets: ['plainwordsonly'] } }]);
|
||||
await admin.log({ lines: 7 });
|
||||
assert.equal(calls[1].lines, 7);
|
||||
await assert.rejects(a1Fixture(t, { unitState: { installed: false, active: 'inactive', healthy: false } }).admin.log(), code('not-configured'));
|
||||
await assert.rejects(a1Fixture(t, { log: null }).admin.log(), code('not-configured'));
|
||||
await assert.rejects(a1Fixture(t, { statusError: true }).admin.log(), code('outcome-unknown'));
|
||||
const failing = a1Fixture(t, { log: async () => { throw Object.assign(new Error('journal'), { code: 'outcome-unknown' }); } });
|
||||
await assert.rejects(failing.admin.log(), code('outcome-unknown'));
|
||||
});
|
||||
|
||||
test('serviceKey and history read the configured directories', async t => {
|
||||
const { admin, configDir, dataRoot } = a1Fixture(t);
|
||||
assert.equal(admin.serviceKey().problem, 'missing');
|
||||
fs.writeFileSync(join(configDir, 'proxy.json'), '{}', { mode: 0o600 });
|
||||
assert.equal(admin.serviceKey().problem, null);
|
||||
assert.match(admin.serviceKey().madeAt, /^\d{4}-\d\d-\d\dT/);
|
||||
assert.deepEqual(admin.history(), { entries: [], next: null });
|
||||
admin.recordAccount({ verb: 'proxy.login.status', result: { status: 'ok' } });
|
||||
assert.deepEqual(admin.history({ limit: 5 }), { entries: [{ time: new Date(0).toISOString(), op: 'account.proxy.login.complete' }], next: null });
|
||||
assert.equal(receipts(dataRoot).length, 1);
|
||||
});
|
||||
|
||||
test('history withholds an env secret a receipt holds', async t => {
|
||||
const { admin, dataRoot } = a1Fixture(t, { env: { PROXY_TOKEN: 'plainwordsonly' } });
|
||||
fs.mkdirSync(join(dataRoot, 'state'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(receiptFile(dataRoot), JSON.stringify({ op: 'x', note: 'plain words only' }) + '\n', { mode: 0o600 });
|
||||
assert.deepEqual(admin.history().entries, [{ op: 'x', note: '[redacted]' }]);
|
||||
});
|
||||
|
||||
test('recordAccount records account changes by label only, never a key, login state, callback or model name', async t => {
|
||||
const { admin, dataRoot } = a1Fixture(t);
|
||||
const KEY = 'sk-proj-Ab3dE5fG7hJ9kL1mN3pQ5rS7tU9vW1xY';
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: KEY }, result: { added: true }, user: 'jason', org: 'acme' }), true);
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: KEY, key: KEY } }), true);
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'ok' } }), true);
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'wait' } }), null);
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.priority.set', args: { accountId: '0123456789ab', priority: 2 } }), true);
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.group.models.set', args: { accountId: 'not-hex', models: ['secret-model-name', 'b'] }, org: '../x' }), true);
|
||||
for (const verb of ['proxy.login.start', 'proxy.login.submit', 'proxy.login.cancel', 'plugins.set', 'proxy.accounts', undefined]) {
|
||||
assert.equal(admin.recordAccount({ verb, args: { redirect_url: 'https://cb.example/?code=abc', provider: 'x' } }), null, String(verb));
|
||||
}
|
||||
const all = receipts(dataRoot);
|
||||
const at = new Date(0).toISOString();
|
||||
assert.deepEqual(all, [
|
||||
{ time: at, op: 'account.proxy.apikey.add', provider: 'openai', org: 'acme', user: 'jason' },
|
||||
{ time: at, op: 'account.proxy.apikey.add', provider: null },
|
||||
{ time: at, op: 'account.proxy.login.complete' },
|
||||
{ time: at, op: 'account.proxy.priority.set', accountId: '0123456789ab', priority: 2 },
|
||||
{ time: at, op: 'account.proxy.group.models.set', accountId: null, models: 2 },
|
||||
]);
|
||||
const text = fs.readFileSync(receiptFile(dataRoot), 'utf8');
|
||||
for (const bit of ['Ab3dE5', 'state-secret', 'secret-model', 'cb.example', 'code=abc']) assert.equal(text.includes(bit), false, bit);
|
||||
});
|
||||
|
||||
test('recordAccount answers false, and throws nothing, when the history cannot be written', async t => {
|
||||
const { admin, dataRoot } = a1Fixture(t);
|
||||
fs.mkdirSync(join(dataRoot, 'state'), { mode: 0o700 });
|
||||
fs.mkdirSync(receiptFile(dataRoot));
|
||||
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: 'k' } }), false);
|
||||
});
|
||||
|
||||
// #1873 settings-backend A2 (items 5 and 8): fake organizations behind the riders. The harness names
|
||||
// are made up; every answer carries a planted key, which no result, receipt or history entry may hold.
|
||||
const REV = 'a'.repeat(64), REV2 = 'b'.repeat(64);
|
||||
const PLANT = `mso-zz-acme-key-${'Q'.repeat(43)}`;
|
||||
const KEY_TEXT = /ms[kotp][-_][A-Za-z0-9_-]{6,}/;
|
||||
const busError = name => Object.assign(new Error(`refused ${PLANT}`), { code: name, reason: PLANT });
|
||||
function fakeOrg(id, { on = ['alpha', 'beta'], revision = REV, fileRevision = null, instances = {}, routesError = null, routesRevision = null, document = null, fileError = false, down = false, setError = null, keys = [], keysError = null, fixture = false, cliproxy = true, plugins = undefined } = {}) {
|
||||
const calls = [];
|
||||
const rider = {
|
||||
id, fixture, cliproxy, changes: '',
|
||||
file: () => { if (fileError) throw new Error(PLANT); return { document: document ?? { roles: {}, plugins: { harness: on }, secretNote: PLANT }, revision: fileRevision ?? revision }; },
|
||||
call: async (verb, args) => {
|
||||
calls.push(args === undefined ? [verb] : [verb, args]);
|
||||
if (down) throw busError('outcome-unknown');
|
||||
if (verb === 'plugins') return { business: id, revision, plugins: plugins !== undefined ? plugins : { harness: on, 'model-provider': ['cliproxy'] }, available: { harness: on }, note: PLANT };
|
||||
if (verb === 'routes') { if (routesError) throw busError(routesError); return { business: id, revision: routesRevision ?? revision, harnesses: on, models: ['m1'], providerModels: {}, levels: {}, instances, note: PLANT }; }
|
||||
if (verb === 'plugins.set') { if (setError) throw busError(setError); return { business: id, revision: REV2, plugins: args.plugins }; }
|
||||
if (verb === 'proxy.keys') { if (keysError) throw busError(keysError); return { keys }; }
|
||||
throw busError('invalid-request');
|
||||
},
|
||||
};
|
||||
return { rider, calls };
|
||||
}
|
||||
const NO_ROOT = { state: 'absent', agents: {}, assistant: null };
|
||||
const programsFixture = (t, orgs, extra = {}) => fixture(t, { extra: { riders: async () => orgs.map(o => o.rider), harnesses: () => ['alpha', 'beta', 'gamma'], rootAgents: () => NO_ROOT, ...extra } });
|
||||
const rootAgent = (vars, { definition = 'coder', excludeOrgs = [] } = {}) => ({ definition, title: 'Coder', vars, excludeOrgs });
|
||||
const route = harness => ({ harness, model: 'm1', thinking: null, fallback: null });
|
||||
|
||||
test('A2 item 5: the installed list comes from the harness plugin tree, and status lists it with no organization', async t => {
|
||||
const tree = new URL('../../plugins/harness/', import.meta.url);
|
||||
const fromTree = fs.readdirSync(tree).filter(name => { try { return fs.lstatSync(new URL(`${name}/index.mjs`, tree)).isFile(); } catch { return false; } }).sort();
|
||||
assert.ok(fromTree.length >= 1);
|
||||
assert.deepEqual(installedHarnesses(), fromTree);
|
||||
const { admin } = fixture(t);
|
||||
assert.deepEqual((await admin.status()).programs, { installed: fromTree, organizations: [] });
|
||||
});
|
||||
|
||||
test('A2 item 5: status names the programs each organization has on; one bus down is null and leaves the others', async t => {
|
||||
const acme = fakeOrg('acme', { on: ['alpha'] }), bolt = fakeOrg('bolt', { down: true }), crux = fakeOrg('crux', { plugins: { harness: 'alpha' } });
|
||||
const { admin } = programsFixture(t, [acme, bolt, crux]);
|
||||
const status = await admin.status();
|
||||
assert.deepEqual(status.programs, { installed: ['alpha', 'beta', 'gamma'], organizations: [{ id: 'acme', on: ['alpha'] }, { id: 'bolt', on: null }, { id: 'crux', on: null }] });
|
||||
assert.doesNotMatch(JSON.stringify(status), KEY_TEXT);
|
||||
});
|
||||
|
||||
test('A2 item 5: off skips a program any route still uses, whatever its model, and writes nothing there', async t => {
|
||||
// A role route, a fallback route, a project agent only the file shows, and a route whose model has
|
||||
// no known account kind: each keeps alpha on (the harness rule).
|
||||
const role = fakeOrg('role', { instances: { chief: route('alpha') } });
|
||||
const fallback = fakeOrg('fallback', { instances: { chief: { ...route('beta'), fallback: { harness: 'alpha', model: 'm1', thinking: null } } } });
|
||||
const project = fakeOrg('project', { routesError: 'launch-not-configured', document: { roles: {}, plugins: { harness: ['alpha', 'beta'] }, projects: { site: { agents: { dev: { definition: 'coder', vars: { harness: 'alpha' } } } } } } });
|
||||
const unknownKind = fakeOrg('unknown-kind', { instances: { chief: { harness: 'alpha', model: 'mystery-account-model', thinking: null, fallback: null } } });
|
||||
const { admin } = programsFixture(t, [role, fallback, project, unknownKind]);
|
||||
const out = await admin.programsOff({ name: 'alpha' });
|
||||
assert.deepEqual(out.results.map(r => [r.id, r.outcome]), [['role', 'in-use'], ['fallback', 'in-use'], ['project', 'in-use'], ['unknown-kind', 'in-use']]);
|
||||
for (const o of [role, fallback, project, unknownKind]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('A2 item 5: off turns the program off where nothing uses it, skips the last program, already off and unreadable, and reports bus down', async t => {
|
||||
const free = fakeOrg('free', { instances: { chief: route('beta') } });
|
||||
const last = fakeOrg('last', { on: ['alpha'] });
|
||||
const already = fakeOrg('already', { on: ['beta'] });
|
||||
const down = fakeOrg('down', { down: true });
|
||||
const unreadable = fakeOrg('unreadable', { fileError: true });
|
||||
const noFile = fakeOrg('no-file'); delete noFile.rider.file;
|
||||
const badRoutes = fakeOrg('bad-routes', { routesError: 'organization-invalid' });
|
||||
const { admin } = programsFixture(t, [free, last, already, down, unreadable, noFile, badRoutes]);
|
||||
const out = await admin.programsOff({ name: 'alpha', user: 'owner' });
|
||||
assert.equal(out.name, 'alpha');
|
||||
assert.deepEqual(out.results, [
|
||||
{ id: 'free', outcome: 'off' }, { id: 'last', outcome: 'last-program' }, { id: 'already', outcome: 'already-off' },
|
||||
{ id: 'down', outcome: 'bus-down' }, { id: 'unreadable', outcome: 'unreadable' }, { id: 'no-file', outcome: 'unreadable' }, { id: 'bad-routes', outcome: 'unreadable' },
|
||||
]);
|
||||
assert.deepEqual(free.calls.find(([verb]) => verb === 'plugins.set'), ['plugins.set', { revision: REV, plugins: { harness: ['beta'] } }]);
|
||||
for (const o of [last, already, down, unreadable, noFile, badRoutes]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('A2 item 5: a plugins.set refusal is reported per organization, and a revision change is reported once, never retried', async t => {
|
||||
const refused = fakeOrg('refused', { setError: 'unknown-plugin' });
|
||||
const raced = fakeOrg('raced', { setError: 'revision-conflict' });
|
||||
const moved = fakeOrg('moved', { fileRevision: REV2 });
|
||||
const ok = fakeOrg('ok');
|
||||
const { admin } = programsFixture(t, [refused, raced, moved, ok]);
|
||||
const out = await admin.programsOff({ name: 'alpha' });
|
||||
assert.deepEqual(out.results.map(r => r.outcome), ['failed:unknown-plugin', 'failed:revision-conflict', 'failed:revision-conflict', 'off']);
|
||||
assert.equal(raced.calls.filter(([verb]) => verb === 'plugins.set').length, 1);
|
||||
assert.equal(moved.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('A2 item 5: off writes one receipt by name and outcome ids, and no answer, receipt or history entry holds a key', async t => {
|
||||
const a = fakeOrg('acme'), b = fakeOrg('bolt', { setError: 'invalid-plugins' });
|
||||
const { admin, dataRoot } = programsFixture(t, [a, b]);
|
||||
const out = await admin.programsOff({ name: 'beta', user: 'owner' });
|
||||
const record = { time: new Date(0).toISOString(), op: 'programs.off', name: 'beta', results: [{ id: 'acme', outcome: 'off' }, { id: 'bolt', outcome: 'failed:invalid-plugins' }], user: 'owner' };
|
||||
assert.deepEqual(out.receipt, record);
|
||||
assert.deepEqual(receipts(dataRoot), [record]);
|
||||
const history = admin.history({});
|
||||
assert.deepEqual(history.entries, [record]);
|
||||
for (const value of [out, receipts(dataRoot), history]) assert.doesNotMatch(JSON.stringify(value), KEY_TEXT);
|
||||
});
|
||||
|
||||
test('A2 item 5: an unknown name is invalid-request and calls no bus; two off calls at once give proxy-admin-busy for one', async t => {
|
||||
let release;
|
||||
const gate = new Promise(r => { release = r; });
|
||||
const slow = fakeOrg('slow');
|
||||
const original = slow.rider.call;
|
||||
// Blocks only from the busy part on, so a name check that lets a bad name through goes red, not hangs.
|
||||
let blocking = false;
|
||||
slow.rider.call = async (verb, args) => { if (verb === 'plugins' && blocking) await gate; return original(verb, args); };
|
||||
const { admin, dataRoot } = programsFixture(t, [slow]);
|
||||
await assert.rejects(admin.programsOff({ name: 'delta' }), code('invalid-request'));
|
||||
await assert.rejects(admin.programsOff({ name: 42 }), code('invalid-request'));
|
||||
assert.deepEqual(slow.calls, []);
|
||||
assert.deepEqual(receipts(dataRoot), []);
|
||||
blocking = true;
|
||||
const first = admin.programsOff({ name: 'alpha' });
|
||||
await new Promise(r => setImmediate(r));
|
||||
// Bounded: without the lock the second call would wait on the same gate, so it answers 'waited'.
|
||||
const second = admin.programsOff({ name: 'beta' }).then(() => 'answered', e => e?.code);
|
||||
assert.equal(await Promise.race([second, new Promise(r => setTimeout(() => r('waited'), 1000))]), 'proxy-admin-busy');
|
||||
release();
|
||||
await second;
|
||||
assert.deepEqual((await first).results, [{ id: 'slow', outcome: 'off' }]);
|
||||
assert.equal(receipts(dataRoot).length, 1);
|
||||
});
|
||||
|
||||
test('A2 item 5: an installed list that cannot be read refuses off as invalid-request', async t => {
|
||||
const a = fakeOrg('acme');
|
||||
const { admin } = programsFixture(t, [a], { harnesses: () => { throw new Error('unreadable tree'); } });
|
||||
await assert.rejects(admin.programsOff({ name: 'alpha' }), code('invalid-request'));
|
||||
assert.deepEqual(a.calls, []);
|
||||
assert.equal((await admin.status()).programs.installed, null);
|
||||
});
|
||||
|
||||
test('A2 item 5 (review P1-1): a root agent the organization takes keeps its program on; an excluded organization and the root assistant do not count', async t => {
|
||||
// Only the root agent file names alpha: nothing in either organization's file or routes does.
|
||||
const root = { state: 'ok', assistant: 'helper', agents: {
|
||||
writer: rootAgent({ harness: 'gamma', 'fallback.harness': 'alpha' }, { excludeOrgs: ['spare'] }),
|
||||
helper: rootAgent({ harness: 'beta' }, { definition: 'assistant' }),
|
||||
} };
|
||||
const takes = fakeOrg('takes', { on: ['alpha', 'beta', 'gamma'] });
|
||||
const spare = fakeOrg('spare', { on: ['alpha', 'beta', 'gamma'] });
|
||||
const { admin } = programsFixture(t, [takes, spare], { rootAgents: () => root });
|
||||
const out = await admin.programsOff({ name: 'alpha' });
|
||||
assert.deepEqual(out.results, [{ id: 'takes', outcome: 'in-use' }, { id: 'spare', outcome: 'off' }]);
|
||||
assert.equal(takes.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
// The root assistant is not copied into an organization, so its harness does not keep beta on.
|
||||
const again = await admin.programsOff({ name: 'beta' });
|
||||
assert.deepEqual(again.results.map(r => r.outcome), ['off', 'off']);
|
||||
// The root file is read once per call, not once per organization.
|
||||
let reads = 0;
|
||||
const counted = programsFixture(t, [fakeOrg('a'), fakeOrg('b')], { rootAgents: () => { reads++; return NO_ROOT; } });
|
||||
await counted.admin.programsOff({ name: 'alpha' });
|
||||
assert.equal(reads, 1);
|
||||
});
|
||||
|
||||
test('A2 item 5 (review P1-1): a root agent file that cannot be read, or no reader, writes nothing where the program is on', async t => {
|
||||
const on = fakeOrg('on'), already = fakeOrg('already', { on: ['beta'] });
|
||||
const { admin } = programsFixture(t, [on, already], { rootAgents: () => { throw Object.assign(new Error(`root agent file refused ${PLANT}`), { name: 'BusinessError' }); } });
|
||||
const out = await admin.programsOff({ name: 'alpha' });
|
||||
assert.deepEqual(out.results, [{ id: 'on', outcome: 'unreadable' }, { id: 'already', outcome: 'already-off' }]);
|
||||
assert.doesNotMatch(JSON.stringify(out), KEY_TEXT);
|
||||
const bare = fakeOrg('bare');
|
||||
const none = fixture(t, { extra: { riders: async () => [bare.rider], harnesses: () => ['alpha', 'beta'] } });
|
||||
assert.deepEqual((await none.admin.programsOff({ name: 'alpha' })).results, [{ id: 'bare', outcome: 'unreadable' }]);
|
||||
for (const o of [on, already, bare]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
// A root answer of the wrong shape is unreadable too.
|
||||
assert.equal(rootHarnessesNamed({ agents: { w: { vars: { harness: 'alpha' } } } }, 'acme'), null);
|
||||
assert.equal(rootHarnessesNamed(null, 'acme'), null);
|
||||
assert.deepEqual([...rootHarnessesNamed(NO_ROOT, 'acme')], []);
|
||||
});
|
||||
|
||||
test('A2 item 5 (review P3-1): a revision that is not 64 hex, routes from another revision, and routes with no instances write nothing; later organizations still go', async t => {
|
||||
const badRev = fakeOrg('bad-rev', { revision: 'not-a-revision' });
|
||||
const routesMoved = fakeOrg('routes-moved', { routesRevision: REV2 });
|
||||
const noInstances = fakeOrg('no-instances', { instances: null });
|
||||
const after = fakeOrg('after');
|
||||
const { admin, dataRoot } = programsFixture(t, [badRev, routesMoved, noInstances, after]);
|
||||
const out = await admin.programsOff({ name: 'alpha' });
|
||||
assert.deepEqual(out.results, [{ id: 'bad-rev', outcome: 'unreadable' }, { id: 'routes-moved', outcome: 'failed:revision-conflict' }, { id: 'no-instances', outcome: 'unreadable' }, { id: 'after', outcome: 'off' }]);
|
||||
for (const o of [badRev, routesMoved, noInstances]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
|
||||
assert.equal(receipts(dataRoot).length, 1);
|
||||
});
|
||||
|
||||
test('A2 item 5 (review P3-1): a harness program the instance plugin lock pins is listed as installed', t => {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pl-'));
|
||||
// The install leaves read-only directories; open them up before removing the tree.
|
||||
const thaw = p => { const st = fs.lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { fs.chmodSync(p, 0o700); for (const n of fs.readdirSync(p)) thaw(join(p, n)); } };
|
||||
t.after(() => { thaw(root); fs.rmSync(root, { recursive: true, force: true }); });
|
||||
const src = join(root, 'src'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(join(src, 'harness'), { recursive: true }); fs.mkdirSync(dataRoot);
|
||||
fs.writeFileSync(join(src, 'harness', 'index.mjs'), KINDS.harness.exports.map(name => `export function ${name}(){return ${name === 'levels' ? "['high']" : name === 'countsAccount' ? 'true' : 'null'};}`).join('\n') + '\nexport const interfaceVersion=1;');
|
||||
const manifest = { name: 'zetaplug', version: '1.0.0', kinds: ['harness'], interfaceVersions: { harness: 1 }, sha256: '0'.repeat(64), source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
|
||||
fs.writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
manifest.sha256 = pluginHash(src);
|
||||
fs.writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
assert.equal(installedHarnesses(dataRoot).includes('zetaplug'), false);
|
||||
installPlugin({ dataRoot, source: src, expectedHash: manifest.sha256 });
|
||||
const listed = installedHarnesses(dataRoot);
|
||||
assert.ok(listed.includes('zetaplug'));
|
||||
assert.deepEqual(listed.filter(n => n !== 'zetaplug'), installedHarnesses());
|
||||
});
|
||||
|
||||
test('A2 item 5 (review P3-3): an organization whose harness list holds anything but plugin names reads on: null', async t => {
|
||||
const odd = fakeOrg('odd', { plugins: { harness: ['alpha', `bad ${PLANT}`] } });
|
||||
const fine = fakeOrg('fine', { on: ['alpha'] });
|
||||
const { admin } = programsFixture(t, [odd, fine]);
|
||||
const status = await admin.status();
|
||||
assert.deepEqual(status.programs.organizations, [{ id: 'odd', on: null }, { id: 'fine', on: ['alpha'] }]);
|
||||
assert.doesNotMatch(JSON.stringify(status), KEY_TEXT);
|
||||
});
|
||||
|
||||
test('A2: harnessesNamed reads every harness and fallback.harness string outside the plugins list', () => {
|
||||
assert.deepEqual([...harnessesNamed({ plugins: { harness: ['alpha'] }, roles: { a: { vars: { harness: 'beta', 'fallback.harness': 'gamma' } } }, projects: { p: { agents: { x: { vars: { harness: 'delta' } } } } } })].sort(), ['beta', 'delta', 'gamma']);
|
||||
assert.equal(harnessesNamed(null), null);
|
||||
assert.equal(harnessesNamed([]), null);
|
||||
});
|
||||
|
||||
const key = (keyId, management, state, agent = 'dev') => ({ keyId, management, agent, issuedAt: '2026-11-01T10:00:00.000Z', state });
|
||||
test('A2 item 8: access gives each organization a health and key ids, never a key, and never reads the usage queue', async t => {
|
||||
const ok = fakeOrg('ok', { keys: [key('0123456789ab', 'stack-managed', 'active'), key('ba9876543210', 'not stack-managed', null, null), key('aaaaaaaaaaaa', 'sentinel', null, null)] });
|
||||
const attention = fakeOrg('attention', { keys: [key('0123456789ab', 'stack-managed', 'active'), key('bbbbbbbbbbbb', 'stack-managed', 'revoked')] });
|
||||
const missing = fakeOrg('missing', { keys: [key('cccccccccccc', 'not stack-managed', null, null)] });
|
||||
const fixtureOrg = fakeOrg('fixture', { fixture: true });
|
||||
const ownModels = fakeOrg('own', { cliproxy: false });
|
||||
const down = fakeOrg('down', { down: true });
|
||||
const noClient = fakeOrg('no-client', { keysError: 'not-configured' });
|
||||
const uncertain = fakeOrg('uncertain', { keysError: 'proxy-uncertain' });
|
||||
const proxyDown = fakeOrg('proxy-down', { keysError: 'proxy-down' });
|
||||
const badShape = fakeOrg('bad-shape', { keys: 'none' });
|
||||
const planted = fakeOrg('planted', { keys: [key('dddddddddddd', 'stack-managed', PLANT, PLANT), { ...key('eeeeeeeeeeee', 'stack-managed', 'active'), value: PLANT, issuedAt: PLANT }] });
|
||||
const plantedId = fakeOrg('planted-id', { keys: [key(PLANT, 'stack-managed', 'active')] });
|
||||
const unread = fakeOrg('unread'); unread.rider.fixture = undefined;
|
||||
const all = [ok, attention, missing, fixtureOrg, ownModels, down, noClient, uncertain, proxyDown, badShape, planted, plantedId, unread];
|
||||
const { admin } = programsFixture(t, all);
|
||||
const out = await admin.access();
|
||||
assert.deepEqual(out.organizations, [
|
||||
{ id: 'ok', health: 'ok', keys: [{ keyId: '0123456789ab', agent: 'dev', state: 'active', issuedAt: '2026-11-01T10:00:00.000Z' }], other: 1, sentinel: 1 },
|
||||
{ id: 'attention', health: 'attention', keys: [{ keyId: '0123456789ab', agent: 'dev', state: 'active', issuedAt: '2026-11-01T10:00:00.000Z' }, { keyId: 'bbbbbbbbbbbb', agent: 'dev', state: 'revoked', issuedAt: '2026-11-01T10:00:00.000Z' }], other: 0, sentinel: 0 },
|
||||
{ id: 'missing', health: 'missing', keys: [], other: 1, sentinel: 0 },
|
||||
{ id: 'fixture', health: 'not-riding', keys: [] },
|
||||
{ id: 'own', health: 'not-riding', keys: [] },
|
||||
{ id: 'down', health: 'unreadable', reason: 'bus-down', keys: [] },
|
||||
{ id: 'no-client', health: 'unreadable', reason: 'no-proxy-client', keys: [] },
|
||||
{ id: 'uncertain', health: 'attention', reason: 'proxy-uncertain', keys: [] },
|
||||
{ id: 'proxy-down', health: 'unreadable', reason: 'unreadable', keys: [] },
|
||||
{ id: 'bad-shape', health: 'unreadable', reason: 'unreadable', keys: [] },
|
||||
{ id: 'planted', health: 'attention', keys: [{ keyId: 'dddddddddddd', agent: null, state: null, issuedAt: '2026-11-01T10:00:00.000Z' }, { keyId: 'eeeeeeeeeeee', agent: 'dev', state: 'active', issuedAt: null }], other: 0, sentinel: 0 },
|
||||
{ id: 'planted-id', health: 'unreadable', reason: 'unreadable', keys: [] },
|
||||
{ id: 'unread', health: 'unreadable', reason: 'unreadable', keys: [] },
|
||||
]);
|
||||
assert.doesNotMatch(JSON.stringify(out), KEY_TEXT);
|
||||
assert.notEqual(out.organizations.find(o => o.id === 'uncertain').health, 'ok');
|
||||
// proxy.keys is the only verb access sends; the usage queue is never read.
|
||||
for (const o of all) for (const [verb] of o.calls) assert.equal(verb, 'proxy.keys');
|
||||
});
|
||||
@@ -6,12 +6,15 @@ import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { PIN } from '../src/common.mjs';
|
||||
import { installPaths } from '../src/settings.mjs';
|
||||
import {
|
||||
processTree, pidListensOn, processStartMs, verifyRestart, initLockStatus, clearInitLock, initFiles, initState,
|
||||
fenceState, createUnitControl, releaseState, receiptFile, unitName,
|
||||
unitLog, serviceKeyState, receiptHistory, appendReceipt, LOG_LINES, HISTORY_LIMIT,
|
||||
} from '../src/admin.mjs';
|
||||
import { secretValues } from '../src/redact.mjs';
|
||||
|
||||
const code = name => error => error.code === name;
|
||||
const scratch = t => { const dir = fs.mkdtempSync(join(tmpdir(), 'pa-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); return dir; };
|
||||
@@ -193,3 +196,198 @@ test('unit actions map proxy-service refusals by code and refuse a missing unit'
|
||||
assert.equal(started.healthy, true); assert.deepEqual(verbs, ['start']);
|
||||
assert.throws(() => createUnitControl({ unitDir: 'relative' }), code('proxy-unit-path'));
|
||||
});
|
||||
|
||||
// #1873 settings-backend A1: the reads behind the setup page's log, service key and history.
|
||||
// Planted keys, one of each Mosaic prefix and short enough that only the prefix rule finds them,
|
||||
// plus long ones of the real shapes.
|
||||
const TAIL = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE';
|
||||
const PLANTED = ['msk-tag-qwertyu', 'mso-tag-acme-qwerty', 'mst-tag-triage-zxcvb', 'msp-tag-plmokn',
|
||||
`msk-k1a2-${TAIL}`, `mso-k1a2-acme-${TAIL}`, `mst-k1a2-triage-${TAIL}`, `msp-k1a2-${TAIL}`];
|
||||
const ENV_SECRET = 'plainwordsonly';
|
||||
const leaks = text => [...PLANTED, ...PLANTED.map(k => k.slice(4)), TAIL.slice(0, 10), ENV_SECRET].filter(bit => text.includes(bit));
|
||||
|
||||
function journal(stdout, { code: exit = 0, calls = [] } = {}) {
|
||||
return async (command, args, options) => { calls.push({ command, args, options }); if (stdout instanceof Error) throw stdout; return { code: exit, stdout, stderr: 'raw stderr msk-tag-qwertyu' }; };
|
||||
}
|
||||
|
||||
test('unitLog asks journalctl for the named unit only, clamps the line count, and shows no planted key', async () => {
|
||||
const calls = [];
|
||||
const lines = ['proxy listening on 127.0.0.1:18432', ...PLANTED.map(k => `upstream refused ${k} for model x`), `auth with ${ENV_SECRET} ok`, 'msk-tag-qwertyu', '', 'last line'];
|
||||
const result = await unitLog({ run: journal(lines.join('\n') + '\n', { calls }), unit: 'mosaic-proxy-zz.service', lines: 10000, env: { X: '1' }, secrets: secretValues({ PROXY_KEY: ENV_SECRET }) });
|
||||
assert.deepEqual(calls[0].args, ['--user', '-u', 'mosaic-proxy-zz.service', '-n', String(LOG_LINES.max), '-o', 'cat', '--no-pager', '-q']);
|
||||
assert.equal(calls[0].command, 'journalctl');
|
||||
assert.deepEqual(calls[0].options.env, { X: '1' });
|
||||
assert.equal(result.unit, 'mosaic-proxy-zz.service');
|
||||
assert.equal(result.lines[0], 'proxy listening on 127.0.0.1:18432', 'a line with nothing secret shows as it is');
|
||||
assert.equal(result.lines.at(-1), 'last line');
|
||||
assert.equal(result.lines.filter(l => l === 'upstream refused [redacted] for model x').length, PLANTED.length);
|
||||
assert.equal(result.redacted, PLANTED.length, 'shown lines with a redaction; dropped lines count in dropped');
|
||||
assert.equal(result.dropped, 2, 'the env-secret line and the key-only line are dropped, the blank one is not counted');
|
||||
assert.deepEqual(leaks(JSON.stringify(result)), []);
|
||||
// At least one line, and a line count that is not an integer is refused.
|
||||
await unitLog({ run: journal('x\n', { calls }), unit: 'mosaic-proxy.service', lines: 0 });
|
||||
assert.equal(calls.at(-1).args[4], '1');
|
||||
await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: 2.5 }), code('invalid-request'));
|
||||
await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: '5' }), code('invalid-request'));
|
||||
});
|
||||
|
||||
test('unitLog keeps only the last lines asked for and never takes a unit name it was not given by unitName', async () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
|
||||
assert.deepEqual((await unitLog({ run: journal(many), unit: 'mosaic-proxy.service', lines: 3 })).lines, ['line 27', 'line 28', 'line 29']);
|
||||
for (const unit of ['sshd.service', 'mosaic-proxy.service; rm', '../mosaic-proxy.service', 'mosaic-proxy-A.service', undefined]) {
|
||||
await assert.rejects(unitLog({ run: journal('x'), unit, lines: 5 }), code('proxy-unit-usage'), String(unit));
|
||||
}
|
||||
});
|
||||
|
||||
test('a journal that cannot be read refuses outcome-unknown with no lines and no other source', async () => {
|
||||
for (const run of [journal(Object.assign(new Error('spawn journalctl ENOENT'), { code: 'ENOENT' })), journal('partial msk-tag-qwertyu', { code: 1 }), async () => ({ code: 0, stdout: null }), async () => null]) {
|
||||
await assert.rejects(unitLog({ run, unit: 'mosaic-proxy.service', lines: 5 }), error => error.code === 'outcome-unknown' && !leaks(String(error.message) + JSON.stringify(error)).length);
|
||||
}
|
||||
});
|
||||
|
||||
test('a secret split across journal lines drops every line', async () => {
|
||||
const result = await unitLog({ run: journal('ok one\nplain\nwordsonly\nok two\n'), unit: 'mosaic-proxy.service', lines: 10, secrets: [ENV_SECRET] });
|
||||
assert.deepEqual(result.lines, []);
|
||||
assert.equal(result.dropped, 4);
|
||||
});
|
||||
|
||||
test('createUnitControl.log runs unitLog for its own unit', async () => {
|
||||
const calls = [];
|
||||
const control = createUnitControl({ instance: 'zz', port: () => 1, run: journal('hello msk-tag-qwertyu\n', { calls }), probe: async () => true, waitMs: 0, pollMs: 0 });
|
||||
assert.deepEqual(await control.log(5), { unit: 'mosaic-proxy-zz.service', lines: ['hello [redacted]'], redacted: 1, dropped: 0 });
|
||||
assert.equal(calls[0].args[2], 'mosaic-proxy-zz.service');
|
||||
});
|
||||
|
||||
test('serviceKeyState answers proxy.json\'s mtime and never opens or stats the key file', t => {
|
||||
const dir = scratch(t);
|
||||
assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'missing' });
|
||||
const files = initFiles(dir, join(dir, 'data'));
|
||||
fs.writeFileSync(files.settings, '{}', { mode: 0o600 });
|
||||
fs.mkdirSync(join(files.key, '..'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(files.key, 'msk-k1a2-' + TAIL, { mode: 0o600 });
|
||||
fs.utimesSync(join(dir, 'proxy.json'), new Date(Date.UTC(2026, 10, 1, 8)), new Date(Date.UTC(2026, 10, 1, 8)));
|
||||
const spies = ['openSync', 'readFileSync', 'statSync', 'lstatSync', 'accessSync', 'existsSync', 'realpathSync', 'readdirSync'].map(name => t.mock.method(fs, name));
|
||||
const state = serviceKeyState(dir);
|
||||
const seen = spies.flatMap(spy => spy.mock.calls.map(call => String(call.arguments[0])));
|
||||
spies.forEach(spy => spy.mock.restore());
|
||||
assert.deepEqual(state, { madeAt: '2026-11-01T08:00:00.000Z', renewedAt: null, renewal: 'not-built', problem: null });
|
||||
assert.deepEqual(seen, [join(dir, 'proxy.json')]);
|
||||
assert.deepEqual(leaks(JSON.stringify(state)), []);
|
||||
});
|
||||
|
||||
test('serviceKeyState gives no date for a proxy.json that is a symlink, a directory or another user\'s', t => {
|
||||
const dir = scratch(t), other = scratch(t);
|
||||
fs.writeFileSync(join(other, 'real.json'), '{}');
|
||||
fs.symlinkSync(join(other, 'real.json'), join(dir, 'proxy.json'));
|
||||
assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'unreadable' });
|
||||
fs.rmSync(join(dir, 'proxy.json')); fs.mkdirSync(join(dir, 'proxy.json'));
|
||||
assert.equal(serviceKeyState(dir).problem, 'unreadable');
|
||||
fs.rmSync(join(dir, 'proxy.json'), { recursive: true }); fs.writeFileSync(join(dir, 'proxy.json'), '{}');
|
||||
assert.equal(serviceKeyState(dir, { uid: process.getuid() + 1 }).problem, 'unreadable');
|
||||
assert.equal(serviceKeyState(dir).problem, null);
|
||||
});
|
||||
|
||||
// A receipt file with `count` entries; some lines padded so the file crosses several 64 KB chunks.
|
||||
function history(t, count, { pad = 0 } = {}) {
|
||||
const dataRoot = scratch(t);
|
||||
for (let i = 0; i < count; i++) appendReceipt(dataRoot, { time: new Date(i * 1000).toISOString(), op: 'fetch', n: i, ...(pad ? { note: 'word '.repeat(pad) } : {}) });
|
||||
return dataRoot;
|
||||
}
|
||||
const pages = (dataRoot, limit, extra = {}) => {
|
||||
const seen = []; let before = null, guard = 0;
|
||||
do {
|
||||
const page = receiptHistory(dataRoot, { limit, before, ...extra });
|
||||
seen.push(page.entries.map(e => e.n));
|
||||
before = page.next;
|
||||
} while (before !== null && ++guard < 1000);
|
||||
return seen;
|
||||
};
|
||||
|
||||
test('receiptHistory pages newest first, oldest first within a page, each entry exactly once across chunks', t => {
|
||||
const dataRoot = history(t, 300, { pad: 150 });
|
||||
assert.ok(fs.statSync(receiptFile(dataRoot)).size > 3 * 65536, 'the file spans several chunks');
|
||||
const seen = pages(dataRoot, 7);
|
||||
assert.deepEqual(seen[0], [293, 294, 295, 296, 297, 298, 299]);
|
||||
assert.deepEqual(seen.flat().sort((a, b) => a - b), Array.from({ length: 300 }, (_, i) => i));
|
||||
assert.equal(new Set(seen.flat()).size, 300);
|
||||
assert.deepEqual(seen.reverse().flat(), Array.from({ length: 300 }, (_, i) => i), 'pages read back to front are the whole history in order');
|
||||
const first = receiptHistory(dataRoot);
|
||||
assert.equal(first.entries.length, HISTORY_LIMIT.default);
|
||||
assert.equal(receiptHistory(dataRoot, { limit: 1000 }).entries.length, HISTORY_LIMIT.max, 'limit is clamped');
|
||||
assert.equal(receiptHistory(dataRoot, { limit: 0 }).entries.length, 1);
|
||||
assert.deepEqual(Object.keys(first.entries[0]).sort(), ['n', 'note', 'op', 'time']);
|
||||
});
|
||||
|
||||
test('receiptHistory skips a torn line and a partial last line, and a write after a page does not repeat or lose entries', t => {
|
||||
const dataRoot = history(t, 5);
|
||||
const file = receiptFile(dataRoot);
|
||||
const text = fs.readFileSync(file, 'utf8').split('\n');
|
||||
text.splice(2, 0, '{"op":"torn', '[1,2]', '{"no":"op"}', 'x'.repeat(70000));
|
||||
// The last line is a whole object whose newline is not written yet: it waits for the newline.
|
||||
fs.writeFileSync(file, text.join('\n') + '{"op":"partial","n":99}');
|
||||
const first = receiptHistory(dataRoot, { limit: 2 });
|
||||
assert.deepEqual(first.entries.map(e => e.n), [3, 4]);
|
||||
assert.deepEqual(receiptHistory(dataRoot, { limit: 1 }).entries.map(e => e.n), [4], 'not shown before its newline');
|
||||
fs.appendFileSync(file, '\n'); appendReceipt(dataRoot, { op: 'fetch', n: 100 });
|
||||
const rest = receiptHistory(dataRoot, { limit: 10, before: first.next });
|
||||
assert.deepEqual(rest.entries.map(e => e.n), [0, 1, 2]);
|
||||
assert.equal(rest.next, null);
|
||||
assert.deepEqual(receiptHistory(dataRoot, { limit: 3 }).entries.map(e => e.n), [4, 99, 100], 'the finished line shows on the next newest read');
|
||||
});
|
||||
|
||||
test('receiptHistory refuses a cursor that is not a line start, past the end, negative or not an integer', t => {
|
||||
const dataRoot = history(t, 3);
|
||||
const size = fs.statSync(receiptFile(dataRoot)).size;
|
||||
for (const before of [1, size + 1, -1, 1.5, '10', Number.MAX_SAFE_INTEGER + 2]) {
|
||||
assert.throws(() => receiptHistory(dataRoot, { before }), code('invalid-request'), String(before));
|
||||
}
|
||||
assert.throws(() => receiptHistory(dataRoot, { limit: 'all' }), code('invalid-request'));
|
||||
assert.deepEqual(receiptHistory(dataRoot, { before: 0 }), { entries: [], next: null });
|
||||
assert.equal(receiptHistory(dataRoot, { before: size }).entries.length, 3);
|
||||
});
|
||||
|
||||
test('receiptHistory withholds an entry whose fields hold an environment secret split across them', t => {
|
||||
const dataRoot = scratch(t);
|
||||
appendReceipt(dataRoot, { op: 'fetch', n: 1 });
|
||||
appendReceipt(dataRoot, { op: 'x', a: 'plainword', b: 'sonly' });
|
||||
appendReceipt(dataRoot, { op: 'x', plainw: 'ordsonly' });
|
||||
appendReceipt(dataRoot, { op: 'x', list: ['plainwo', 'rdsonly'] });
|
||||
appendReceipt(dataRoot, { op: 'fetch', n: 2 });
|
||||
const all = receiptHistory(dataRoot, { limit: 10, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) });
|
||||
assert.deepEqual(all.entries, [{ op: 'fetch', n: 1 }, { withheld: true }, { withheld: true }, { withheld: true }, { op: 'fetch', n: 2 }]);
|
||||
assert.equal(receiptHistory(dataRoot, { limit: 10 }).entries[1].a, 'plainword', 'with no secrets nothing is withheld');
|
||||
});
|
||||
|
||||
test('receiptHistory: a missing file is an empty history; a symlink, FIFO, directory, group-readable or foreign file refuses', t => {
|
||||
const dataRoot = scratch(t);
|
||||
assert.deepEqual(receiptHistory(dataRoot), { entries: [], next: null });
|
||||
assert.throws(() => receiptHistory(dataRoot, { before: 5 }), code('invalid-request'));
|
||||
appendReceipt(dataRoot, { op: 'fetch' });
|
||||
const file = receiptFile(dataRoot);
|
||||
fs.chmodSync(file, 0o640);
|
||||
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
|
||||
fs.chmodSync(file, 0o600);
|
||||
assert.throws(() => receiptHistory(dataRoot, { uid: process.getuid() + 1 }), code('outcome-unknown'));
|
||||
assert.equal(receiptHistory(dataRoot).entries.length, 1);
|
||||
const elsewhere = join(scratch(t), 'x.jsonl'); fs.writeFileSync(elsewhere, '{"op":"planted"}\n', { mode: 0o600 });
|
||||
fs.rmSync(file); fs.symlinkSync(elsewhere, file);
|
||||
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
|
||||
fs.rmSync(file); fs.mkdirSync(file);
|
||||
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
|
||||
fs.rmSync(file, { recursive: true });
|
||||
execFileSync('mkfifo', ['-m', '600', file]);
|
||||
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'), 'a FIFO is refused without blocking');
|
||||
});
|
||||
|
||||
test('receiptHistory shows no planted key from any receipt field, nested value or key name', t => {
|
||||
const dataRoot = scratch(t);
|
||||
for (const key of PLANTED) appendReceipt(dataRoot, { time: new Date(0).toISOString(), op: 'init', note: `made ${key}`, nested: { list: [key, { deeper: key }] }, [key.replace(/-/g, '_')]: 1 });
|
||||
appendReceipt(dataRoot, { op: 'init', env: ENV_SECRET, [`x${ENV_SECRET}`]: 1 });
|
||||
appendReceipt(dataRoot, { op: PLANTED[1] });
|
||||
const all = receiptHistory(dataRoot, { limit: 100, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) });
|
||||
assert.equal(all.entries.length, PLANTED.length + 2);
|
||||
assert.deepEqual(leaks(JSON.stringify(all)), []);
|
||||
assert.deepEqual(all.entries[0], { time: new Date(0).toISOString(), op: 'init', note: 'made [redacted]', nested: { list: ['[redacted]', { deeper: '[redacted]' }] } });
|
||||
assert.deepEqual(all.entries.at(-2), { op: 'init', env: '[redacted]' });
|
||||
assert.deepEqual(all.entries.at(-1), { op: '[redacted]' });
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// P4 pinned8.0.42 regression: absent Claude provider config is HTTP404.
|
||||
// P4 regression since PIN 8.0.42 (still so on 8.0.79): absent Claude provider config is HTTP 404.
|
||||
// Normalize only that fixed GET; all other methods/endpoints/statuses refuse.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
@@ -13,3 +13,13 @@ for (const [field, maximum, code] of [['rotateGraceMinutes', 1440, 'proxy-rotate
|
||||
assert.throws(() => validateProxy({ ...base, [field]: value }, dataRoot), e => e.code === code);
|
||||
});
|
||||
}
|
||||
// #1873 PIN bump: a sidecar written under an earlier PIN keeps the instance config valid.
|
||||
test('a proxy.json written under an earlier PIN reads as the current pinned path', () => {
|
||||
const old = { ...base, binary: '/fixture-data/opt/cliproxyapi/8.0.42/cli-proxy-api' };
|
||||
assert.deepEqual(validateProxy(old, dataRoot), base);
|
||||
assert.deepEqual(validateProxy({ ...old, rotateGraceMinutes: 60 }, dataRoot), { ...base, rotateGraceMinutes: 60 });
|
||||
});
|
||||
for (const binary of ['/bad', '/fixture-data/opt/cliproxyapi/8.0.42/other', '/fixture-data/opt/cliproxyapi/latest/cli-proxy-api',
|
||||
'/fixture-data/opt/cliproxyapi/8.0.42/x/cli-proxy-api', '/fixture-data/opt/cliproxyapi/../cliproxyapi/8.0.42/cli-proxy-api',
|
||||
'/other-data/opt/cliproxyapi/8.0.42/cli-proxy-api', '/fixture-data/opt/cliproxyapi/8.0/cli-proxy-api', 7])
|
||||
test(`proxy-config-invalid: binary ${JSON.stringify(binary)}`, () => assert.throws(() => validateProxy({ ...base, binary }, dataRoot), e => e.code === 'proxy-config-invalid'));
|
||||
@@ -1,4 +1,4 @@
|
||||
// P4 client contract; endpoint/payload cases are probe-pending on PIN8.0.42.
|
||||
// P4 client contract; endpoint/payload cases were probe-pending on PIN 8.0.42.
|
||||
// Catches management key/body/query values leaking into receipts, redirects/retries.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// #1873 settings-backend-a3: the management client's sign-in allow list and the setup status's
|
||||
// provider field both come from the plugin's PROVIDERS. oauthStart refuses the key provider and any
|
||||
// provider a test copy of the list leaves out, before any request. The status field carries id,
|
||||
// label and sign-in kind only: no base URL, no sign-in host, no key text.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { ManagementClient } from '../src/client.mjs';
|
||||
import { createProxyAdmin } from '../src/admin-control.mjs';
|
||||
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
const code = name => error => error.code === name;
|
||||
|
||||
async function server(t) {
|
||||
const asked = [];
|
||||
const s = http.createServer((q, r) => { asked.push(new URL(q.url, 'http://x').searchParams.get('provider')); r.setHeader('content-type', 'application/json'); r.end(JSON.stringify({ status: 'ok', state: 's', url: 'https://claude.ai/x?state=s' })); });
|
||||
await new Promise(r => s.listen(0, '127.0.0.1', r)); t.after(() => new Promise(r => s.close(r)));
|
||||
return { asked, baseUrl: `http://127.0.0.1:${s.address().port}` };
|
||||
}
|
||||
|
||||
test('a3: oauthStart asks the proxy for each sign-in provider in PROVIDERS and refuses the key provider before any request', async t => {
|
||||
const { asked, baseUrl } = await server(t);
|
||||
const c = new ManagementClient({ baseUrl, key: 'a3-management' });
|
||||
for (const p of PROVIDERS.filter(p => p.signIn === 'oauth')) await c.oauthStart(p.id);
|
||||
assert.deepEqual(asked, PROVIDERS.filter(p => p.signIn === 'oauth').map(p => p.id));
|
||||
const keyed = PROVIDERS.filter(p => p.signIn === 'apikey');
|
||||
assert.ok(keyed.length > 0);
|
||||
for (const p of keyed) await assert.rejects(async () => c.oauthStart(p.id), code('proxy-client-invalid'), p.id);
|
||||
for (const id of ['other', '', 'claude&x=1', undefined]) await assert.rejects(async () => c.oauthStart(id), code('proxy-client-invalid'));
|
||||
assert.equal(asked.length, PROVIDERS.filter(p => p.signIn === 'oauth').length, 'no refused provider reached the proxy');
|
||||
});
|
||||
|
||||
test('a3: oauthStart refuses a sign-in provider a test copy of the list leaves out, and asks for one it adds', async t => {
|
||||
const { asked, baseUrl } = await server(t);
|
||||
for (const gone of PROVIDERS.filter(p => p.signIn === 'oauth')) {
|
||||
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: PROVIDERS.filter(p => p !== gone) });
|
||||
await assert.rejects(async () => c.oauthStart(gone.id), code('proxy-client-invalid'), gone.id);
|
||||
}
|
||||
assert.deepEqual(asked, []);
|
||||
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: [...PROVIDERS, { id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }] });
|
||||
await c.oauthStart('fixture-sso');
|
||||
assert.deepEqual(asked, ['fixture-sso']);
|
||||
assert.throws(() => new ManagementClient({ baseUrl, key: 'a3-management', providers: null }), code('proxy-client-invalid'));
|
||||
});
|
||||
|
||||
function admin(t, extra = {}) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'a3-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const unit = { unit: 'mosaic-proxy-a3.service', status: async () => ({ unit: 'mosaic-proxy-a3.service', installed: false, active: 'inactive', healthy: false }) };
|
||||
return createProxyAdmin({ dataRoot, configDir, unit, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}), now: () => new Date(0),
|
||||
orgs: async () => [], harnesses: () => [], rootAgents: () => ({ state: 'absent', agents: {}, assistant: null }), ...extra });
|
||||
}
|
||||
|
||||
test('a3: the status lists the providers as id, label and sign-in kind only, in the plugin\'s order', async t => {
|
||||
const status = await admin(t).status();
|
||||
assert.deepEqual(status.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
|
||||
for (const p of status.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
|
||||
const text = JSON.stringify(status.providers);
|
||||
for (const word of ['https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
|
||||
});
|
||||
|
||||
test('a3: the status field holds no key text, even from a list entry that carries a key, and a provider left out is gone', async t => {
|
||||
const canary = 'a3-status-canary-key-0123456789';
|
||||
const list = [...PROVIDERS.filter(p => p.id !== 'codex'), { id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: `https://${canary}.invalid/`, key: canary, apiKey: canary }];
|
||||
const status = await admin(t, { providers: list }).status();
|
||||
assert.deepEqual(status.providers.map(p => p.id), ['claude', 'z.ai', 'fixture.ai']);
|
||||
assert.equal(JSON.stringify(status.providers).includes(canary), false);
|
||||
assert.equal(JSON.stringify(status).includes(canary), false);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
// #1873 settings-backend A1: the redaction the setup page's log and history reads use. It is
|
||||
// chat-fail's list (packages/harness/src/failure-notice.mjs) with Mosaic's key prefixes added.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { redactLine, redactValue, holdsSecret, secretValues, REDACTED, LINE_MAX } from '../src/redact.mjs';
|
||||
|
||||
// Short keys of each Mosaic prefix, letters only, so no long-run or mixed-run rule catches them:
|
||||
// only the key-prefix line does.
|
||||
const SHORT = { msk: 'msk-tag-qwertyu', mso: 'mso-tag-acme-qwerty', mst: 'mst-tag-triage-zxcvb', msp: 'msp-tag-plmokn' };
|
||||
|
||||
for (const [prefix, key] of Object.entries(SHORT)) {
|
||||
test(`a short ${prefix}- key is redacted from a line, and the rest of the line stays`, () => {
|
||||
const safe = redactLine(`proxy said ${key} was refused`);
|
||||
assert.equal(safe.text, `proxy said ${REDACTED} was refused`);
|
||||
assert.equal(safe.redacted, true);
|
||||
assert.equal(safe.text.includes(key), false);
|
||||
// Upper case, and joined by _ instead of -, too.
|
||||
assert.equal(redactLine(`proxy said ${key.toUpperCase()} x`).text, `proxy said ${REDACTED} x`);
|
||||
assert.equal(redactLine(`proxy said ${key.replace('-', '_')} x`).text, `proxy said ${REDACTED} x`);
|
||||
});
|
||||
}
|
||||
|
||||
test('a short Mosaic key glued to a word or an underscore is redacted', () => {
|
||||
for (const key of Object.values(SHORT)) {
|
||||
for (const glued of [`x${key}`, `_${key}`, `id=x${key}`, `9${key.toUpperCase()}`]) {
|
||||
const safe = redactLine(`proxy said ${glued} was refused`);
|
||||
assert.equal(safe.redacted, true, glued);
|
||||
assert.equal(safe.text.toLowerCase().includes(key.slice(4)), false, glued);
|
||||
assert.match(safe.text, / was refused$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the real key shapes of each prefix are redacted', () => {
|
||||
const tail = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE';
|
||||
for (const key of [`msk-k1a2-${tail}`, `mso-k1a2-acme-${tail}`, `mst-k1a2-triage-${tail}`, `msp-k1a2-${tail}`, `sk-ant-${tail}`]) {
|
||||
const safe = redactLine(`key ${key} rejected by upstream`);
|
||||
assert.equal(safe.text.includes(key.slice(0, 12)), false, key.slice(0, 4));
|
||||
assert.equal(safe.text.includes(tail.slice(0, 8)), false, key.slice(0, 4));
|
||||
}
|
||||
});
|
||||
|
||||
test('bearer and basic tokens, key=value pairs, links, emails and paths never show', () => {
|
||||
const line = 'POST https://u:[email protected]/v1?key=abc Authorization: Bearer abcdefgh api_key=hunter2 token "quoted value" '
|
||||
+ 'by [email protected] from /home/jane/.config/mosaic-dev/proxy.json and ~/.mosaic/x C:\\Users\\j \\\\host\\share Basic dXNlcjpwYXNz eyJhbGciOi.x.y';
|
||||
const safe = redactLine(line);
|
||||
for (const bit of ['u:p@', 'api.example', 'abcdefgh', 'hunter2', 'quoted value', 'jane@', '/home/jane', '.config', '.mosaic', 'Users', 'share', 'dXNlcjpwYXNz', 'eyJhbGci']) {
|
||||
assert.equal(safe.text.includes(bit), false, bit);
|
||||
}
|
||||
assert.match(safe.text, /^POST /);
|
||||
});
|
||||
|
||||
test('a line holding an environment secret is withheld whole, even split by spaces, controls or encoding', () => {
|
||||
const secrets = secretValues({ MOSAIC_PROXY_KEY: 'plainwordsonly', HOME: '/home/x', SHORT_TOKEN: 'abc' });
|
||||
assert.deepEqual(secrets, ['plainwordsonly'], 'only secret-named values of 8 or more characters');
|
||||
for (const line of ['started with plainwordsonly', 'started with plain words only', 'started p\u0000lainwords\u200bonly', 'started %70lainwordsonly', 'started plainwordsonly']) {
|
||||
assert.deepEqual(redactLine(line, secrets), { text: null, redacted: true, withheld: true }, JSON.stringify(line));
|
||||
}
|
||||
assert.equal(holdsSecret('plain\nwords\nonly', secrets), true, 'split across lines');
|
||||
assert.equal(holdsSecret('nothing here', secrets), false);
|
||||
assert.equal(holdsSecret('plainwordsonly', []), false);
|
||||
});
|
||||
|
||||
test('a line that is empty, blank or only redactions is dropped; a long one is cut to the line cap', () => {
|
||||
assert.deepEqual(redactLine(''), { text: null, redacted: false });
|
||||
assert.deepEqual(redactLine(' \u0000\t '), { text: null, redacted: false });
|
||||
assert.deepEqual(redactLine(`${SHORT.mso} ${SHORT.mst}`), { text: null, redacted: true });
|
||||
assert.equal(redactLine(`a ${SHORT.mso} ${SHORT.mst} b`).text, `a ${REDACTED} b`, 'repeated redactions collapse');
|
||||
const long = redactLine('word '.repeat(200));
|
||||
assert.equal(Array.from(long.text).length, LINE_MAX);
|
||||
assert.match(long.text, /\.\.\.$/);
|
||||
assert.equal(redactLine('\u001b[31mred\u001b[0m text').text, 'red text', 'ANSI goes');
|
||||
});
|
||||
|
||||
test('a stored value is redacted all through: strings, nested strings, and keys that read as secrets', () => {
|
||||
const value = { op: 'account.proxy.apikey.add', time: '2026-11-19T12:34:56.789Z', provider: 'openai', note: `got ${SHORT.mso}`, deep: { list: [SHORT.msk, 3, true, null] }, [SHORT.mst.replace(/-/g, '_')]: 'x', 'bad key': 1 };
|
||||
const out = redactValue(value);
|
||||
assert.deepEqual(out, { op: 'account.proxy.apikey.add', time: '2026-11-19T12:34:56.789Z', provider: 'openai', note: `got ${REDACTED}`, deep: { list: [REDACTED, 3, true, null] } });
|
||||
assert.equal(JSON.stringify(out).includes('qwerty'), false);
|
||||
// Depth and size are bounded.
|
||||
assert.deepEqual(redactValue({ a: { b: { c: { d: { e: 1 } } } } }), { a: { b: { c: { d: null } } } });
|
||||
assert.equal(redactValue(Array.from({ length: 100 }, (_, i) => i)).length, 64);
|
||||
assert.equal(redactValue('plainwordsonly', ['plainwordsonly']), REDACTED);
|
||||
assert.equal(redactValue(undefined), null);
|
||||
});
|
||||
|
||||
// chat-fail's shape: redaction runs over a whole line before the cut, so a long run with no spaces
|
||||
// must stay linear.
|
||||
test('a 128000-character run with no spaces is redacted in well under a second', () => {
|
||||
const N = 128000;
|
||||
const secrets = secretValues({ API_KEY: 'plainwordsonly' });
|
||||
for (const run of ['a'.repeat(N), 'a.'.repeat(N / 2), 'a-'.repeat(N / 2), 'a/'.repeat(N / 2), 'a:'.repeat(N / 2), 'a"'.repeat(N / 2), 'mso-'.repeat(N / 4), 'a@'.repeat(N / 2)]) {
|
||||
const started = performance.now();
|
||||
const safe = redactLine(`${run} then the unit stopped`, secrets);
|
||||
const took = performance.now() - started;
|
||||
assert.ok(took < 1000, `${run.slice(0, 4)}... took ${Math.round(took)} ms`);
|
||||
assert.ok(safe.text === null || Array.from(safe.text).length <= LINE_MAX);
|
||||
}
|
||||
// A run that reads as a key is redacted whole, so the words after it show.
|
||||
assert.equal(redactLine(`${'a'.repeat(N)} then the unit stopped`).text, `${REDACTED} then the unit stopped`);
|
||||
});
|
||||
|
||||
// The list is a copy of failure-notice.mjs's. Every line must still match it, except the key-prefix
|
||||
// line, which is the original with mso, mst and msp added after msk, and Mosaic's glued-prefix line
|
||||
// right after it.
|
||||
test('the redaction list matches failure-notice.mjs line for line, with only the prefixes and one line added', () => {
|
||||
const source = file => fs.readFileSync(fileURLToPath(new URL(file, import.meta.url)), 'utf8');
|
||||
const block = text => {
|
||||
const body = /const REDACT = \[\n([\s\S]*?)\n\];/.exec(text)[1];
|
||||
return body.split('\n').map(line => line.trim()).filter(line => line && !line.startsWith('//')).map(line => line.replace(/,\s*\/\/ .*$/, ',').replace(/,$/, ''));
|
||||
};
|
||||
const keyWord = text => /const KEY_WORD = (.*);/.exec(text)[1];
|
||||
const theirs = source('../../harness/src/failure-notice.mjs'), ours = source('../src/redact.mjs');
|
||||
assert.equal(keyWord(ours), keyWord(theirs));
|
||||
const expected = block(theirs).map(line => line.replace('(?:sk|msk|rk|', '(?:sk|msk|mso|mst|msp|rk|'));
|
||||
assert.equal(expected.filter((line, i) => line !== block(theirs)[i]).length, 1, 'the original has one key-prefix line');
|
||||
const at = expected.findIndex(line => line.includes('(?:sk|msk|mso|mst|msp|rk|'));
|
||||
expected.splice(at + 1, 0, '/ms[kotp][-_]\\S+/gi');
|
||||
assert.deepEqual(block(ours), expected);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
// #1873 ride-default slice 1: once Ride all adds the model proxy to an organization, a fenced
|
||||
// proxy refuses each of that organization's launches with proxy-uncertain, a direct anthropic
|
||||
// route included. A real organization bus bound to the instance's proxy, a loopback stand-in for
|
||||
// the proxy's management API (made-up key, kept in this test's memory), and the real Ride all.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { busOrganization } from '../../bus/src/organization-context.mjs';
|
||||
import { createProxyLock } from '../../bus/src/proxy-lock.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { createProxyAdmin } from '../src/admin-control.mjs';
|
||||
|
||||
const MANAGE = 'ride-fence-manage';
|
||||
|
||||
async function ridingBus(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'ride-fence-')), configDir = join(root, 'config');
|
||||
fs.mkdirSync(join(configDir, 'secrets'), { recursive: true, mode: 0o700 });
|
||||
fs.mkdirSync(join(root, 'proxy'), { mode: 0o700 });
|
||||
let keys = ['msk-ride-fence-sentinel'];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end('{}'); return; }
|
||||
if (req.url === '/v8/management/config/access/api-keys') {
|
||||
if (req.method === 'PUT') keys = JSON.parse(Buffer.concat(chunks));
|
||||
res.end(JSON.stringify(req.method === 'GET' ? keys : { status: 'ok' })); return;
|
||||
}
|
||||
if (req.url.startsWith('/v8/management/credentials')) { res.end(JSON.stringify({ files: [], observed_at: '2026-11-19T00:00:00Z' })); return; }
|
||||
if (req.url.startsWith('/v8/management/config/api-keys/')) { res.end('[]'); return; }
|
||||
res.writeHead(404); res.end('{}');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root), doc = businessDoc(root, 'demo');
|
||||
// A direct anthropic route and no model provider: before Ride all, no launch asks the proxy.
|
||||
doc.plugins = { ...doc.plugins, harness: ['pi'] };
|
||||
doc.launch.models['claude-opus-5-5'] = { provider: 'anthropic', model: 'claude-opus-5-5' };
|
||||
doc.roles.coder.vars = { ...doc.roles.coder.vars, harness: 'pi', model: 'claude-opus-5-5', thinking: 'low' };
|
||||
writeJson(join(configDir, 'businesses', 'demo.json'), doc);
|
||||
fs.writeFileSync(join(configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
const business = loadBusiness('demo', { dir: configDir, rolesDir }), resolved = {};
|
||||
for (const instance of Object.keys(business.roles)) resolved[instance] = resolveInstance({ system, business, instance });
|
||||
fs.mkdirSync(join(root, 'data'), { mode: 0o700 }); new Registry(join(root, 'data'));
|
||||
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: busOrganization(business, resolved) },
|
||||
organization: { dir: configDir, rolesDir, system }, proxy: { port, binary: '/fixture-unused' },
|
||||
org: { id: 'demo' }, instanceDataRoot: root, instanceConfigDir: configDir });
|
||||
t.after(async () => { await bus.close(); server.closeAllConnections(); await new Promise(r => server.close(r)); fs.rmSync(root, { recursive: true, force: true }); });
|
||||
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const call = async (verb, args = {}) => bus.broker.request(human, { verb, args });
|
||||
const lock = createProxyLock({ stateDir: join(root, 'proxy'), identity: `${configDir}:${port}` });
|
||||
const admission = async () => {
|
||||
const current = JSON.parse(fs.readFileSync(join(configDir, 'businesses', 'demo.json'), 'utf8'));
|
||||
const revision = (await call('plugins')).revision, entry = current.launch.models['claude-opus-5-5'];
|
||||
return bus.modelAdmission({ business: 'demo', instance: 'coder', modelKey: 'claude-opus-5-5', harness: 'pi', revision, entry,
|
||||
provider: entry.provider, model: entry.model, account: null, route: 'primary', transport: null });
|
||||
};
|
||||
return { root, configDir, bus, call, lock, admission, doc: () => JSON.parse(fs.readFileSync(join(configDir, 'businesses', 'demo.json'), 'utf8')) };
|
||||
}
|
||||
|
||||
test('a fenced proxy refuses each riding organization\'s launches with proxy-uncertain, direct anthropic included', async t => {
|
||||
const b = await ridingBus(t);
|
||||
const dir = fs.mkdtempSync(join(tmpdir(), 'ride-fence-admin-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
const admin = createProxyAdmin({ dataRoot: dir, configDir: dir, unit: { status: async () => ({}) }, buses: async () => [], fetch: async () => ({}),
|
||||
riders: async () => [{ id: 'demo', fixture: false, cliproxy: (b.doc().plugins['model-provider'] ?? []).includes('cliproxy'), changes: '', call: b.call }] });
|
||||
const ride = await admin.rideAll();
|
||||
assert.deepEqual(ride.added, ['demo'], JSON.stringify(ride));
|
||||
assert.deepEqual(b.doc().plugins['model-provider'], ['cliproxy']);
|
||||
assert.equal(b.doc().launch.models['claude-opus-5-5'].module, undefined, 'the direct anthropic route stays as it was');
|
||||
await b.lock.run(async () => b.lock.fence({ org: 'demo', op: 'ride-fence-test' }));
|
||||
assert.deepEqual(await b.admission(), { allow: false, code: 'proxy-uncertain' });
|
||||
assert.deepEqual((await admin.rideAll()).already, ['demo'], 'a second Ride all leaves a riding organization alone');
|
||||
});
|
||||
|
||||
// The launcher half: on an instance with a model proxy, a direct anthropic route never asks the
|
||||
// bus's admission until the organization lists a model provider. After Ride all it does, so the
|
||||
// fenced answer above refuses the launch before any run exists.
|
||||
test('after Ride all the launcher asks admission for a direct anthropic route and a fenced answer refuses the launch', async t => {
|
||||
const { readFileSync } = fs;
|
||||
const { createLauncher } = await import('../../cli/src/launcher.mjs');
|
||||
const { initializeControl } = await import('../../processing-control/src/state.mjs');
|
||||
const { fakeHarnesses, fixture, tmp, withoutHostCredentials } = await import('../../cli/tests/helpers.mjs');
|
||||
// Ride all writes the organization's providers through its bus's plugins.set; this stand-in bus
|
||||
// applies that write to the organization file the launcher reads.
|
||||
const ride = async file => {
|
||||
const dir = fs.mkdtempSync(join(tmpdir(), 'ride-fence-admin-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
const call = async (verb, args = {}) => {
|
||||
const doc = JSON.parse(readFileSync(file, 'utf8'));
|
||||
if (verb === 'plugins') return { revision: 'r1', plugins: doc.plugins };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { assert.equal(args.revision, 'r1'); doc.plugins = { ...doc.plugins, ...args.plugins }; fs.writeFileSync(file, JSON.stringify(doc)); return { revision: 'r2' }; }
|
||||
throw Object.assign(Error('unexpected verb'), { code: 'invalid-request' });
|
||||
};
|
||||
const admin = createProxyAdmin({ dataRoot: dir, configDir: dir, unit: { status: async () => ({}) }, buses: async () => [], fetch: async () => ({}),
|
||||
riders: async () => [{ id: 'acme', fixture: false, cliproxy: false, changes: '', call }] });
|
||||
assert.deepEqual((await admin.rideAll()).added, ['acme']);
|
||||
};
|
||||
const launchOf = async riding => {
|
||||
const root = tmp(t);
|
||||
// A Claude model on a legacy entry counts as OAuth and runs on claude-code only. The stand-in adapter
|
||||
// path skips only the binary check; the launch stops at authorizeLaunch, before any adapter runs.
|
||||
const f = fixture(root, 'acme', doc => {
|
||||
doc.plugins = { ...doc.plugins, harness: ['claude-code'] };
|
||||
doc.launch.models['claude-opus-5-5'] = { provider: 'anthropic', model: 'claude-opus-5-5' };
|
||||
doc.roles.coder.vars = { harness: 'claude-code', model: 'claude-opus-5-5', thinking: 'low' };
|
||||
return doc;
|
||||
});
|
||||
if (riding) await ride(join(root, 'config', 'businesses', 'acme.json'));
|
||||
initializeControl(f.dataRoot); withoutHostCredentials(f.env, { piKey: true });
|
||||
const ops = [];
|
||||
const host = { business: 'acme', beforeClose: () => {}, op: async x => {
|
||||
ops.push(x.op);
|
||||
if (x.op === 'identity') return { business: 'acme', role: 'pm' };
|
||||
if (x.op === 'mayLaunch') return { allow: true };
|
||||
if (x.op === 'modelAdmission') return { allow: false, code: 'proxy-uncertain' };
|
||||
if (x.op === 'authorizeLaunch') throw Object.assign(Error('fixture authorization stop'), { code: 'fixture-policy' });
|
||||
return {};
|
||||
} };
|
||||
const makeLoader = await fakeHarnesses(t, { 'claude-code': '/fixture-unused' }, write => write('model-provider', 'cliproxy', `export * from ${JSON.stringify(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).href)};`));
|
||||
const system = { ...JSON.parse(readFileSync(f.config, 'utf8')), proxy: { port: 1, binary: '/fixture-unused' } };
|
||||
const launcher = createLauncher({ host, system, env: f.env, makeLoader, bwrap: '/usr/bin/true', log: () => {} });
|
||||
return { answer: await launcher.fromSession('fixture-cap', 'coder'), ops };
|
||||
};
|
||||
const before = await launchOf(false);
|
||||
assert.equal(before.ops.includes('modelAdmission'), false, JSON.stringify(before));
|
||||
assert.equal(before.ops.includes('mayLaunch'), true, 'the before launch reached the limit checks');
|
||||
assert.notDeepEqual(before.answer, { ok: false, error: 'proxy-uncertain' });
|
||||
const after = await launchOf(true);
|
||||
assert.equal(after.ops.includes('modelAdmission'), true, JSON.stringify(after));
|
||||
assert.deepEqual(after.answer, { ok: false, error: 'proxy-uncertain' });
|
||||
});
|
||||
@@ -0,0 +1,546 @@
|
||||
// #1873 ride-default slice 1: Ride all adds the instance's model proxy (cliproxy) to the owner's
|
||||
// organizations, skips and names the ones it must not change, and lists fixture organizations,
|
||||
// which move to the owner's models only by a separate confirmed action.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createProxyAdmin } from '../src/admin-control.mjs';
|
||||
import { initFiles, receiptFile, appendReceipt, receiptsText, ownedText } from '../src/admin.mjs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { PIN } from '../src/common.mjs';
|
||||
import { cliproxyRemoved, localRide, riddenOrgs, pickModel, fixtureMove, moveFixtureOrg, readRider, ownerModelsFrom } from '../src/ride.mjs';
|
||||
import * as orgService from '../../organization/src/org-service.mjs';
|
||||
import { orgUsesFixture } from '../../cli/src/dev-fixture.mjs';
|
||||
|
||||
const stopped = async () => ({ stopped: true, running: [] });
|
||||
const row = (over = {}) => ({ key: 'claude-claude-opus-5-5', module: 'cliproxy', upstream: 'claude', provider: 'anthropic', model: 'claude-opus-5-5', label: 'Claude Opus 5.5', available: true, reason: null, harnesses: ['claude-code', 'pi'], ...over });
|
||||
const glm = row({ key: 'zai-glm-5-3', upstream: 'zai', provider: 'zai', model: 'glm-5.3', label: 'GLM 5.3', harnesses: ['pi'] });
|
||||
const committed = changes => JSON.stringify({ state: 'committed', changes }) + '\n';
|
||||
const busError = code => Object.assign(new Error('bus text that must not leak'), { code });
|
||||
|
||||
// A fake organization bus: `plugins` answers the providers and revision; `proxy.accounts` answers
|
||||
// or throws; `plugins.set` records the write.
|
||||
function bus({ providers = ['fixture'], down = false, client = true, accounts = null, set = null } = {}) {
|
||||
const calls = [];
|
||||
const call = async (verb, args) => {
|
||||
calls.push([verb, args]);
|
||||
if (down) throw busError('no-bus-host');
|
||||
if (verb === 'plugins') return { business: 'x', revision: 'rev-1', plugins: { 'model-provider': providers }, available: {} };
|
||||
if (verb === 'proxy.accounts') { if (accounts) throw accounts; if (!client) throw busError('not-configured'); return { accounts: [] }; }
|
||||
if (verb === 'plugins.set') { if (set) throw set; providers = args.plugins['model-provider']; return { revision: 'rev-2' }; }
|
||||
throw new Error(`unexpected ${verb}`);
|
||||
};
|
||||
return { call, calls };
|
||||
}
|
||||
function admin(t, { riders, ownerModels, move, unitState } = {}) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'rd-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const state = unitState ?? { installed: false, active: 'inactive', healthy: false };
|
||||
const unit = { unit: 'mosaic-proxy-zz.service', status: async () => ({ unit: 'mosaic-proxy-zz.service', ...state }) };
|
||||
const sha = text => createHash('sha256').update(text).digest('hex');
|
||||
const pin = { ...PIN, archive: { ...PIN.archive, sha256: sha('a') }, binary: { sha256: sha('b') }, panel: { ...PIN.panel, sha256: sha('p') } };
|
||||
const a = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: async () => ({}), now: () => new Date(0), pin,
|
||||
...(riders ? { riders } : {}), ...(ownerModels ? { ownerModels } : {}), ...(move !== undefined ? { move } : {}) });
|
||||
return { admin: a, configDir, dataRoot, pin, state };
|
||||
}
|
||||
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
|
||||
|
||||
test('a change log shows cliproxy removed only when a committed write took it off', () => {
|
||||
assert.equal(cliproxyRemoved(''), false);
|
||||
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['fixture', 'cliproxy'] }])), false);
|
||||
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }])), true);
|
||||
assert.equal(cliproxyRemoved(committed([{ path: 'plugins', old: { 'model-provider': ['cliproxy'] }, new: { 'model-provider': ['fixture'] } }])), true);
|
||||
assert.equal(cliproxyRemoved(JSON.stringify({ state: 'staged', changes: [{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }] }) + '\n'), false, 'a write that did not commit removed nothing');
|
||||
assert.equal(cliproxyRemoved(committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }, { path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]) ), true, 'a removal stays a removal once seen');
|
||||
assert.equal(cliproxyRemoved('{not json\n'), null);
|
||||
assert.equal(cliproxyRemoved(null), null);
|
||||
});
|
||||
|
||||
test('the local rule names unreadable, removed, fixture, already and ready in that order', () => {
|
||||
const removed = committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]);
|
||||
assert.equal(localRide({ fixture: undefined, cliproxy: false, changes: '' }), 'unreadable');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: undefined, changes: '' }), 'unreadable');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: null }), 'unreadable');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: false, changes: removed }), 'removed');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: false, changes: '' }), 'fixture');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '' }), 'already');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '' }), 'ready');
|
||||
// Review round: an organization that uses cliproxy now is already riding, whatever its history.
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: removed }), 'already', 'removed once and added back');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: null }), 'already');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: '' }), 'fixture');
|
||||
// The proxy's receipts show it put cliproxy on the organization, and it lacks cliproxy now.
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '', ridden: true }), 'removed');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: false, changes: '', ridden: true }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '', ridden: true }), 'already');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: '', ridden: null }), 'unreadable');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: '', ridden: null }), 'already');
|
||||
});
|
||||
|
||||
test('the proxy receipts name each organization ride all added, tried to add, moved or saw removed', () => {
|
||||
const lines = records => records.map(r => JSON.stringify(r)).join('\n') + '\n';
|
||||
const text = lines([{ op: 'ride-all', added: ['a', 'b'], skipped: [{ id: 'c', reason: 'bus-down' }], fixtures: ['d'] }, { op: 'ride-move', org: 'e', model: 'm' },
|
||||
{ op: 'fetch', added: ['f'] }, { op: 'ride-intent', org: 'g' }, { op: 'ride-removed', org: 'h' }]);
|
||||
assert.deepEqual([...riddenOrgs(text)].sort(), ['a', 'b', 'e', 'g', 'h']);
|
||||
assert.deepEqual([...riddenOrgs('')], []);
|
||||
assert.equal(riddenOrgs(null), null);
|
||||
// Round 3 (P2a): a line that does not parse, or a ride record of the wrong shape, fails closed.
|
||||
assert.equal(riddenOrgs(text + '{torn'), null, 'a torn line');
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-all', added: [7] }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-all', added: 'a' }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-intent' }])), null);
|
||||
assert.equal(riddenOrgs(lines([{ op: 'ride-removed', org: 3 }])), null);
|
||||
assert.equal(riddenOrgs('7\n'), null, 'a line that is not a record');
|
||||
// Round 3 (P2b): an intent the bus then showed was not applied is cleared, and only that intent.
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], []);
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-all', added: ['g'] }, { op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], ['g'], 'an earlier add stays');
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-removed', org: 'g' }, { op: 'ride-intent', org: 'g' }, { op: 'ride-not-added', org: 'g' }]))], ['g'], 'an earlier removal stays');
|
||||
assert.deepEqual([...riddenOrgs(lines([{ op: 'ride-not-added', org: 'g' }, { op: 'ride-intent', org: 'g' }]))], ['g'], 'a later intent stands');
|
||||
});
|
||||
|
||||
test('a change log that shows cliproxy on the organization at any time, or a write to its providers it cannot read, counts as removed once cliproxy is gone', () => {
|
||||
// Round 3 (P1 case b): added on the Settings page, then removed on the admin page, which writes no log entry.
|
||||
const added = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]);
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: added }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: true, changes: added }), 'already');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: added }), 'fixture', 'a fixture organization that lists cliproxy is still listed to move');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins', old: null, new: { 'model-provider': ['cliproxy'] } }]) }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: '', old: null, new: { plugins: { 'model-provider': ['cliproxy'] } } }]) }), 'removed');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', oldPresent: true, newPresent: true }]) }), 'removed', 'a paths-only write to the providers');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'roles.chief.vars', oldPresent: true, newPresent: true }]) }), 'ready', 'a paths-only write elsewhere');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['openai'] }]) }), 'ready');
|
||||
assert.equal(localRide({ fixture: false, cliproxy: false, changes: JSON.stringify({ state: 'aborted', changes: [{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }] }) + '\n' }), 'ready', 'a write that did not commit');
|
||||
});
|
||||
|
||||
test('the reviewer probe: an organization created from the cliproxy preset and saved without it on its admin page is skipped as removed', async t => {
|
||||
// P1 case a. Nothing in the change log: the preset made it, the admin page took it off. The
|
||||
// admin page leaves a ride-removed receipt (proxy admin rideRemoved) before it saves.
|
||||
const b = bus({ providers: [] });
|
||||
const { admin: a, dataRoot } = admin(t, { riders: async () => [{ id: 'p', fixture: false, cliproxy: false, changes: '', call: b.call }] });
|
||||
assert.equal(a.rideRemoved('p').op, 'ride-removed');
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 'p', reason: 'removed' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(dataRoot).filter(x => x.op === 'ride-removed').map(x => x.org), ['p']);
|
||||
assert.throws(() => a.rideRemoved('../x'), /proxy-org-invalid|invalid/);
|
||||
});
|
||||
|
||||
test('the reviewer probe: an organization added on the Settings page and removed on its admin page is skipped as removed', async t => {
|
||||
// P1 case b, with no ride-removed receipt at all: the change log's add is enough.
|
||||
const b = bus({ providers: [] });
|
||||
const log = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]);
|
||||
const { admin: a } = admin(t, { riders: async () => [{ id: 's', fixture: false, cliproxy: false, changes: log, call: b.call }] });
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, []); assert.deepEqual(r.skipped, [{ id: 's', reason: 'removed' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('each add leaves its intent receipt before plugins.set, and an add whose outcome is unknown stays recorded', async t => {
|
||||
// P2b. The bus reads the receipts at the moment of the write.
|
||||
let seen = null, dataRootOf = null;
|
||||
const order = [];
|
||||
const watching = id => { const b = bus({ providers: [] }); const call = async (verb, args) => { if (verb === 'plugins.set') { order.push(id); seen = receipts(dataRootOf()).map(r => `${r.op}:${r.org ?? ''}`); } return b.call(verb, args); }; return { ...b, call }; };
|
||||
const one = watching('one'), two = watching('two');
|
||||
const f = admin(t, { riders: async () => [{ id: 'one', fixture: false, cliproxy: false, changes: '', call: one.call }, { id: 'two', fixture: false, cliproxy: false, changes: '', call: two.call }] });
|
||||
dataRootOf = () => f.dataRoot;
|
||||
await f.admin.rideAll();
|
||||
assert.deepEqual(order, ['one', 'two']);
|
||||
assert.deepEqual(seen, ['ride-intent:one', 'ride-intent:two'], 'the first add is on record before the second starts');
|
||||
// Probe C: plugins.set commits, then the call times out. The bus shows cliproxy, so the intent stands.
|
||||
let providers = [];
|
||||
const timeout = { calls: [], call: async (verb, args) => {
|
||||
if (verb === 'plugins') return { revision: 'r1', plugins: { 'model-provider': providers } };
|
||||
if (verb === 'proxy.accounts') return { accounts: [] };
|
||||
if (verb === 'plugins.set') { providers = args.plugins['model-provider']; throw busError('timeout'); }
|
||||
} };
|
||||
let cp = false;
|
||||
const c = admin(t, { riders: async () => [{ id: 't', fixture: false, cliproxy: cp, changes: '', call: timeout.call }] });
|
||||
const first = await c.admin.rideAll();
|
||||
assert.deepEqual(first.skipped, [{ id: 't', reason: 'timeout' }]);
|
||||
assert.deepEqual(receipts(c.dataRoot).filter(r => r.org === 't').map(r => r.op), ['ride-intent']);
|
||||
providers = []; // the owner took it off
|
||||
assert.deepEqual((await c.admin.rideAll()).skipped, [{ id: 't', reason: 'removed' }]);
|
||||
// A refusal the bus shows was not applied clears the intent, so the organization can ride later.
|
||||
const refusedBus = bus({ providers: [], set: busError('revision-conflict') });
|
||||
const d = admin(t, { riders: async () => [{ id: 'q', fixture: false, cliproxy: false, changes: '', call: refusedBus.call }] });
|
||||
assert.deepEqual((await d.admin.rideAll()).skipped, [{ id: 'q', reason: 'revision-conflict' }]);
|
||||
assert.deepEqual(receipts(d.dataRoot).filter(r => r.org === 'q').map(r => r.op), ['ride-intent', 'ride-not-added']);
|
||||
assert.deepEqual((await d.admin.status()).ride, [{ id: 'q', state: 'ready' }]);
|
||||
// A bus that does not answer the re-read leaves the intent: the add may have happened.
|
||||
let gone = false;
|
||||
const lost = { call: async (verb, args) => { if (gone) throw busError('no-bus-host'); if (verb === 'plugins') return { revision: 'r1', plugins: { 'model-provider': [] } }; if (verb === 'proxy.accounts') return { accounts: [] }; if (verb === 'plugins.set') { gone = true; throw busError('timeout'); } } };
|
||||
const e = admin(t, { riders: async () => [{ id: 'l', fixture: false, cliproxy: false, changes: '', call: lost.call }] });
|
||||
await e.admin.rideAll();
|
||||
assert.deepEqual(receipts(e.dataRoot).filter(r => r.org === 'l').map(r => r.op), ['ride-intent']);
|
||||
});
|
||||
|
||||
test('a removal saved while Ride all works on earlier organizations is read before the later add', async t => {
|
||||
// Re-check 3, P3-1: the run's first read of the receipts showed nothing for 'late'. While the run
|
||||
// reads 'first', the owner takes cliproxy off 'late' on its admin page (a ride-removed receipt).
|
||||
let a = null;
|
||||
const first = bus({ providers: [] }), late = bus({ providers: [] });
|
||||
const firstCall = async (verb, args) => { if (verb === 'plugins') a.rideRemoved('late'); return first.call(verb, args); };
|
||||
const f = admin(t, { riders: async () => [{ id: 'first', fixture: false, cliproxy: false, changes: '', call: firstCall }, { id: 'late', fixture: false, cliproxy: false, changes: '', call: late.call }] });
|
||||
a = f.admin;
|
||||
const r = await a.rideAll();
|
||||
assert.deepEqual(r.added, ['first']); assert.deepEqual(r.skipped, [{ id: 'late', reason: 'removed' }]);
|
||||
assert.equal(late.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(f.dataRoot).filter(x => x.org === 'late').map(x => x.op), ['ride-removed']);
|
||||
// Receipts that turn unreadable during the run skip the later add as unreadable.
|
||||
const g1 = bus({ providers: [] }), g2 = bus({ providers: [] });
|
||||
let g = null;
|
||||
const tear = async (verb, args) => { if (verb === 'plugins') { appendReceipt(g.dataRoot, { op: 'fetch' }); fs.appendFileSync(receiptFile(g.dataRoot), '{torn\n'); } return g1.call(verb, args); };
|
||||
g = admin(t, { riders: async () => [{ id: 'one', fixture: false, cliproxy: false, changes: '', call: tear }, { id: 'two', fixture: false, cliproxy: false, changes: '', call: g2.call }] });
|
||||
const s = await g.admin.rideAll();
|
||||
assert.deepEqual(s.skipped, [{ id: 'one', reason: 'unreadable' }, { id: 'two', reason: 'unreadable' }]);
|
||||
assert.equal(g2.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('settings-p3 R1: the change log is read again before each add, and a read that fails skips the add', async t => {
|
||||
// While Ride all works on 'first', the owner adds cliproxy to 'late' on its Settings page and takes it
|
||||
// off again. Only its change log shows that; the receipts do not. The run's first read showed nothing.
|
||||
let lateLog = '';
|
||||
const first = bus({ providers: [] }), late = bus({ providers: [] });
|
||||
const firstCall = async (verb, args) => { if (verb === 'plugins') lateLog = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]) + committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]); return first.call(verb, args); };
|
||||
const f = admin(t, { riders: async () => [{ id: 'first', fixture: false, cliproxy: false, changes: '', call: firstCall }, { id: 'late', fixture: false, cliproxy: false, changes: lateLog, call: late.call }] });
|
||||
const r = await f.admin.rideAll();
|
||||
assert.deepEqual(r.added, ['first']); assert.deepEqual(r.skipped, [{ id: 'late', reason: 'removed' }]);
|
||||
assert.equal(late.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(f.dataRoot).filter(x => x.org === 'late').map(x => x.op), []);
|
||||
// Fail closed: a change log that can no longer be read, an organization that is no longer listed,
|
||||
// or a list that can't be read again skips the add as unreadable, with no intent and no plugins.set.
|
||||
for (const [name, again] of [
|
||||
['log unreadable', b => [{ id: 'o', fixture: false, cliproxy: false, changes: null, call: b.call }]],
|
||||
['no longer listed', () => []],
|
||||
['list throws', () => { throw new Error('read failed'); }],
|
||||
]) {
|
||||
const b = bus({ providers: [] });
|
||||
let reads = 0;
|
||||
const g = admin(t, { riders: async () => (reads++ === 0 ? [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: b.call }] : again(b)) });
|
||||
assert.deepEqual((await g.admin.rideAll()).skipped, [{ id: 'o', reason: 'unreadable' }], name);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false, name);
|
||||
assert.deepEqual(receipts(g.dataRoot).filter(x => x.op === 'ride-intent'), [], name);
|
||||
}
|
||||
});
|
||||
|
||||
test('settings-p3 review P3-1: an organization that took cliproxy during the run reads as already using it, with no add', async t => {
|
||||
const b = bus({ providers: [] });
|
||||
let reads = 0;
|
||||
const f = admin(t, { riders: async () => [{ id: 'o', fixture: false, cliproxy: reads++ > 0, changes: '', call: b.call }] });
|
||||
const r = await f.admin.rideAll();
|
||||
assert.deepEqual([r.added, r.already, r.skipped], [[], ['o'], []]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual(receipts(f.dataRoot).filter(x => x.op === 'ride-intent'), []);
|
||||
});
|
||||
|
||||
test('an intent receipt that cannot be written stops that add before plugins.set', async t => {
|
||||
const b = bus({ providers: [] });
|
||||
const f = admin(t, { riders: async () => [{ id: 'w', fixture: false, cliproxy: false, changes: '', call: b.call }] });
|
||||
appendReceipt(f.dataRoot, { op: 'fetch' });
|
||||
fs.chmodSync(receiptFile(f.dataRoot), 0o400); // readable by its owner only, not writable
|
||||
const r = await f.admin.rideAll();
|
||||
assert.deepEqual(r.skipped, [{ id: 'w', reason: 'not-recorded' }]);
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
});
|
||||
|
||||
test('receipts that are torn, a symlink, not the owner\'s or open to others are unreadable, and every organization without cliproxy is skipped', async t => {
|
||||
// P2a and P3 (probes D and E).
|
||||
const b = bus({ providers: [] });
|
||||
const f = admin(t, { riders: async () => [{ id: 'z', fixture: false, cliproxy: false, changes: '', call: b.call }, { id: 'y', fixture: false, cliproxy: true, changes: '', call: b.call }] });
|
||||
const file = receiptFile(f.dataRoot);
|
||||
appendReceipt(f.dataRoot, { op: 'fetch' });
|
||||
fs.appendFileSync(file, '{"op":"ride-all","added":["z"]');
|
||||
let r = await f.admin.rideAll();
|
||||
assert.deepEqual(r.skipped, [{ id: 'z', reason: 'unreadable' }], 'torn'); assert.deepEqual(r.already, ['y']);
|
||||
fs.rmSync(file); fs.writeFileSync(join(f.dataRoot, 'state', 'empty'), '', { mode: 0o600 });
|
||||
fs.symlinkSync(join(f.dataRoot, 'state', 'empty'), file);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'symlink');
|
||||
assert.equal(fs.lstatSync(file).isSymbolicLink(), true);
|
||||
fs.rmSync(file); fs.writeFileSync(file, '', { mode: 0o600 }); fs.chmodSync(file, 0o640);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'group-readable');
|
||||
fs.rmSync(file); fs.mkdirSync(file);
|
||||
assert.deepEqual((await f.admin.rideAll()).skipped, [{ id: 'z', reason: 'unreadable' }], 'not a file');
|
||||
fs.rmSync(file, { recursive: true });
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
|
||||
assert.deepEqual((await f.admin.rideAll()).added, ['z'], 'no receipt file is no history');
|
||||
});
|
||||
|
||||
test('the receipts are read only when the Console\'s own user owns them', t => {
|
||||
const f = admin(t);
|
||||
appendReceipt(f.dataRoot, { op: 'ride-removed', org: 'p' });
|
||||
assert.match(receiptsText(f.dataRoot), /"ride-removed"/);
|
||||
assert.equal(receiptsText(f.dataRoot, { uid: process.getuid() + 1 }), null, 'another user\'s file');
|
||||
});
|
||||
|
||||
test('a FIFO in place of the receipts is unreadable and never blocks the read', t => {
|
||||
const f = admin(t);
|
||||
fs.mkdirSync(join(f.dataRoot, 'state'), { mode: 0o700 });
|
||||
execFileSync('mkfifo', ['-m', '600', receiptFile(f.dataRoot)]);
|
||||
assert.equal(receiptsText(f.dataRoot), null);
|
||||
});
|
||||
|
||||
test('the change log read takes the writer\'s rule: group readable is fine, group writable, a symlink or a missing file is not', t => {
|
||||
const dir = fs.mkdtempSync(join(tmpdir(), 'rdo-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
const file = join(dir, 'changes.jsonl'); fs.writeFileSync(file, 'x\n', { mode: 0o600 }); fs.chmodSync(file, 0o640);
|
||||
assert.equal(ownedText(file, { mask: 0o022 }), 'x\n');
|
||||
fs.chmodSync(file, 0o660);
|
||||
assert.throws(() => ownedText(file, { mask: 0o022 }), { code: 'proxy-file-refused' });
|
||||
fs.chmodSync(file, 0o600); fs.symlinkSync(file, join(dir, 'link'));
|
||||
assert.throws(() => ownedText(join(dir, 'link'), { mask: 0o022 }), { code: 'ELOOP' });
|
||||
assert.throws(() => ownedText(join(dir, 'gone'), { mask: 0o022 }), { code: 'ENOENT' });
|
||||
// readRider, as the Console wires it: a refused log is unreadable, a missing one is empty.
|
||||
const doc = { plugins: { 'model-provider': [] } };
|
||||
fs.chmodSync(file, 0o660);
|
||||
assert.equal(readRider({ id: 'a', read: () => doc, readLog: () => ownedText(file, { mask: 0o022 }), isFixture: () => false }).changes, null);
|
||||
assert.equal(readRider({ id: 'a', read: () => doc, readLog: () => ownedText(join(dir, 'gone'), { mask: 0o022 }), isFixture: () => false }).changes, '');
|
||||
});
|
||||
|
||||
test('a fixture organization that uses cliproxy now, with a removal in its log, is removed, not movable', () => {
|
||||
const log = committed([{ path: 'plugins.model-provider', old: ['fixture', 'cliproxy'], new: ['fixture'] }]) + committed([{ path: 'plugins.model-provider', old: ['fixture'], new: ['fixture', 'cliproxy'] }]);
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: log }), 'removed');
|
||||
assert.equal(localRide({ fixture: true, cliproxy: true, changes: '' }), 'fixture');
|
||||
});
|
||||
|
||||
test('an organization ride all once added and its owner then saved without cliproxy is skipped as removed', async t => {
|
||||
// The organization's file as the Console reads it. The organization admin page saves a whole
|
||||
// document and writes no change-log entry, so the log stays empty after the owner's removal.
|
||||
let cliproxy = false;
|
||||
const b = bus({ providers: [] });
|
||||
const { admin: a, dataRoot } = admin(t, { riders: async () => [{ id: 'a', fixture: false, cliproxy, changes: '', call: b.call }] });
|
||||
assert.deepEqual((await a.rideAll()).added, ['a']);
|
||||
cliproxy = true;
|
||||
assert.deepEqual((await a.rideAll()).already, ['a']);
|
||||
cliproxy = false; // the owner saved the organization without cliproxy on its admin page
|
||||
const second = await a.rideAll();
|
||||
assert.deepEqual(second.skipped, [{ id: 'a', reason: 'removed' }], JSON.stringify(second));
|
||||
assert.equal(b.calls.filter(([verb]) => verb === 'plugins.set').length, 1, 'no second write');
|
||||
assert.deepEqual((await a.status()).ride, [{ id: 'a', state: 'removed' }]);
|
||||
// A fixture organization the proxy once moved, and its owner then put back on stand-in models, is not moved again.
|
||||
const moved = { id: 'f', fixture: true, cliproxy: false, changes: '', call: bus({ down: true }).call };
|
||||
const m = admin(t, { riders: async () => [moved], ownerModels: async () => ({ proxy: true, riding: true, models: [row()] }), move: async () => ({ moved: true, model: row().key }) });
|
||||
appendReceipt(m.dataRoot, { op: 'ride-move', org: 'f', model: row().key });
|
||||
assert.deepEqual(await m.admin.rideMove({ org: 'f' }), { org: 'f', moved: false, reason: 'removed' });
|
||||
// Receipts that cannot be read name every organization without cliproxy unreadable.
|
||||
fs.chmodSync(receiptFile(dataRoot), 0o200);
|
||||
assert.deepEqual((await a.rideAll()).skipped, [{ id: 'a', reason: 'unreadable' }]);
|
||||
});
|
||||
|
||||
test('the owner model is a usable catalogue row that serves every harness, claude first', () => {
|
||||
assert.equal(pickModel([glm, row()]).key, 'claude-claude-opus-5-5');
|
||||
assert.equal(pickModel([glm]).key, 'zai-glm-5-3');
|
||||
assert.equal(pickModel([glm, row()], ['claude-code']).key, 'claude-claude-opus-5-5');
|
||||
assert.equal(pickModel([glm], ['claude-code']), null);
|
||||
assert.equal(pickModel([row({ available: false }), row({ reason: 'unverified' }), row({ module: 'fixture' })]), null, 'a model the catalogue does not offer is never picked');
|
||||
assert.equal(pickModel(null), null);
|
||||
});
|
||||
|
||||
test('ride all adds cliproxy through plugins.set and skips and names each organization it must not change', async t => {
|
||||
const ready = bus({ providers: [] }), noClient = bus({ providers: [], client: false }), down = bus({ down: true }), checkFails = bus({ providers: [], accounts: busError('proxy-down') });
|
||||
const refused = bus({ providers: [], set: busError('revision-conflict') }), alreadyBus = bus({ providers: ['cliproxy'] }), removedBus = bus({ providers: [] }), fixtureBus = bus({ down: true });
|
||||
const unreadable = bus({ providers: [] }), raced = bus({ providers: ['cliproxy'] });
|
||||
const riders = async () => [
|
||||
{ id: 'ready', fixture: false, cliproxy: false, changes: '', call: ready.call },
|
||||
{ id: 'removed', fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]), call: removedBus.call },
|
||||
{ id: 'down', fixture: false, cliproxy: false, changes: '', call: down.call },
|
||||
{ id: 'noclient', fixture: false, cliproxy: false, changes: '', call: noClient.call },
|
||||
{ id: 'checkfails', fixture: false, cliproxy: false, changes: '', call: checkFails.call },
|
||||
{ id: 'refused', fixture: false, cliproxy: false, changes: '', call: refused.call },
|
||||
{ id: 'already', fixture: false, cliproxy: true, changes: '', call: alreadyBus.call },
|
||||
{ id: 'raced', fixture: false, cliproxy: false, changes: '', call: raced.call },
|
||||
{ id: 'unreadable', fixture: undefined, cliproxy: undefined, changes: '', call: unreadable.call },
|
||||
{ id: 'stand-in', fixture: true, cliproxy: false, changes: '', call: fixtureBus.call, status: async () => ({ pid: null }) },
|
||||
];
|
||||
const { admin: a, dataRoot } = admin(t, { riders });
|
||||
const result = await a.rideAll();
|
||||
assert.deepEqual(result.added, ['ready']);
|
||||
assert.deepEqual(result.already, ['already', 'raced']);
|
||||
assert.deepEqual(result.skipped, [
|
||||
{ id: 'removed', reason: 'removed' }, { id: 'down', reason: 'bus-down' }, { id: 'noclient', reason: 'no-proxy-client' },
|
||||
{ id: 'checkfails', reason: 'proxy-check-failed' }, { id: 'refused', reason: 'revision-conflict' }, { id: 'unreadable', reason: 'unreadable' },
|
||||
]);
|
||||
assert.deepEqual(result.fixtures, [{ id: 'stand-in', running: false }]);
|
||||
assert.deepEqual(ready.calls.find(([v]) => v === 'plugins.set'), ['plugins.set', { revision: 'rev-1', plugins: { 'model-provider': ['cliproxy'] } }]);
|
||||
for (const [name, b] of Object.entries({ removedBus, down, noClient, checkFails, alreadyBus, raced, unreadable, fixtureBus }))
|
||||
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false, `${name} gets no write`);
|
||||
assert.equal(JSON.stringify(result).includes('must not leak'), false);
|
||||
const last = receipts(dataRoot).at(-1);
|
||||
assert.equal(last.op, 'ride-all'); assert.deepEqual(last.added, ['ready']); assert.deepEqual(last.fixtures, ['stand-in']);
|
||||
});
|
||||
|
||||
test('ride all keeps the providers an organization already has', async t => {
|
||||
const b = bus({ providers: ['openai'] });
|
||||
const { admin: a } = admin(t, { riders: async () => [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: b.call }] });
|
||||
assert.deepEqual((await a.rideAll()).added, ['o']);
|
||||
assert.deepEqual(b.calls.find(([v]) => v === 'plugins.set')[1].plugins, { 'model-provider': ['openai', 'cliproxy'] });
|
||||
});
|
||||
|
||||
test('status names ride all after accounts while an organization can still ride', async t => {
|
||||
let list = [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: bus().call }];
|
||||
const f = admin(t, { riders: async () => list, unitState: { installed: true, active: 'active', healthy: true, pid: 3 } });
|
||||
const binDir = join(f.dataRoot, 'opt', 'cliproxyapi', PIN.version);
|
||||
fs.mkdirSync(join(binDir, 'static'), { recursive: true });
|
||||
fs.writeFileSync(join(binDir, 'cli-proxy-api'), 'b'); fs.writeFileSync(join(binDir, 'static', 'management.html'), 'p');
|
||||
const files = initFiles(f.configDir, f.dataRoot);
|
||||
fs.mkdirSync(join(f.configDir, 'secrets'), { mode: 0o700 }); fs.writeFileSync(files.key, 'fixture', { mode: 0o600 });
|
||||
fs.mkdirSync(files.proxyDir, { mode: 0o700 });
|
||||
fs.writeFileSync(files.settings, JSON.stringify({ binary: join(binDir, 'cli-proxy-api'), port: 18432 }), { mode: 0o600 });
|
||||
let status = await f.admin.status();
|
||||
assert.deepEqual(status.next, ['accounts', 'ride-all']);
|
||||
assert.deepEqual(status.ride, [{ id: 'o', state: 'ready' }]);
|
||||
list = [{ id: 'o', fixture: true, cliproxy: false, changes: '', call: bus().call }];
|
||||
assert.deepEqual((await f.admin.status()).next, ['accounts', 'ride-all'], 'a fixture organization can still be moved');
|
||||
list = [{ id: 'o', fixture: false, cliproxy: true, changes: '', call: bus().call }];
|
||||
status = await f.admin.status();
|
||||
assert.deepEqual(status.next, ['accounts']);
|
||||
list = [{ id: 'o', fixture: false, cliproxy: false, changes: committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]), call: bus().call }];
|
||||
assert.deepEqual((await f.admin.status()).next, ['accounts'], 'a removed organization is not a reason to ride');
|
||||
f.state.healthy = false;
|
||||
list = [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: bus().call }];
|
||||
assert.deepEqual((await f.admin.status()).next, ['unit-restart'], 'never before the proxy answers');
|
||||
});
|
||||
|
||||
test('a fixture organization moves only when stopped, with a proxy, a riding bus and a move seam', async t => {
|
||||
const owner = { proxy: true, riding: true, models: [row()] };
|
||||
const moves = [];
|
||||
const move = async (id, models, principal) => { moves.push({ id, models, principal }); return { moved: true, model: models[0].key }; };
|
||||
let stoppedBus = bus({ down: true }), runningBus = bus();
|
||||
// Round 3 (P2c): stopped is the organization admin page's test, a bus status with no process id.
|
||||
const stopped = async () => ({ healthy: false, pid: null }), running = async () => ({ healthy: true, pid: 4242 });
|
||||
const riders = async () => [
|
||||
{ id: 'stand-in', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: stopped },
|
||||
{ id: 'live', fixture: true, cliproxy: false, changes: '', call: runningBus.call, status: running },
|
||||
{ id: 'busy', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: async () => ({ healthy: false, pid: 4343 }) },
|
||||
{ id: 'unproven', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call, status: async () => { throw busError('stale-host'); } },
|
||||
{ id: 'no-status', fixture: true, cliproxy: false, changes: '', call: stoppedBus.call },
|
||||
{ id: 'real', fixture: false, cliproxy: false, changes: '', call: stoppedBus.call, status: stopped },
|
||||
];
|
||||
let ownerNow = owner;
|
||||
const f = admin(t, { riders, ownerModels: async () => ownerNow, move });
|
||||
const principal = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' };
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'nope', principal }), { org: 'nope', moved: false, reason: 'unknown' });
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'real', principal }), { org: 'real', moved: false, reason: 'ready' });
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'live', principal }), { org: 'live', moved: false, reason: 'bus-running' });
|
||||
// A slow or busy bus that does not answer, or a status that cannot be read, is running.
|
||||
for (const org of ['busy', 'unproven']) assert.deepEqual(await f.admin.rideMove({ org, principal }), { org, moved: false, reason: 'bus-running' }, org);
|
||||
// settings-p3 R2: no status at all (the single-business Console) can never show the bus stopped, so
|
||||
// "stop its bus" would not help: moving is not available there, and whether it runs is unknown.
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'no-status', principal }), { org: 'no-status', moved: false, reason: 'not-available' });
|
||||
const listed = await f.admin.rideAll();
|
||||
assert.deepEqual(listed.fixtures, [{ id: 'stand-in', running: false }, { id: 'live', running: true }, { id: 'busy', running: true }, { id: 'unproven', running: true }, { id: 'no-status', running: null }]);
|
||||
// settings-p3 review P3-3: the status summary says so before any run, without asking any bus.
|
||||
assert.deepEqual((await f.admin.status()).ride.filter(r => r.state === 'fixture'), [{ id: 'stand-in', state: 'fixture' }, { id: 'live', state: 'fixture' }, { id: 'busy', state: 'fixture' }, { id: 'unproven', state: 'fixture' }, { id: 'no-status', state: 'fixture', running: null }]);
|
||||
ownerNow = { ...owner, proxy: false };
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'no-proxy' });
|
||||
ownerNow = { ...owner, riding: false };
|
||||
assert.deepEqual(await f.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'no-riding-bus' });
|
||||
assert.equal(moves.length, 0);
|
||||
ownerNow = owner;
|
||||
const done = await f.admin.rideMove({ org: 'stand-in', principal });
|
||||
assert.equal(done.moved, true); assert.equal(done.model, 'claude-claude-opus-5-5');
|
||||
assert.deepEqual(moves, [{ id: 'stand-in', models: [row()], principal }]);
|
||||
const last = receipts(f.dataRoot).at(-1);
|
||||
assert.deepEqual({ op: last.op, org: last.org, model: last.model }, { op: 'ride-move', org: 'stand-in', model: 'claude-claude-opus-5-5' });
|
||||
const none = admin(t, { riders, ownerModels: async () => owner, move: null });
|
||||
assert.deepEqual(await none.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'not-available' });
|
||||
const throws = admin(t, { riders, ownerModels: async () => owner, move: async () => { throw Object.assign(new Error('raw text'), { code: 'revision-conflict' }); } });
|
||||
assert.deepEqual(await throws.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'revision-conflict' });
|
||||
});
|
||||
|
||||
test('the fixture move rewrites the model provider, the model entry and every role that used it', async () => {
|
||||
const doc = await orgService.templateRender('alpha', { fixture: 'local' });
|
||||
Object.assign(doc.roles.assistant.vars, { 'fallback.harness': 'pi', 'fallback.model': 'fixture-deterministic', 'fallback.thinking': 'off' });
|
||||
doc.projects.work.agents = { helper: { definition: 'coder', vars: { harness: 'pi', model: 'fixture-deterministic', thinking: 'off' } } };
|
||||
assert.deepEqual(await orgService.validateOrg(doc), { ok: true, errors: [] });
|
||||
assert.equal(orgUsesFixture(doc), true);
|
||||
const { doc: next, model } = fixtureMove(doc, [glm, row()]);
|
||||
assert.equal(model.key, 'claude-claude-opus-5-5', 'the fixture assistant runs pi; of the models that serve pi, claude comes first');
|
||||
assert.equal(orgUsesFixture(next), false);
|
||||
assert.deepEqual(next.plugins['model-provider'], ['cliproxy']);
|
||||
assert.deepEqual(next.launch.models, { 'claude-claude-opus-5-5': { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' } });
|
||||
assert.equal(next.roles.assistant.vars.model, 'claude-claude-opus-5-5');
|
||||
assert.equal(next.roles.assistant.vars['fallback.model'], 'claude-claude-opus-5-5');
|
||||
assert.equal(next.roles.assistant.vars.harness, 'pi', 'the harness is left as it was');
|
||||
assert.equal(next.projects.work.agents.helper.vars.model, 'claude-claude-opus-5-5', 'a project\'s own agent moves too');
|
||||
assert.deepEqual(await orgService.validateOrg(next), { ok: true, errors: [] });
|
||||
const zai = fixtureMove(doc, [glm]);
|
||||
assert.equal(zai.model.key, 'zai-glm-5-3');
|
||||
assert.deepEqual(zai.doc.launch.models, { 'zai-glm-5-3': { provider: 'zai', model: 'glm-5.3', module: 'cliproxy', upstream: 'zai' } });
|
||||
assert.deepEqual(await orgService.validateOrg(zai.doc), { ok: true, errors: [] });
|
||||
assert.equal(doc.plugins['model-provider'][0], 'fixture', 'the input is not changed');
|
||||
assert.deepEqual(fixtureMove(doc, [row({ harnesses: ['claude-code'] })]), { reason: 'no-model' }, 'a model that cannot serve the harness is not used');
|
||||
assert.deepEqual(fixtureMove(doc, [row({ available: false, harnesses: ['pi'] })]), { reason: 'no-model' }, 'a model the catalogue does not offer is not used');
|
||||
});
|
||||
|
||||
test('the fixture move writes through the organization service as the owner, and only at the revision read', async () => {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'rd-svc-'));
|
||||
try {
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const ctx = { configDir, dataRoot, instance: 'test', principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } };
|
||||
await orgService.createOrg(ctx, 'alpha', await orgService.templateRender('alpha', { fixture: 'local' }));
|
||||
const stranger = { ...ctx, principal: { provider: 'sso', iss: 'https://idp.invalid', sub: 'someone' } };
|
||||
await assert.rejects(moveFixtureOrg({ service: orgService, ctx: stranger, id: 'alpha', models: [row()] }));
|
||||
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true, 'a stranger moved nothing');
|
||||
assert.deepEqual(await moveFixtureOrg({ service: orgService, ctx, id: 'alpha', models: [row({ harnesses: ['claude-code'] })] }), { moved: false, reason: 'no-model' });
|
||||
// A moved document the service does not accept is not written.
|
||||
const refusing = { ...orgService, validateOrg: async () => ({ ok: false, errors: [{ path: '$', message: 'no' }] }) };
|
||||
assert.deepEqual(await moveFixtureOrg({ service: refusing, ctx, id: 'alpha', models: [row()] }), { moved: false, reason: 'invalid' });
|
||||
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true, 'an invalid move wrote nothing');
|
||||
// A write between the read and the update loses: the service refuses the stale revision.
|
||||
const racing = { ...orgService, validateOrg: async d => { const now = await orgService.showOrg(ctx, 'alpha'); await orgService.updateOrg(ctx, 'alpha', now.doc, { ifRevision: now.revision }); return orgService.validateOrg(d); } };
|
||||
await assert.rejects(moveFixtureOrg({ service: racing, ctx, id: 'alpha', models: [row()] }), { code: 'revision-conflict' });
|
||||
assert.equal(orgUsesFixture((await orgService.showOrg(ctx, 'alpha')).doc), true);
|
||||
assert.deepEqual(await moveFixtureOrg({ service: orgService, ctx, id: 'alpha', models: [row()] }), { moved: true, model: 'claude-claude-opus-5-5' });
|
||||
const after = (await orgService.showOrg(ctx, 'alpha')).doc;
|
||||
assert.equal(orgUsesFixture(after), false);
|
||||
assert.deepEqual(after.plugins['model-provider'], ['cliproxy']);
|
||||
assert.equal(after.roles.assistant.vars.model, 'claude-claude-opus-5-5');
|
||||
assert.deepEqual(after.launch.models['claude-claude-opus-5-5'], { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' });
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('an organization is read from its file and change log; a missing log is empty and any other failure unreadable', () => {
|
||||
const enoent = () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); };
|
||||
const eacces = () => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); };
|
||||
const doc = providers => ({ plugins: { 'model-provider': providers } });
|
||||
assert.deepEqual(readRider({ id: 'a', read: () => doc(['cliproxy']), readLog: () => 'log', isFixture: () => false }), { id: 'a', fixture: false, cliproxy: true, changes: 'log' });
|
||||
assert.deepEqual(readRider({ id: 'b', read: () => doc(['fixture']), readLog: enoent, isFixture: () => true }), { id: 'b', fixture: true, cliproxy: false, changes: '' });
|
||||
assert.deepEqual(readRider({ id: 'c', read: () => ({}), readLog: eacces, isFixture: () => false }), { id: 'c', fixture: false, cliproxy: false, changes: null });
|
||||
const unread = readRider({ id: 'd', read: () => { throw new Error('bad json'); }, readLog: () => '', isFixture: () => true });
|
||||
assert.deepEqual(unread, { id: 'd', fixture: undefined, cliproxy: undefined, changes: '' });
|
||||
assert.equal(localRide(unread), 'unreadable');
|
||||
assert.equal(localRide(readRider({ id: 'c', read: () => ({}), readLog: eacces, isFixture: () => false })), 'unreadable');
|
||||
// The real fixture test decides the fixture field.
|
||||
assert.equal(readRider({ id: 'e', read: () => doc(['fixture']), readLog: () => '', isFixture: orgUsesFixture }).fixture, true);
|
||||
});
|
||||
|
||||
test('the owner models come only from riding buses that answer a ready catalogue, cliproxy rows once each', async () => {
|
||||
const asked = [];
|
||||
const rider = (id, cliproxy, answer) => ({ id, cliproxy, call: async verb => { asked.push([id, verb]); if (answer instanceof Error) throw answer; return answer; } });
|
||||
const ready = models => ({ catalogue: { status: 'ready', models } });
|
||||
assert.deepEqual(await ownerModelsFrom({ proxy: false, riders: [rider('a', true, ready([row()]))] }), { proxy: false, riding: false, models: [] });
|
||||
assert.deepEqual(asked, [], 'no proxy asks no bus');
|
||||
const fixtureRow = row({ key: 'fixture-deterministic', module: 'fixture' });
|
||||
const answer = await ownerModelsFrom({ proxy: true, riders: [
|
||||
rider('a', true, ready([row(), fixtureRow])), rider('b', true, ready([row({ label: 'later copy' }), glm])), rider('c', false, ready([row({ key: 'not-riding' })])),
|
||||
rider('d', true, { catalogue: { status: 'unavailable', models: [row({ key: 'fenced' })] } }), rider('e', true, busError('no-bus-host')),
|
||||
] });
|
||||
assert.deepEqual(answer, { proxy: true, riding: true, models: [row(), glm] });
|
||||
assert.deepEqual(asked.map(([id]) => id).sort(), ['a', 'b', 'd', 'e'], 'only organizations that list cliproxy are asked');
|
||||
assert.deepEqual(await ownerModelsFrom({ proxy: true, riders: [rider('d', true, { catalogue: { status: 'unavailable', models: [] } }), rider('e', true, busError('no-bus-host'))] }), { proxy: true, riding: false, models: [] });
|
||||
// A hung bus does not hold the others back: they are asked together.
|
||||
let release; const hung = { id: 'h', cliproxy: true, call: () => new Promise(r => { release = r; }) };
|
||||
const pending = ownerModelsFrom({ proxy: true, riders: [hung, rider('a', true, ready([row()]))] });
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.equal(asked.filter(([id]) => id === 'a').length, 2, 'the second bus was asked while the first hung');
|
||||
release(null); assert.deepEqual((await pending).models, [row()]);
|
||||
// Review round: a key one bus lists as unavailable and another as usable keeps the usable row.
|
||||
const stale = row({ available: false, reason: 'proxy-down', label: 'stale' });
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('s', true, ready([stale])), rider('a', true, ready([row()]))] })).models, [row()]);
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('a', true, ready([row()])), rider('s', true, ready([stale]))] })).models, [row()]);
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { join } from "node:path";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { checkDefinitions } from "./definitions.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { checkVars, mergeVars, REGISTRY } from "./vars.mjs";
|
||||
import { deepFreeze, isPlainObject, readJsonFile, rejectUnknownKeys, requireDistinctList, requireId, requireObject } from "./util.mjs";
|
||||
|
||||
@@ -27,6 +28,8 @@ export function rootAgentsPath(configDir) {
|
||||
function definitionOf(name, at, rolesDir, cache, definitions = {}) {
|
||||
if (typeof name === "string" && name.startsWith("org:") && Object.hasOwn(definitions,name)) return definitions[name];
|
||||
requireId(name, `${at}.definition`);
|
||||
// #1873 triage-fence: no root or project agent, and so no copy of one, names a system-only template.
|
||||
if (systemOnly(name)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.definition names ${name}, a template no organization may hold`);
|
||||
if (!cache.has(name)) {
|
||||
// A role refusal names host paths; this message travels to the Console, so it names none.
|
||||
try { cache.set(name, loadRole(rolesDir, name)); }
|
||||
|
||||
@@ -15,6 +15,7 @@ import { OrganizationError } from "./organization.mjs";
|
||||
import {
|
||||
diffDefinition, entryFromTemplate, instancesNaming, readTemplate, templateHashes, checkDefinitionName, ORG_PREFIX,
|
||||
} from "./definitions.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
// The verb names the policy table maps, following R1's hire.resolve.console.
|
||||
export const DEFINITION_VERBS = Object.freeze({
|
||||
@@ -64,6 +65,8 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
// Copies a template into definitions with from set to its name and current hash.
|
||||
function importTemplate(id, { revision, template, as = template }, caller) {
|
||||
authorize(caller, "import");
|
||||
// #1873 triage-fence: no organization imports a system-only template.
|
||||
if (systemOnly(template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
checkDefinitionName(as, "definition name");
|
||||
const source = readTemplate(rolesDir, template);
|
||||
const result = writer.setDefinition(id, as, (current) => {
|
||||
@@ -125,5 +128,5 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
return { organization: id, revision, ...diffDefinition(document, name, rolesDir) };
|
||||
}
|
||||
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir) };
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir).filter(({ template }) => !systemOnly(template)) };
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { createHash } from "node:crypto";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { buildRegistry, checkComposition } from "./composition.mjs";
|
||||
import { validateRoleDocument } from "./role.mjs";
|
||||
import { ID_PATTERN } from "./vocabulary.mjs";
|
||||
import { ID_PATTERN, SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { canonicalJson, deepFreeze } from "./util.mjs";
|
||||
|
||||
export const ORG_PREFIX = "org:";
|
||||
@@ -88,6 +88,8 @@ export function checkDefinition(name, entry, { assertClean = NO_STORE, where = "
|
||||
keysOnly(entry.from, FROM_KEYS, `${at}.from`);
|
||||
if (typeof entry.from.template !== "string" || !ID_PATTERN.test(entry.from.template)) refuse(`${at}.from.template must be a template name matching ${ID_PATTERN}`);
|
||||
if (typeof entry.from.sha256 !== "string" || !HEX64.test(entry.from.sha256)) refuse(`${at}.from.sha256 must be 64 lowercase hex characters`);
|
||||
// #1873 triage-fence: no organization definition copies a system-only template.
|
||||
if (systemOnly(entry.from.template)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.from.template names ${entry.from.template}, a template no organization may hold`);
|
||||
}
|
||||
if (!plain(entry.role)) refuse(`${at}.role must be a JSON object`);
|
||||
keysOnly(entry.role, ROLE_KEYS, `${at}.role`);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { compositionOf, entryFromTemplate, readTemplate, templateHashes } from '
|
||||
import { readRootAgentsFile, changeRootAgent } from './agent-levels-write.mjs';
|
||||
import { validateBusinessDocument } from './organization-config.mjs';
|
||||
import { canonicalJson, isPlainObject, readJsonFile } from './util.mjs';
|
||||
import { ID_PATTERN, NETWORKS } from './vocabulary.mjs';
|
||||
import { ID_PATTERN, NETWORKS, SYSTEM_ONLY_REFUSAL, systemOnly } from './vocabulary.mjs';
|
||||
import { OrganizationError } from './organization.mjs';
|
||||
import { resolveInstance } from './resolve.mjs';
|
||||
import { checkRoutes } from './launch-settings.mjs';
|
||||
@@ -204,6 +204,8 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in input.role) { id(input.role.template); if (!/^[a-f0-9]{64}$/.test(input.role.sha256??'') || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('definition' in input.role) { id(input.role.definition); if (!Number.isSafeInteger(input.role.rev) || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('inline' in input.role && Object.keys(input.role).length!==1) fail('invalid-request');
|
||||
// #1873 triage-fence: no hire or change at any level copies a system-only template.
|
||||
if (systemOnly(input.role.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
} else if (['role','route','credentials','personality'].some(k=>k in input)) fail('invalid-request');
|
||||
const {document:doc,revision} = writer.read(business);
|
||||
const loaded = validateBusinessDocument(doc,`${business}.json`,{rolesDir,dataRoot});
|
||||
@@ -226,6 +228,7 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in ref) { const template=readTemplate(rolesDir,ref.template); if(template.sha256!==ref.sha256) fail('decision-stale'); entry=entryFromTemplate(template); }
|
||||
else if ('definition' in ref) { entry=doc.definitions?.[ref.definition]; if(!entry || entry.rev!==ref.rev) fail('definition-rev-conflict'); entry=structuredClone(entry); }
|
||||
else entry={rev:1,role:{},instructions:''};
|
||||
if (systemOnly(entry.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
let c='inline' in ref ? structuredClone(ref.inline) : compositionOf(entry);
|
||||
if ('credentials' in input) c.credentials=structuredClone(input.credentials);
|
||||
if ('personality' in input) c.personality=structuredClone(input.personality);
|
||||
@@ -387,5 +390,5 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
const result=writer.reverseHireDecision(business,p,{...caller,beforeWrite:guard,beforePublish:publicationGuard});
|
||||
return {...result,...(r.op==='change' && stopped?.running?{relaunch:publicOf(p)}:{})};
|
||||
}
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).filter(({template})=>!systemOnly(template)).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { resolveInstance } from "./resolve.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { isPlainObject, canonicalJson } from "./util.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, checkGrantScope, grantScopeOf } from "./vocabulary.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, SYSTEM_ONLY_REFUSAL, checkGrantScope, grantScopeOf, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch", "tracker"];
|
||||
const VETO_KEYS = ["revision", "op", "name"];
|
||||
@@ -93,6 +93,8 @@ const sameCredentialServices = (before, after) => credentialServices(before).joi
|
||||
// Row 194 (brief item 7): the human's add passes credentials true and lifts it. The tester's add,
|
||||
// change and hire keep it.
|
||||
function definitionFor(rolesDir, name, { credentials = false } = {}) {
|
||||
// #1873 triage-fence: no add or change of definition gives an instance a system-only template.
|
||||
if (systemOnly(name)) throw new OrganizationError(SYSTEM_ONLY_REFUSAL);
|
||||
if (closed(name)) throw new OrganizationError("organization-definition-refused");
|
||||
const definition = loadRole(rolesDir, name);
|
||||
if (definition.roleVersion !== 2) throw new OrganizationError("invalid-request", `role definition ${name} is version 1`);
|
||||
@@ -153,6 +155,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
||||
const out = {};
|
||||
for (const file of readdirSync(rolesDir).filter(f => f.endsWith(".json")).sort()) {
|
||||
const name = file.slice(0, -5);
|
||||
// #1873 triage-fence: the add list never offers a system-only template.
|
||||
if (systemOnly(name)) continue;
|
||||
let definition;
|
||||
try {
|
||||
definition = loadRole(rolesDir, name);
|
||||
|
||||
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user