counterparts 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/docs/module-map.md +2 -0
- package/package.json +2 -1
- package/src/adapters/claude-code/CONTRACT.md +2 -1
- package/src/adapters/claude-code/NOTES.md +90 -2
- package/src/adapters/claude-code/bin/hook.ts +17 -2
- package/src/adapters/claude-code/bin/runner.ts +4 -1
- package/src/adapters/claude-code/config.ts +23 -0
- package/src/adapters/claude-code/doctor.ts +148 -26
- package/src/adapters/claude-code/hooks.ts +37 -12
- package/src/adapters/claude-code/index.ts +2 -0
- package/src/adapters/claude-code/standdown.ts +12 -1
- package/src/adapters/claude-code/transcript.ts +79 -6
- package/src/adapters/cli/INTERFACE-GAPS.md +4 -0
- package/src/adapters/cli/commands.ts +209 -61
- package/src/adapters/cli/export.ts +27 -3
- package/src/adapters/cli/help.ts +22 -8
- package/src/adapters/cli/install.ts +3 -5
- package/src/adapters/cli/mechanisms.ts +295 -0
- package/src/adapters/cli/repair-dates.ts +3 -1
- package/src/adapters/cli/snapshot.ts +4 -27
- package/src/adapters/dashboard/CONTRACT.md +13 -9
- package/src/adapters/dashboard/INTERFACE-GAPS.md +4 -0
- package/src/adapters/dashboard/NOTES.md +3 -2
- package/src/adapters/dashboard/activity.ts +2 -1
- package/src/adapters/dashboard/bin/dashboard.ts +18 -3
- package/src/adapters/dashboard/upgrade.ts +23 -0
- package/src/adapters/dashboard/web/README.md +153 -0
- package/src/adapters/dashboard/web/actions.ts +631 -0
- package/src/adapters/dashboard/web/app.html +40 -1703
- package/src/adapters/dashboard/web/app.js +55 -0
- package/src/adapters/dashboard/web/mechanisms/association/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/association/panel.js +17 -0
- package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +23 -0
- package/src/adapters/dashboard/web/mechanisms/decay/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/decay/panel.js +45 -0
- package/src/adapters/dashboard/web/mechanisms/emotional/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/episodic-semantic/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/index.js +60 -0
- package/src/adapters/dashboard/web/mechanisms/interference/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/picture.js +28 -0
- package/src/adapters/dashboard/web/mechanisms/prospective/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/reconsolidation/panel.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/regions.js +30 -0
- package/src/adapters/dashboard/web/mechanisms/retrieval/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/retrieval/panel.js +20 -0
- package/src/adapters/dashboard/web/mechanisms/salience/index.js +15 -0
- package/src/adapters/dashboard/web/mechanisms/salience/panel.js +14 -0
- package/src/adapters/dashboard/web/mechanisms/schema/index.js +15 -0
- package/src/adapters/dashboard/web/narrate.ts +10 -10
- package/src/adapters/dashboard/web/pages/flow/flow.css +38 -0
- package/src/adapters/dashboard/web/pages/flow/index.js +117 -0
- package/src/adapters/dashboard/web/pages/flow/sections/blind.js +12 -0
- package/src/adapters/dashboard/web/pages/flow/sections/detail.js +45 -0
- package/src/adapters/dashboard/web/pages/flow/sections/diagram.js +291 -0
- package/src/adapters/dashboard/web/pages/flow/sections/feed.js +11 -0
- package/src/adapters/dashboard/web/pages/flow/sections/fired.js +41 -0
- package/src/adapters/dashboard/web/pages/flow/sections/heatmap.js +25 -0
- package/src/adapters/dashboard/web/pages/flow/sections/records.js +24 -0
- package/src/adapters/dashboard/web/pages/flow/sections/symmetry.js +17 -0
- package/src/adapters/dashboard/web/pages/flow/state.js +3 -0
- package/src/adapters/dashboard/web/pages/health/health.css +93 -0
- package/src/adapters/dashboard/web/pages/health/index.js +41 -0
- package/src/adapters/dashboard/web/pages/health/sections/archive.js +84 -0
- package/src/adapters/dashboard/web/pages/health/sections/checks.js +172 -0
- package/src/adapters/dashboard/web/pages/health/sections/cycle.js +37 -0
- package/src/adapters/dashboard/web/pages/health/sections/verify.js +54 -0
- package/src/adapters/dashboard/web/pages/home/brain.js +375 -0
- package/src/adapters/dashboard/web/pages/home/home.css +134 -0
- package/src/adapters/dashboard/web/pages/home/index.js +84 -0
- package/src/adapters/dashboard/web/pages/home/sections/explorer.js +206 -0
- package/src/adapters/dashboard/web/pages/home/sections/hero.js +22 -0
- package/src/adapters/dashboard/web/pages/home/sections/live-activity.js +25 -0
- package/src/adapters/dashboard/web/pages/home/sections/recent-chapters.js +13 -0
- package/src/adapters/dashboard/web/pages/home/sections/tiles.js +52 -0
- package/src/adapters/dashboard/web/pages/memories/index.js +75 -0
- package/src/adapters/dashboard/web/pages/memories/memories.css +143 -0
- package/src/adapters/dashboard/web/pages/memories/sections/constellation.js +178 -0
- package/src/adapters/dashboard/web/pages/memories/sections/kinds.js +42 -0
- package/src/adapters/dashboard/web/pages/memories/sections/list.js +114 -0
- package/src/adapters/dashboard/web/pages/memories/sections/search.js +102 -0
- package/src/adapters/dashboard/web/pages/memories/sections/tools.js +155 -0
- package/src/adapters/dashboard/web/pages/memories/state.js +22 -0
- package/src/adapters/dashboard/web/pages/self/diff.js +79 -0
- package/src/adapters/dashboard/web/pages/self/index.js +43 -0
- package/src/adapters/dashboard/web/pages/self/markdown.js +61 -0
- package/src/adapters/dashboard/web/pages/self/sections/journal.js +32 -0
- package/src/adapters/dashboard/web/pages/self/sections/page.js +149 -0
- package/src/adapters/dashboard/web/pages/self/sections/settling.js +150 -0
- package/src/adapters/dashboard/web/pages/self/sections/stories.js +47 -0
- package/src/adapters/dashboard/web/pages/self/sections/wake.js +74 -0
- package/src/adapters/dashboard/web/pages/self/self.css +182 -0
- package/src/adapters/dashboard/web/server.ts +305 -28
- package/src/adapters/dashboard/web/shared/absence.js +14 -0
- package/src/adapters/dashboard/web/shared/actions.js +48 -0
- package/src/adapters/dashboard/web/shared/api.js +17 -0
- package/src/adapters/dashboard/web/shared/base.css +34 -0
- package/src/adapters/dashboard/web/shared/canvas.js +68 -0
- package/src/adapters/dashboard/web/shared/colors.js +6 -0
- package/src/adapters/dashboard/web/shared/dom.js +4 -0
- package/src/adapters/dashboard/web/shared/event-modal.js +25 -0
- package/src/adapters/dashboard/web/shared/fonts/OFL-courier-prime.txt +93 -0
- package/src/adapters/dashboard/web/shared/fonts/OFL-outfit.txt +93 -0
- package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-400.woff2 +0 -0
- package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-700.woff2 +0 -0
- package/src/adapters/dashboard/web/shared/fonts/outfit-latin-wght.woff2 +0 -0
- package/src/adapters/dashboard/web/shared/format.js +31 -0
- package/src/adapters/dashboard/web/shared/layout.css +32 -0
- package/src/adapters/dashboard/web/shared/memory-modal.js +124 -0
- package/src/adapters/dashboard/web/shared/modal.css +24 -0
- package/src/adapters/dashboard/web/shared/modal.js +22 -0
- package/src/adapters/dashboard/web/shared/state.js +12 -0
- package/src/adapters/dashboard/web/shared/tip.css +4 -0
- package/src/adapters/dashboard/web/shared/tip.js +12 -0
- package/src/adapters/dashboard/web/shared/tokens.css +50 -0
- package/src/adapters/dashboard/web/shared/type.css +52 -0
- package/src/adapters/dashboard/web/shared/utilities.css +5 -0
- package/src/adapters/dashboard/web/shared/vendor/MIT-three.txt +21 -0
- package/src/adapters/dashboard/web/shared/vendor/three.module.min.js +6 -0
- package/src/adapters/dashboard/web/shared/widgets/bar.css +9 -0
- package/src/adapters/dashboard/web/shared/widgets/card.css +6 -0
- package/src/adapters/dashboard/web/shared/widgets/chapters.js +15 -0
- package/src/adapters/dashboard/web/shared/widgets/chart.css +4 -0
- package/src/adapters/dashboard/web/shared/widgets/confirm.css +31 -0
- package/src/adapters/dashboard/web/shared/widgets/confirm.js +52 -0
- package/src/adapters/dashboard/web/shared/widgets/feed.css +13 -0
- package/src/adapters/dashboard/web/shared/widgets/feed.js +41 -0
- package/src/adapters/dashboard/web/shared/widgets/light.css +4 -0
- package/src/adapters/dashboard/web/shared/widgets/light.js +15 -0
- package/src/adapters/dashboard/web/shared/widgets/rows.css +7 -0
- package/src/adapters/dashboard/web/shared/widgets/table.css +17 -0
- package/src/adapters/dashboard/web/shared/widgets/tiles.css +14 -0
- package/src/adapters/dashboard/web/shell/pages.js +15 -0
- package/src/adapters/dashboard/web/shell/pulse.js +86 -0
- package/src/adapters/dashboard/web/shell/tabs.js +49 -0
- package/src/adapters/dashboard/web/static.ts +76 -0
- package/src/adapters/dashboard/web/views/activity.ts +80 -0
- package/src/adapters/dashboard/web/views/archive-words.ts +57 -0
- package/src/adapters/dashboard/web/views/flow-view.ts +217 -0
- package/src/adapters/dashboard/web/views/health.ts +328 -0
- package/src/adapters/dashboard/web/views/mechanism-panel.ts +370 -0
- package/src/adapters/dashboard/web/views/mechanisms.ts +302 -0
- package/src/adapters/dashboard/web/views/memories.ts +342 -0
- package/src/adapters/dashboard/web/views/memory.ts +210 -0
- package/src/adapters/dashboard/web/views/meta.ts +64 -0
- package/src/adapters/dashboard/web/views/mind.ts +729 -0
- package/src/adapters/dashboard/web/views/overview.ts +282 -0
- package/src/adapters/dashboard/web/views/pulse.ts +19 -0
- package/src/adapters/dashboard/web/views/rows.ts +207 -0
- package/src/adapters/dashboard/web/views/search.ts +62 -0
- package/src/adapters/dashboard/web/views/shared.ts +161 -0
- package/src/adapters/dashboard/web/views.ts +34 -1724
- package/src/adapters/fired.ts +138 -31
- package/src/adapters/mcp/INTERFACE-GAPS.md +4 -1
- package/src/adapters/mcp/NOTES.md +43 -0
- package/src/adapters/mcp/bin/serve.ts +9 -1
- package/src/adapters/mcp/index.ts +7 -0
- package/src/adapters/mcp/server.ts +167 -6
- package/src/adapters/mcp/tools.ts +42 -0
- package/src/adapters/mcp/write-up.ts +1 -1
- package/src/adapters/sessions.ts +18 -1
- package/src/adapters/snapshots.ts +71 -39
- package/src/core/associate/INTERFACE-GAPS.md +8 -0
- package/src/core/counterpart.ts +86 -7
- package/src/core/encode/INTERFACE-GAPS.md +12 -0
- package/src/core/feelings-wheel.ts +218 -0
- package/src/core/handoff/INTERFACE-GAPS.md +2 -0
- package/src/core/mint.ts +14 -2
- package/src/core/prospective/INTERFACE-GAPS.md +14 -0
- package/src/core/prospective/windows.ts +10 -48
- package/src/core/recall/INTERFACE-GAPS.md +6 -0
- package/src/core/remember/INTERFACE-GAPS.md +10 -0
- package/src/core/schemas/INTERFACE-GAPS.md +8 -0
- package/src/core/schemas/NOTES.md +118 -1
- package/src/core/schemas/index.ts +330 -40
- package/src/core/schemas/tunables.ts +23 -0
- package/src/core/schemas/types.ts +64 -1
- package/src/core/self/CONTRACT.md +3 -0
- package/src/core/self/INTERFACE-GAPS.md +10 -0
- package/src/core/self/NOTES.md +33 -2
- package/src/core/self/calendar.ts +7 -78
- package/src/core/self/episodes.ts +52 -12
- package/src/core/self/index.ts +40 -12
- package/src/core/self/writer.ts +22 -22
- package/src/core/sleep/NOTES.md +36 -0
- package/src/core/sleep/cycle.ts +38 -3
- package/src/core/sleep/fade.ts +76 -0
- package/src/core/sleep/index.ts +4 -1
- package/src/core/sleep/prune.ts +8 -1
- package/src/core/sleep/tunables.ts +5 -0
- package/src/core/sleep/types.ts +24 -0
- package/src/core/store/CONTRACT.md +36 -7
- package/src/core/store/NOTES.md +197 -0
- package/src/core/store/errors.ts +22 -0
- package/src/core/store/feelings.ts +182 -0
- package/src/core/store/index.ts +339 -45
- package/src/core/store/operational.ts +240 -22
- package/src/core/store/owner-op-seam.ts +13 -3
- package/src/core/store/paths.ts +15 -1
- package/src/core/store/pre-migration.ts +258 -0
- package/src/core/store/prose.ts +8 -1
- package/src/core/store/render.ts +3 -0
- package/src/core/time.ts +374 -0
- package/src/core/types.ts +13 -0
- package/src/adapters/dashboard/web/brain.html +0 -463
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE MANAGEMENT SEAM — what the owner does on purpose from the dashboard
|
|
3
|
+
* (owner, 2026-09-25; CONTRACT §5, `docs/observer-mode.md` §1).
|
|
4
|
+
*
|
|
5
|
+
* Looking and managing are kept apart by WHICH DOOR a request goes through, not
|
|
6
|
+
* by a mode:
|
|
7
|
+
*
|
|
8
|
+
* - **Looking** is `server.ts#router` over the observer source, and nothing
|
|
9
|
+
* in this file can reach that source: no function here takes a
|
|
10
|
+
* `DashboardSource`, a `Dashboard` or a `Store`. It is handed the store's
|
|
11
|
+
* DIRECTORY and the configuration's PATH — two strings, exactly what a
|
|
12
|
+
* person types after `--dir` and `--config`.
|
|
13
|
+
* - **Managing** is the console's own `run()` — the function
|
|
14
|
+
* `bin/counterparts.ts` calls — with an argv array built here from
|
|
15
|
+
* validated fields. Every check, refusal and sentence is the CLI's; this
|
|
16
|
+
* file adds guards in front of it and never a way around one.
|
|
17
|
+
*
|
|
18
|
+
* ## Why in-process, and not a child process
|
|
19
|
+
*
|
|
20
|
+
* A child process running `bin/counterparts.ts` would be the most literal
|
|
21
|
+
* reading of "the CLI's own door", and it CANNOT REMOVE: `remove --confirm`
|
|
22
|
+
* asks the person to type the id back through `io.prompt`, the bin binds a
|
|
23
|
+
* prompt only when stdin is a terminal, and a pipe gets "refused: removal
|
|
24
|
+
* requires an interactive confirmation" — deliberately, with no `--yes`.
|
|
25
|
+
* In-process, the prompt is a seam `run()` already has (`Io.prompt`): the
|
|
26
|
+
* browser asks the owner to type the id, and the string they typed is what the
|
|
27
|
+
* CLI's own prompt receives, so the CLI's own comparison is what refuses a
|
|
28
|
+
* mismatch. `io.tty` is left absent, so `isInteractive` is false and removal
|
|
29
|
+
* takes the scripted door (`--confirm`) exactly as a script would.
|
|
30
|
+
*
|
|
31
|
+
* What that costs, said plainly: a command running in this process cannot be
|
|
32
|
+
* killed. The timeout below stops WAITING and says so; the command finishes in
|
|
33
|
+
* the background, and the queue holds every other action until it has.
|
|
34
|
+
*
|
|
35
|
+
* The CLI module is imported LAZILY, on the first action, so a dashboard that
|
|
36
|
+
* is only looked at never loads a line of code that can write.
|
|
37
|
+
*
|
|
38
|
+
* ## Which commands
|
|
39
|
+
*
|
|
40
|
+
* `note`, `remove`, `backup`, `export`, `scope`, `rebrief`, `verify`, and the
|
|
41
|
+
* read-only `ask` and `doctor` (the health tab's checklist: `doctor --json`,
|
|
42
|
+
* the console's own reading, so the page and the terminal cannot disagree
|
|
43
|
+
* about what "healthy" means). `install`, `uninstall` and `start-fresh` stay terminal-only
|
|
44
|
+
* (owner, 2026-09-25) — they are not in `ACTIONS`, so no argv for them can be
|
|
45
|
+
* built here.
|
|
46
|
+
*/
|
|
47
|
+
import { isAbsolute } from "node:path";
|
|
48
|
+
|
|
49
|
+
import { REQUIRE_EXPLICIT_DIR_ENV } from "../../../core/store/paths.js";
|
|
50
|
+
import { CONFIG_ENV } from "../../config-path.js";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* THE HOME A BARE-STORE ACTION RESOLVES CONFIGURATIONS UNDER: a path that does
|
|
54
|
+
* not exist, so the console's default configuration (`<home>/.counterparts/
|
|
55
|
+
* claude-code.json`) is simply absent and every knob takes its default. See
|
|
56
|
+
* `bareStore` below.
|
|
57
|
+
*/
|
|
58
|
+
export const NO_CONFIG_HOME = "/nonexistent/counterparts-dashboard-bare-store";
|
|
59
|
+
|
|
60
|
+
/** The actions, in the order a reader meets them. */
|
|
61
|
+
export const ACTIONS = ["ask", "note", "remove", "backup", "export", "scope", "rebrief", "verify", "doctor"] as const;
|
|
62
|
+
export type ActionName = (typeof ACTIONS)[number];
|
|
63
|
+
|
|
64
|
+
export function isActionName(name: string): name is ActionName {
|
|
65
|
+
return (ACTIONS as readonly string[]).includes(name);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The header every action must echo the page's token in. */
|
|
69
|
+
export const TOKEN_HEADER = "x-counterparts-token";
|
|
70
|
+
/** The `<meta name>` the served page carries the token in. */
|
|
71
|
+
export const TOKEN_META = "counterparts-action-token";
|
|
72
|
+
|
|
73
|
+
/** A request body larger than this is refused before it is parsed. */
|
|
74
|
+
export const MAX_BODY_BYTES = 64 * 1024;
|
|
75
|
+
/** How much console output one action may return (both streams together). */
|
|
76
|
+
export const MAX_OUTPUT_BYTES = 256 * 1024;
|
|
77
|
+
|
|
78
|
+
/** How long the page waits for an action before it says it stopped waiting. */
|
|
79
|
+
export const TIMEOUT_MS: Record<ActionName, number> = {
|
|
80
|
+
ask: 120_000,
|
|
81
|
+
note: 120_000,
|
|
82
|
+
remove: 120_000,
|
|
83
|
+
scope: 30_000,
|
|
84
|
+
rebrief: 120_000,
|
|
85
|
+
// The three that walk the whole store: a backup and an export copy it, and
|
|
86
|
+
// `verify --rebuild` re-embeds it.
|
|
87
|
+
backup: 30 * 60_000,
|
|
88
|
+
export: 30 * 60_000,
|
|
89
|
+
verify: 30 * 60_000,
|
|
90
|
+
// A read, but a wide one: the whole event log, every scope's captured words,
|
|
91
|
+
// and a few bounded `git` calls.
|
|
92
|
+
doctor: 60_000,
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A fresh token for one launch of the dashboard. `crypto.getRandomValues` is
|
|
97
|
+
* the platform's CSPRNG (bun and Node both), reached without importing a
|
|
98
|
+
* module the adapter's import scan would have to learn about.
|
|
99
|
+
*/
|
|
100
|
+
export function newActionToken(): string {
|
|
101
|
+
const bytes = new Uint8Array(32);
|
|
102
|
+
crypto.getRandomValues(bytes);
|
|
103
|
+
return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Equal strings, compared in time that does not depend on where they differ. */
|
|
107
|
+
export function tokensMatch(given: string, expected: string): boolean {
|
|
108
|
+
if (given.length !== expected.length || expected.length === 0) return false;
|
|
109
|
+
let diff = 0;
|
|
110
|
+
for (let i = 0; i < expected.length; i++) diff |= given.charCodeAt(i) ^ expected.charCodeAt(i);
|
|
111
|
+
return diff === 0;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── the request guard ───────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
export interface ActionRequest {
|
|
117
|
+
readonly method: string;
|
|
118
|
+
readonly host: string | null;
|
|
119
|
+
readonly origin: string | null;
|
|
120
|
+
readonly contentType: string | null;
|
|
121
|
+
readonly token: string | null;
|
|
122
|
+
/** `Sec-Fetch-Site`, when the browser sends one. */
|
|
123
|
+
readonly fetchSite: string | null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface Refusal {
|
|
127
|
+
readonly status: number;
|
|
128
|
+
readonly error: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* EVERY ACTION PASSES THIS FIRST, before its body is read. It is what stands
|
|
135
|
+
* between a page on some other website and the owner's memory: loopback alone
|
|
136
|
+
* stops remote machines, not the owner's own browser being told to POST to
|
|
137
|
+
* 127.0.0.1 (CSRF), nor a hostile name rebound to 127.0.0.1 (DNS rebinding —
|
|
138
|
+
* the Host allowlist, v1 audit #30).
|
|
139
|
+
*
|
|
140
|
+
* - POST only. A GET never acts, so a link, an <img>, a prefetch cannot.
|
|
141
|
+
* - Host is loopback, on the port this server is bound to.
|
|
142
|
+
* - Origin is REQUIRED and must be this same origin. A browser sends it on
|
|
143
|
+
* every POST; a request without one is not from this page.
|
|
144
|
+
* - `Sec-Fetch-Site`, when present, must say same-origin.
|
|
145
|
+
* - `Content-Type: application/json`, which a cross-site form cannot send
|
|
146
|
+
* and a cross-site fetch cannot send without a preflight this server never
|
|
147
|
+
* answers.
|
|
148
|
+
* - The per-launch token, which only a page served by THIS process holds:
|
|
149
|
+
* another origin cannot read the page it is embedded in.
|
|
150
|
+
*/
|
|
151
|
+
export function checkActionRequest(
|
|
152
|
+
req: ActionRequest,
|
|
153
|
+
expectedToken: string,
|
|
154
|
+
boundPort: number,
|
|
155
|
+
): Refusal | null {
|
|
156
|
+
if (req.method !== "POST") {
|
|
157
|
+
return { status: 405, error: "an action is a POST; nothing was done" };
|
|
158
|
+
}
|
|
159
|
+
const host = hostPort(req.host);
|
|
160
|
+
if (host === null || !LOOPBACK.has(host.name) || host.port !== boundPort) {
|
|
161
|
+
return { status: 403, error: "forbidden: an action must be addressed to this dashboard on 127.0.0.1" };
|
|
162
|
+
}
|
|
163
|
+
if (req.origin === null || req.origin.length === 0) {
|
|
164
|
+
return { status: 403, error: "forbidden: an action must come from the dashboard's own page (no Origin)" };
|
|
165
|
+
}
|
|
166
|
+
let origin: URL;
|
|
167
|
+
try {
|
|
168
|
+
origin = new URL(req.origin);
|
|
169
|
+
} catch {
|
|
170
|
+
return { status: 403, error: "forbidden: an unreadable Origin" };
|
|
171
|
+
}
|
|
172
|
+
const originHost = hostPort(origin.host);
|
|
173
|
+
if (
|
|
174
|
+
origin.protocol !== "http:" ||
|
|
175
|
+
originHost === null ||
|
|
176
|
+
originHost.name !== host.name ||
|
|
177
|
+
originHost.port !== host.port
|
|
178
|
+
) {
|
|
179
|
+
return { status: 403, error: "forbidden: an action must come from the dashboard's own page (cross-origin)" };
|
|
180
|
+
}
|
|
181
|
+
if (req.fetchSite !== null && req.fetchSite !== "same-origin") {
|
|
182
|
+
return { status: 403, error: "forbidden: the browser says this request is not same-origin" };
|
|
183
|
+
}
|
|
184
|
+
if (req.contentType === null || !/^application\/json\s*(;|$)/i.test(req.contentType)) {
|
|
185
|
+
return { status: 415, error: "an action's body is JSON (content-type: application/json)" };
|
|
186
|
+
}
|
|
187
|
+
if (req.token === null || !tokensMatch(req.token, expectedToken)) {
|
|
188
|
+
return { status: 403, error: "forbidden: this request does not carry the page's token. Reload the dashboard." };
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function hostPort(raw: string | null): { name: string; port: number } | null {
|
|
194
|
+
if (raw === null) return null;
|
|
195
|
+
const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(raw.trim());
|
|
196
|
+
if (m === null) return null;
|
|
197
|
+
const port = m[2] === undefined ? 80 : Number(m[2]);
|
|
198
|
+
return { name: (m[1] ?? "").toLowerCase(), port };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ── validation and argv ─────────────────────────────────────────────────────
|
|
202
|
+
|
|
203
|
+
/** Where the command runs: the store and configuration the dashboard was opened on. */
|
|
204
|
+
export interface ActionContext {
|
|
205
|
+
/** The store's directory — what the dashboard's own `--dir` resolved to. */
|
|
206
|
+
readonly dir: string;
|
|
207
|
+
/** The host configuration, when the dashboard was opened through one. */
|
|
208
|
+
readonly config?: string;
|
|
209
|
+
/** The console's environment. Real runs pass nothing and get `process.env`. */
|
|
210
|
+
readonly env?: Record<string, string | undefined>;
|
|
211
|
+
/** The home the console resolves configurations under (tests only). */
|
|
212
|
+
readonly home?: string;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface Built {
|
|
216
|
+
readonly argv: string[];
|
|
217
|
+
/** What the CLI's confirmation prompt receives — the owner's own typing. */
|
|
218
|
+
readonly answer?: string;
|
|
219
|
+
/** Variables laid over the console's environment for this one run
|
|
220
|
+
* (`undefined` removes one). */
|
|
221
|
+
readonly env?: Record<string, string | undefined>;
|
|
222
|
+
/** The home the console resolves configurations under, for this one run. */
|
|
223
|
+
readonly home?: string;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A memory id as the store accepts one: its family prefix, no whitespace, no slash. */
|
|
227
|
+
const ID = /^(mem|epi|sch)_[A-Za-z0-9_-]{1,64}$/;
|
|
228
|
+
const MAX_TEXT = 20_000;
|
|
229
|
+
const MAX_LINE = 2_000;
|
|
230
|
+
|
|
231
|
+
type Body = Record<string, unknown>;
|
|
232
|
+
|
|
233
|
+
class Invalid extends Error {}
|
|
234
|
+
|
|
235
|
+
function text(body: Body, key: string, max: number, required: boolean): string | undefined {
|
|
236
|
+
const v = body[key];
|
|
237
|
+
if (v === undefined || v === null || v === "") {
|
|
238
|
+
if (required) throw new Invalid(`${key} is required`);
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
if (typeof v !== "string") throw new Invalid(`${key} must be text`);
|
|
242
|
+
if (v.includes("\0")) throw new Invalid(`${key} may not contain a NUL`);
|
|
243
|
+
if (v.length > max) throw new Invalid(`${key} is longer than ${String(max)} characters`);
|
|
244
|
+
if (v.trim().length === 0) {
|
|
245
|
+
if (required) throw new Invalid(`${key} is required`);
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
return v;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function flag(body: Body, key: string): boolean {
|
|
252
|
+
const v = body[key];
|
|
253
|
+
if (v === undefined || v === null || v === false) return false;
|
|
254
|
+
if (v === true) return true;
|
|
255
|
+
throw new Invalid(`${key} is true or false`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function memoryId(body: Body, key: string, required: boolean): string | undefined {
|
|
259
|
+
const v = text(body, key, 80, required);
|
|
260
|
+
if (v === undefined) return undefined;
|
|
261
|
+
const id = v.trim();
|
|
262
|
+
if (!ID.test(id)) throw new Invalid(`${key} is not a memory id (mem_…)`);
|
|
263
|
+
return id;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** An absolute path, no NUL, no control characters. Where it may go is the CLI's call. */
|
|
267
|
+
function absPath(body: Body, key: string): string {
|
|
268
|
+
const v = text(body, key, 4096, true) as string;
|
|
269
|
+
// eslint-disable-next-line no-control-regex
|
|
270
|
+
if (/[\x00-\x1f\x7f]/.test(v)) throw new Invalid(`${key} may not contain control characters`);
|
|
271
|
+
if (!isAbsolute(v)) throw new Invalid(`${key} must be an absolute path`);
|
|
272
|
+
return v;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** A positional the console must read as words, never as a flag. */
|
|
276
|
+
function words(value: string, key: string): string {
|
|
277
|
+
if (value.trimStart().startsWith("--")) {
|
|
278
|
+
throw new Invalid(`${key} may not begin with "--" (the console would read it as a flag)`);
|
|
279
|
+
}
|
|
280
|
+
return value;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function withConfig(ctx: ActionContext): string[] {
|
|
284
|
+
return ctx.config === undefined ? [] : ["--config", ctx.config];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* THE ARGV, from validated fields only. `--dir` is always the dashboard's own
|
|
289
|
+
* store (never a field of the request), and every positional comes after `--`,
|
|
290
|
+
* so no text the owner typed can be read as a flag.
|
|
291
|
+
*/
|
|
292
|
+
export function buildArgv(name: ActionName, body: Body, ctx: ActionContext): Built {
|
|
293
|
+
const built = argvFor(name, body, ctx);
|
|
294
|
+
return ctx.config === undefined ? { ...built, ...bareStore(name) } : built;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* A DASHBOARD OPENED ON A BARE STORE NEVER REACHES A DEFAULT CONFIGURATION.
|
|
299
|
+
*
|
|
300
|
+
* With no `--config` to pass, the console would resolve one on its own —
|
|
301
|
+
* `COUNTERPARTS_CONFIG`, else `~/.counterparts/claude-code.json` — and on this
|
|
302
|
+
* machine that is possibly the owner's live install: `rebrief` took its budget
|
|
303
|
+
* from it, `ask` its recall-by-meaning setting. That is not the store this page
|
|
304
|
+
* is looking at. So every action from a bare-store dashboard runs with:
|
|
305
|
+
*
|
|
306
|
+
* - the explicit-dir guard armed, so any door that checks it refuses rather
|
|
307
|
+
* than falls back;
|
|
308
|
+
* - `COUNTERPARTS_CONFIG` removed, so a stale one in the server's shell names
|
|
309
|
+
* nothing;
|
|
310
|
+
* - a home that does not exist, so the default configuration is ABSENT and
|
|
311
|
+
* every knob takes its default — except `doctor`, whose host reading needs
|
|
312
|
+
* the real home (`~/.claude`, not ours) and which, under the guard with a
|
|
313
|
+
* `--dir`, declines to read the configuration at all and says so in its
|
|
314
|
+
* `config` line (doctor.ts, "not-read").
|
|
315
|
+
*
|
|
316
|
+
* An action that genuinely needs a configuration (`scope`) refuses in
|
|
317
|
+
* `argvFor` before any of this.
|
|
318
|
+
*/
|
|
319
|
+
function bareStore(name: ActionName): Pick<Built, "env" | "home"> {
|
|
320
|
+
const env = { [REQUIRE_EXPLICIT_DIR_ENV]: "1", [CONFIG_ENV]: undefined };
|
|
321
|
+
return name === "doctor" ? { env } : { env, home: NO_CONFIG_HOME };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function argvFor(name: ActionName, body: Body, ctx: ActionContext): Built {
|
|
325
|
+
const dir = ["--dir", ctx.dir];
|
|
326
|
+
switch (name) {
|
|
327
|
+
case "ask": {
|
|
328
|
+
const question = text(body, "question", MAX_LINE, false);
|
|
329
|
+
const id = memoryId(body, "id", false);
|
|
330
|
+
if ((question === undefined) === (id === undefined)) {
|
|
331
|
+
throw new Invalid("ask takes a question or an id — one of them");
|
|
332
|
+
}
|
|
333
|
+
const argv = ["ask", ...dir, ...withConfig(ctx)];
|
|
334
|
+
if (flag(body, "full")) argv.push("--full");
|
|
335
|
+
// The answers as data, so the page can list them and open each one.
|
|
336
|
+
if (flag(body, "json")) argv.push("--json");
|
|
337
|
+
if (id !== undefined) return { argv: [...argv, "--id", id] };
|
|
338
|
+
return { argv: [...argv, "--", words(question as string, "question")] };
|
|
339
|
+
}
|
|
340
|
+
case "note": {
|
|
341
|
+
const content = text(body, "text", MAX_TEXT, true) as string;
|
|
342
|
+
const argv = ["note", ...dir, ...withConfig(ctx)];
|
|
343
|
+
const kind = text(body, "kind", 40, false);
|
|
344
|
+
if (kind !== undefined) {
|
|
345
|
+
if (!/^[a-z][a-z_-]*$/.test(kind)) throw new Invalid("kind is one word");
|
|
346
|
+
argv.push("--kind", kind);
|
|
347
|
+
}
|
|
348
|
+
const title = text(body, "title", 200, false);
|
|
349
|
+
if (title !== undefined) argv.push(`--title=${title}`);
|
|
350
|
+
const salience = body["salience"];
|
|
351
|
+
if (salience !== undefined && salience !== null && salience !== "") {
|
|
352
|
+
if (typeof salience !== "number" || !Number.isFinite(salience) || salience < 0 || salience > 1) {
|
|
353
|
+
throw new Invalid("salience is a number from 0 to 1");
|
|
354
|
+
}
|
|
355
|
+
argv.push("--salience", String(salience));
|
|
356
|
+
}
|
|
357
|
+
return { argv: [...argv, "--", words(content, "text")] };
|
|
358
|
+
}
|
|
359
|
+
case "remove": {
|
|
360
|
+
const id = memoryId(body, "id", true) as string;
|
|
361
|
+
const argv = ["remove", ...dir];
|
|
362
|
+
const reason = text(body, "reason", 500, false);
|
|
363
|
+
if (reason !== undefined) argv.push(`--reason=${reason}`);
|
|
364
|
+
// WITHOUT a typed confirmation this is the CLI's dry run: the plan, and
|
|
365
|
+
// "Nothing has changed". WITH one it is `--confirm`, and what the owner
|
|
366
|
+
// typed is handed to the CLI's own prompt — the CLI compares it.
|
|
367
|
+
const typed = body["confirm"];
|
|
368
|
+
if (typed === undefined || typed === null) return { argv: [...argv, "--", id] };
|
|
369
|
+
if (typeof typed !== "string" || typed.length > 80 || typed.includes("\0")) {
|
|
370
|
+
throw new Invalid("confirm is the id, typed back");
|
|
371
|
+
}
|
|
372
|
+
return { argv: [...argv, "--confirm", "--", id], answer: typed };
|
|
373
|
+
}
|
|
374
|
+
case "backup":
|
|
375
|
+
return { argv: ["backup", ...dir, "--out", absPath(body, "out")] };
|
|
376
|
+
case "export": {
|
|
377
|
+
const argv = ["export", ...dir, "--out", absPath(body, "out")];
|
|
378
|
+
const passphrase = text(body, "passphrase", 1024, false);
|
|
379
|
+
if (passphrase !== undefined) argv.push(`--passphrase=${passphrase}`);
|
|
380
|
+
const booleans: [string, string][] = [
|
|
381
|
+
["plaintext", "--plaintext"],
|
|
382
|
+
["markdown", "--markdown"],
|
|
383
|
+
["includeConfidential", "--include-confidential"],
|
|
384
|
+
["withVersions", "--with-versions"],
|
|
385
|
+
["intoNonEmpty", "--into-non-empty"],
|
|
386
|
+
["overwrite", "--overwrite"],
|
|
387
|
+
];
|
|
388
|
+
for (const [key, f] of booleans) if (flag(body, key)) argv.push(f);
|
|
389
|
+
return { argv };
|
|
390
|
+
}
|
|
391
|
+
case "scope": {
|
|
392
|
+
// The registry sits beside a CONFIGURATION, and a dashboard opened on a
|
|
393
|
+
// bare `--dir` has none to name. The console would fall back to the
|
|
394
|
+
// default one — on this machine, possibly the owner's live install — so
|
|
395
|
+
// this door asks for the configuration to be named instead of guessing.
|
|
396
|
+
if (ctx.config === undefined) {
|
|
397
|
+
throw new Invalid(
|
|
398
|
+
"scope writes the registry beside a configuration, and this dashboard was opened on a store " +
|
|
399
|
+
"without one. Open it with `counterparts dashboard` (or serve --config <path>).",
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
const argv = ["scope", ...withConfig(ctx)];
|
|
403
|
+
if (flag(body, "list")) return { argv: [...argv, "--list"] };
|
|
404
|
+
const path = absPath(body, "path");
|
|
405
|
+
const mode = body["mode"];
|
|
406
|
+
const MODES: Record<string, string> = {
|
|
407
|
+
on: "--on",
|
|
408
|
+
observer: "--observer",
|
|
409
|
+
off: "--off",
|
|
410
|
+
pause: "--pause",
|
|
411
|
+
resume: "--resume",
|
|
412
|
+
};
|
|
413
|
+
if (mode !== undefined && mode !== null && mode !== "") {
|
|
414
|
+
if (typeof mode !== "string" || !(mode in MODES)) {
|
|
415
|
+
throw new Invalid("mode is one of on, observer, off, pause, resume");
|
|
416
|
+
}
|
|
417
|
+
argv.push(MODES[mode] as string);
|
|
418
|
+
const note = text(body, "note", 500, false);
|
|
419
|
+
if (note !== undefined) argv.push(`--note=${note}`);
|
|
420
|
+
}
|
|
421
|
+
return { argv: [...argv, "--", path] };
|
|
422
|
+
}
|
|
423
|
+
case "rebrief": {
|
|
424
|
+
const argv = ["rebrief", ...dir, ...withConfig(ctx)];
|
|
425
|
+
const budget = body["budget"];
|
|
426
|
+
if (budget !== undefined && budget !== null && budget !== "") {
|
|
427
|
+
if (typeof budget !== "number" || !Number.isInteger(budget) || budget <= 0) {
|
|
428
|
+
throw new Invalid("budget is a whole number of bytes");
|
|
429
|
+
}
|
|
430
|
+
argv.push("--budget", String(budget));
|
|
431
|
+
}
|
|
432
|
+
return { argv };
|
|
433
|
+
}
|
|
434
|
+
case "verify": {
|
|
435
|
+
const argv = ["verify", ...dir];
|
|
436
|
+
const booleans: [string, string][] = [
|
|
437
|
+
["rebuild", "--rebuild"],
|
|
438
|
+
["dropVectors", "--drop-vectors"],
|
|
439
|
+
["keepVectors", "--keep-vectors"],
|
|
440
|
+
["pruneIndex", "--prune-index"],
|
|
441
|
+
["retrySkipped", "--retry-skipped"],
|
|
442
|
+
];
|
|
443
|
+
for (const [key, f] of booleans) if (flag(body, key)) argv.push(f);
|
|
444
|
+
return { argv };
|
|
445
|
+
}
|
|
446
|
+
case "doctor":
|
|
447
|
+
// No fields: the reading is the dashboard's own store, and its own
|
|
448
|
+
// configuration when it was opened through one.
|
|
449
|
+
return { argv: ["doctor", ...dir, ...withConfig(ctx), "--json"] };
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** The command line, as a person would read it — the passphrase withheld. */
|
|
454
|
+
export function displayCommand(argv: readonly string[]): string {
|
|
455
|
+
const shown = argv.map((a) => (a.startsWith("--passphrase=") ? "--passphrase=…" : a));
|
|
456
|
+
return ["counterparts", ...shown.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : JSON.stringify(a)))].join(" ");
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ── running ─────────────────────────────────────────────────────────────────
|
|
460
|
+
|
|
461
|
+
export interface ActionResult {
|
|
462
|
+
readonly status: number;
|
|
463
|
+
readonly body: {
|
|
464
|
+
readonly action?: string;
|
|
465
|
+
readonly command?: string;
|
|
466
|
+
readonly exit?: number;
|
|
467
|
+
readonly ok?: boolean;
|
|
468
|
+
readonly out?: string[];
|
|
469
|
+
readonly err?: string[];
|
|
470
|
+
readonly truncated?: boolean;
|
|
471
|
+
readonly error?: string;
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** The console's `run`, as this file needs to see it. */
|
|
476
|
+
export type Run = (
|
|
477
|
+
argv: readonly string[],
|
|
478
|
+
opts: {
|
|
479
|
+
io: { out(line: string): void; err(line: string): void; prompt?: (q: string) => Promise<string> };
|
|
480
|
+
env?: Record<string, string | undefined>;
|
|
481
|
+
home?: string;
|
|
482
|
+
scope?: string;
|
|
483
|
+
},
|
|
484
|
+
) => Promise<number>;
|
|
485
|
+
|
|
486
|
+
let runner: Run | null = null;
|
|
487
|
+
async function cliRun(): Promise<Run> {
|
|
488
|
+
if (runner === null) {
|
|
489
|
+
const mod = (await import("../../cli/index.js")) as unknown as { run: Run };
|
|
490
|
+
runner = mod.run;
|
|
491
|
+
}
|
|
492
|
+
return runner;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* ONE AT A TIME. Two writable opens racing each other is a thing the console
|
|
497
|
+
* never does from one terminal, and a double click on "remove" must not become
|
|
498
|
+
* two removals. The slot is held until the command has REALLY finished, even
|
|
499
|
+
* after a timeout has stopped waiting for it.
|
|
500
|
+
*/
|
|
501
|
+
let running: Promise<unknown> | null = null;
|
|
502
|
+
|
|
503
|
+
export function actionInFlight(): boolean {
|
|
504
|
+
return running !== null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Validate, build, run through the console's `run()`, and report what it said.
|
|
509
|
+
*
|
|
510
|
+
* A refusal by THE CONSOLE (exit 1–3) is an answer, not a failure of this door:
|
|
511
|
+
* it comes back 200 with the exit code and the console's own sentences.
|
|
512
|
+
*/
|
|
513
|
+
export async function runAction(
|
|
514
|
+
name: string,
|
|
515
|
+
body: unknown,
|
|
516
|
+
ctx: ActionContext,
|
|
517
|
+
opts: {
|
|
518
|
+
timeoutMs?: number;
|
|
519
|
+
/** The console's `run`, replaced — tests only, to prove the timeout and the queue. */
|
|
520
|
+
run?: Run;
|
|
521
|
+
} = {},
|
|
522
|
+
): Promise<ActionResult> {
|
|
523
|
+
if (!isActionName(name)) {
|
|
524
|
+
return { status: 404, body: { error: `no such action: ${name}. The dashboard offers ${ACTIONS.join(", ")}.` } };
|
|
525
|
+
}
|
|
526
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
527
|
+
return { status: 400, body: { error: "an action's body is a JSON object" } };
|
|
528
|
+
}
|
|
529
|
+
let built: Built;
|
|
530
|
+
try {
|
|
531
|
+
built = buildArgv(name, body as Body, ctx);
|
|
532
|
+
} catch (err) {
|
|
533
|
+
if (err instanceof Invalid) return { status: 400, body: { action: name, error: err.message } };
|
|
534
|
+
throw err;
|
|
535
|
+
}
|
|
536
|
+
if (running !== null) {
|
|
537
|
+
return {
|
|
538
|
+
status: 409,
|
|
539
|
+
body: { action: name, error: "another action is still running; nothing was done. Try again when it finishes." },
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
const out: string[] = [];
|
|
544
|
+
const err: string[] = [];
|
|
545
|
+
let bytes = 0;
|
|
546
|
+
let truncated = false;
|
|
547
|
+
const keep = (into: string[]) => (line: string): void => {
|
|
548
|
+
if (truncated) return;
|
|
549
|
+
bytes += line.length + 1;
|
|
550
|
+
if (bytes > MAX_OUTPUT_BYTES) {
|
|
551
|
+
truncated = true;
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
into.push(line);
|
|
555
|
+
};
|
|
556
|
+
let asked = false;
|
|
557
|
+
const io = {
|
|
558
|
+
out: keep(out),
|
|
559
|
+
err: keep(err),
|
|
560
|
+
// THE CLI'S OWN PROMPT, answered with what the owner typed — once. A
|
|
561
|
+
// second question is not one the owner saw, so it is refused, not answered.
|
|
562
|
+
...(built.answer === undefined
|
|
563
|
+
? {}
|
|
564
|
+
: {
|
|
565
|
+
prompt: async (): Promise<string> => {
|
|
566
|
+
if (asked) throw new Error("the dashboard answers one confirmation per action");
|
|
567
|
+
asked = true;
|
|
568
|
+
return built.answer as string;
|
|
569
|
+
},
|
|
570
|
+
}),
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
// THE SLOT IS CLAIMED BEFORE ANY AWAIT. Everything above is synchronous, so
|
|
574
|
+
// two requests in the same tick cannot both pass the check above and both
|
|
575
|
+
// run: the second sees `running` set here. (The first version claimed it
|
|
576
|
+
// after `await cliRun()`, and two notes sent together were both written.)
|
|
577
|
+
const work = (async (): Promise<number> => {
|
|
578
|
+
const run = opts.run ?? (await cliRun());
|
|
579
|
+
const env =
|
|
580
|
+
built.env === undefined ? ctx.env : { ...(ctx.env ?? (process.env as Record<string, string | undefined>)), ...built.env };
|
|
581
|
+
return run(built.argv, {
|
|
582
|
+
io,
|
|
583
|
+
...(env === undefined ? {} : { env }),
|
|
584
|
+
...(built.home !== undefined ? { home: built.home } : ctx.home === undefined ? {} : { home: ctx.home }),
|
|
585
|
+
// A note from the browser is filed under the store itself, not under
|
|
586
|
+
// whatever directory this server was launched from (see `RunOptions.scope`).
|
|
587
|
+
scope: ctx.dir,
|
|
588
|
+
});
|
|
589
|
+
})();
|
|
590
|
+
const slot = work.then(
|
|
591
|
+
() => undefined,
|
|
592
|
+
() => undefined,
|
|
593
|
+
);
|
|
594
|
+
running = slot;
|
|
595
|
+
void slot.then(() => {
|
|
596
|
+
if (running === slot) running = null;
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
const command = displayCommand(built.argv);
|
|
600
|
+
const limit = opts.timeoutMs ?? TIMEOUT_MS[name];
|
|
601
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
602
|
+
const timedOut = new Promise<"timeout">((done) => {
|
|
603
|
+
timer = setTimeout(() => done("timeout"), limit);
|
|
604
|
+
});
|
|
605
|
+
let exit: number | "timeout";
|
|
606
|
+
try {
|
|
607
|
+
exit = await Promise.race([work, timedOut]);
|
|
608
|
+
} catch (e) {
|
|
609
|
+
return {
|
|
610
|
+
status: 500,
|
|
611
|
+
body: { action: name, command, out, err, error: e instanceof Error ? e.message : String(e) },
|
|
612
|
+
};
|
|
613
|
+
} finally {
|
|
614
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
615
|
+
}
|
|
616
|
+
if (exit === "timeout") {
|
|
617
|
+
return {
|
|
618
|
+
status: 504,
|
|
619
|
+
body: {
|
|
620
|
+
action: name,
|
|
621
|
+
command,
|
|
622
|
+
out: [...out],
|
|
623
|
+
err: [...err],
|
|
624
|
+
error:
|
|
625
|
+
`still running after ${String(Math.round(limit / 1000))}s. It cannot be stopped from here, ` +
|
|
626
|
+
"so it is finishing in the background; no other action runs until it has.",
|
|
627
|
+
},
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
return { status: 200, body: { action: name, command, exit, ok: exit === 0, out, err, truncated } };
|
|
631
|
+
}
|