@drakonkat/ai-helper 1.2.18 → 1.2.20
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/ARCHITECTURE.md +7 -1
- package/CHANGELOG.md +19 -0
- package/README.md +36 -9
- package/package.json +1 -1
- package/src/hindsight.js +31 -2
- package/src/index.js +9 -4
- package/src/manager.js +107 -21
- package/src/proxy-presets.js +89 -35
- package/src/pxpipe-pool.js +69 -15
- package/src/tui-proxy-setup.js +3 -3
- package/src/tui.js +6 -1
package/ARCHITECTURE.md
CHANGED
|
@@ -91,7 +91,13 @@ belong to Docker Desktop (`com.docker.backend`, `wslrelay`). Readiness is the HT
|
|
|
91
91
|
status of Hindsight's `GET /health`; the live dashboard polls it every 5 seconds.
|
|
92
92
|
When Docker is unavailable, inspection is retried at most every 10 seconds so the
|
|
93
93
|
one-second dashboard refresh never blocks on a stopped daemon. Implementation:
|
|
94
|
-
`src/hindsight.js` (validation, docker argv, health probe, preflight).
|
|
94
|
+
`src/hindsight.js` (validation, docker argv, health probe, preflight, adoption settings).
|
|
95
|
+
|
|
96
|
+
Only containers labelled `io.aih.managed=true` are recreated. Any other container is
|
|
97
|
+
reused as is until the user adopts it (`update --adopt`): its image, ports, volume and
|
|
98
|
+
the environment it adds to its image become aih's settings, and aih recreates it.
|
|
99
|
+
Update stops the container, archives its volume to `~/.aih/backups` and only then
|
|
100
|
+
removes it; it never uses `docker rm -f`, which would SIGKILL the embedded database.
|
|
95
101
|
|
|
96
102
|
---
|
|
97
103
|
|
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,25 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.20] - 2026-11-13
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- **pxpipe overload no longer fails requests**: when the worker queue is full, a request waits more than 10 s, or the body exceeds 64 MiB, the proxy forwards it without pxpipe (stage reason `queue_full`, `queue_timeout`, `body_too_large`) instead of answering HTTP 503. pxpipe-only requests are checked before the JSON body is parsed.
|
|
11
|
+
- The worker queue is limited per worker (4 waiting requests) and by waiting time; the byte cap is now a memory guard of 4 × `--max-body-bytes` instead of a single request's size.
|
|
12
|
+
- Worker affinity follows the Codex thread instead of the session, so forked subagents no longer queue behind their parent and each other.
|
|
13
|
+
- A client disconnect no longer terminates the active pxpipe worker: its result is discarded and the warm worker is kept (replaced only if still busy after 120 s).
|
|
14
|
+
- Compressed requests that decompress beyond `--max-body-bytes` are forwarded unchanged instead of failing; unchanged bodies are no longer re-serialized before pxpipe.
|
|
15
|
+
|
|
16
|
+
## [1.2.19] - 2026-11-10
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- **Adopt an existing Hindsight container**: `aih update hindsight --adopt`, or `u` twice in the live dashboard, imports the image, ports, data volume and environment of a container aih did not create (for example docker compose) into aih's settings and recreates it on the same volume. Without that explicit request such containers are still left untouched.
|
|
20
|
+
- `aih update hindsight` archives the data volume to `~/.aih/backups` (two most recent kept) before replacing the container; a failed archive leaves the old container running.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- `aih update hindsight` moves a version tag of the official image (e.g. `:1.1.0`) to the latest GitHub release and saves it in the settings, instead of pulling the same tag again. `:latest` and custom images behave as before.
|
|
24
|
+
- Hindsight updates stop the container before removing it instead of `docker rm -f`.
|
|
25
|
+
|
|
7
26
|
## [1.2.18] - 2026-11-06
|
|
8
27
|
|
|
9
28
|
### Changed
|
package/README.md
CHANGED
|
@@ -112,13 +112,32 @@ not by PID, and never kills processes on its ports (on Windows they belong to Do
|
|
|
112
112
|
- **stop** runs `docker stop`; data stays in the volume. **logs** shows `docker logs`;
|
|
113
113
|
the docker commands run by aih are recorded in `~/.aih/logs/hindsight.log`.
|
|
114
114
|
- **An existing container with the same name is reused as is**, for example one created
|
|
115
|
-
by docker compose. aih starts/stops it but never recreates or updates it
|
|
115
|
+
by docker compose. aih starts/stops it but never recreates or updates it until you
|
|
116
|
+
adopt it.
|
|
117
|
+
- **adopt** (`aih update hindsight --adopt`, or `u` twice in the dashboard: the first
|
|
118
|
+
press explains, the second adopts) makes aih the owner of such a container. aih reads
|
|
119
|
+
its image, published ports, data volume and environment, saves provider, model and
|
|
120
|
+
base URL in the settings, the LLM key in `~/.aih/hindsight.env` and every other
|
|
121
|
+
variable set on top of the image (failover models, timeouts...) in
|
|
122
|
+
`~/.aih/hindsight-extra.env`, then stops it and recreates it on the same volume with
|
|
123
|
+
the same image. Ports are published on loopback only. Adoption is refused, changing
|
|
124
|
+
nothing, unless the data is in a single Docker volume mounted at
|
|
125
|
+
`/home/hindsight/.pg0`. Afterwards stop using the tool that created the container
|
|
126
|
+
(`docker compose up` would conflict on the name).
|
|
116
127
|
- Containers created by aih carry the labels `io.aih.managed=true` and a settings
|
|
117
128
|
fingerprint: after a settings change they are recreated on the next start (or by
|
|
118
129
|
*Save and apply now* if running), always keeping the data volume.
|
|
119
|
-
- **update** (`aih update hindsight` or `u`)
|
|
120
|
-
|
|
121
|
-
|
|
130
|
+
- **update** (`aih update hindsight` or `u`) works on containers created or adopted by
|
|
131
|
+
aih. When the image is the official one with a version tag (`:1.1.0`), it pulls the
|
|
132
|
+
latest GitHub release and saves the new tag in the settings; any other tag
|
|
133
|
+
(`:latest`, custom images) is pulled again and nothing happens if the image did not
|
|
134
|
+
change. Before replacing the container aih stops it and archives the data volume to
|
|
135
|
+
`~/.aih/backups/hindsight-<timestamp>.tgz` (the two most recent are kept), because a
|
|
136
|
+
newer version may migrate the database. If the archive fails, the old container is
|
|
137
|
+
started again and nothing changes. A running container is recreated and checked again
|
|
138
|
+
through `/health`. To go back, restore the archive into the volume with the container
|
|
139
|
+
stopped and set the previous tag in the settings:
|
|
140
|
+
`docker run --rm -v hindsight-data:/d -v ~/.aih/backups:/b alpine sh -c "rm -rf /d/* /d/.[!.]* && tar xzf /b/<file> -C /d"`.
|
|
122
141
|
|
|
123
142
|
Settings are edited in `aih status --ui` → **`c`** after selecting **hindsight** in the
|
|
124
143
|
Startup step: container name, image (default `ghcr.io/vectorize-io/hindsight:latest`),
|
|
@@ -167,7 +186,7 @@ spaces, such as `--interceptor "./my hooks/interceptor.mjs"`.
|
|
|
167
186
|
| `restart [services...] [--json]` | `aih restart ocx hindsight --json` |
|
|
168
187
|
| `restart proxy [upstream] [proxy options] [--json]` | `aih restart proxy --models="gpt-6-astra,anthropic/claude-fable*"` |
|
|
169
188
|
| `update [--json]` | `aih update` (update aih itself from npm) |
|
|
170
|
-
| `update <services...> [--json]` | `aih update ocx hindsight --json`; `aih ocx update` |
|
|
189
|
+
| `update <services...> [--json] [--adopt]` | `aih update ocx hindsight --json`; `aih ocx update`; `aih update hindsight --adopt` |
|
|
171
190
|
| `open [services...] [--repo]` | `aih open hindsight`; `aih open proxy --repo` |
|
|
172
191
|
| `logs <service> [-n <lines>] [-f]` | `aih logs proxy --lines=100 --follow` |
|
|
173
192
|
| `stats proxy [--json]` | `aih stats proxy --json` |
|
|
@@ -372,6 +391,7 @@ built-in proxy with `aih restart proxy` to load the updated code.
|
|
|
372
391
|
aih ocx update # update OpenCodex to the latest available release
|
|
373
392
|
aih update ocx # equivalent command-first form
|
|
374
393
|
aih update ocx hindsight # update selected services
|
|
394
|
+
aih update hindsight --adopt # take over a Hindsight container not created by aih
|
|
375
395
|
aih update pxpipe ocx hindsight headroom # all managed services, not aih itself
|
|
376
396
|
aih update ocx --json # JSON result array, exit code 1 on any failure
|
|
377
397
|
```
|
|
@@ -446,10 +466,17 @@ tokenization costs and worker-thread experiments.
|
|
|
446
466
|
|
|
447
467
|
Pxpipe transformations and their token estimates run in up to **two persistent
|
|
448
468
|
CPU workers**. Excluded models bypass the worker queue; HTTP and SSE streaming
|
|
449
|
-
remain on the main thread.
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
469
|
+
remain on the main thread. Each Codex thread keeps a stable worker to reuse caches;
|
|
470
|
+
a new thread (for example a forked subagent) starts on its parent's worker only when
|
|
471
|
+
that worker is idle, otherwise on the least busy one. Each worker accepts up to 4
|
|
472
|
+
waiting requests, each waiting at most 10 s, and all waiting input is capped at
|
|
473
|
+
4 × `--max-body-bytes`. Requests over these limits, or with bodies over 64 MiB, are
|
|
474
|
+
**forwarded without pxpipe** (stage reason `queue_full`, `queue_timeout` or
|
|
475
|
+
`body_too_large`) instead of failing; pxpipe-only requests are checked before
|
|
476
|
+
parsing. Compressed bodies that decompress beyond `--max-body-bytes` are forwarded
|
|
477
|
+
unchanged. Disconnecting cancels queued work; an active transformation finishes on
|
|
478
|
+
its warm worker and its result is discarded (a worker still busy after 120 s is
|
|
479
|
+
replaced). Shutdown closes both workers.
|
|
453
480
|
|
|
454
481
|
Installation applies a version-checked correction to pxpipe 0.14.0: diagnostic
|
|
455
482
|
composition counts exclude encrypted reasoning, opaque compaction and media data,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.20",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, hindsight, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
package/src/hindsight.js
CHANGED
|
@@ -6,9 +6,10 @@ import { ensureDir, getAihDir, getLogsDir, getServiceLogPath } from "./utils/pat
|
|
|
6
6
|
import { execCommand } from "./utils/process.js";
|
|
7
7
|
|
|
8
8
|
/** Hindsight runs in Docker; these defaults match the upstream quick start. */
|
|
9
|
+
export const HINDSIGHT_REPOSITORY = "ghcr.io/vectorize-io/hindsight";
|
|
9
10
|
export const HINDSIGHT_DEFAULTS = Object.freeze({
|
|
10
11
|
containerName: "hindsight",
|
|
11
|
-
image: "
|
|
12
|
+
image: HINDSIGHT_REPOSITORY + ":latest",
|
|
12
13
|
apiPort: 8888,
|
|
13
14
|
uiPort: 9999,
|
|
14
15
|
volume: "hindsight-data",
|
|
@@ -154,9 +155,37 @@ export async function inspectContainer(name, run = execCommand, timeout = 5000)
|
|
|
154
155
|
managed: labels["io.aih.managed"] === "true",
|
|
155
156
|
configHash: labels["io.aih.config"] || null,
|
|
156
157
|
composeProject: labels["com.docker.compose.project"] || null,
|
|
158
|
+
// Read only to adopt a container aih did not create.
|
|
159
|
+
env: container?.Config?.Env || [],
|
|
160
|
+
mounts: (container?.Mounts || []).map(m => ({ type: m.Type, name: m.Name, destination: m.Destination })),
|
|
161
|
+
ports: container?.HostConfig?.PortBindings || {},
|
|
157
162
|
};
|
|
158
163
|
}
|
|
159
164
|
|
|
165
|
+
/**
|
|
166
|
+
* Settings that let aih recreate a container it did not create: image, ports, data volume and
|
|
167
|
+
* the variables set on top of its image. Throws when something would be lost.
|
|
168
|
+
*/
|
|
169
|
+
export function adoptedHindsightSettings(containerName, container, imageEnv) {
|
|
170
|
+
const data = container.mounts.find(m => m.destination === DATA_DIR);
|
|
171
|
+
if (data?.type !== "volume" || container.mounts.length !== 1) {
|
|
172
|
+
throw new Error("its data must be in one Docker volume mounted at " + DATA_DIR + ", with no other mounts");
|
|
173
|
+
}
|
|
174
|
+
const inherited = new Set(imageEnv);
|
|
175
|
+
const env = new Map(container.env.filter(line => !inherited.has(line)).map(line => line.split(/=(.*)/s).slice(0, 2)));
|
|
176
|
+
const take = name => { const value = env.get(name); env.delete(name); return value; };
|
|
177
|
+
const hostPort = port => container.ports[port + "/tcp"]?.[0]?.HostPort;
|
|
178
|
+
take("HINDSIGHT_CP_DATAPLANE_API_URL"); // always set by aih
|
|
179
|
+
const key = validateHindsightApiKey(take(HINDSIGHT_KEY_ENV) || "");
|
|
180
|
+
const config = normalizeHindsightConfig({
|
|
181
|
+
containerName, image: container.image, volume: data.name, apiPort: hostPort(API_PORT), uiPort: hostPort(UI_PORT),
|
|
182
|
+
llmProvider: take("HINDSIGHT_API_LLM_PROVIDER"), llmModel: take("HINDSIGHT_API_LLM_MODEL"), llmBaseUrl: take("HINDSIGHT_API_LLM_BASE_URL"),
|
|
183
|
+
});
|
|
184
|
+
const extra = [...env].map(([name, value]) => name + "=" + value);
|
|
185
|
+
if (extra.some(line => /[\r\n]/.test(line))) throw new Error("a multi-line environment value cannot be written to an env file");
|
|
186
|
+
return { config, key, extra };
|
|
187
|
+
}
|
|
188
|
+
|
|
160
189
|
export async function imageId(image, run = execCommand) {
|
|
161
190
|
const result = await run("docker", ["image", "inspect", "--format", "{{.Id}}", image], 10000);
|
|
162
191
|
return result.exitCode === 0 ? result.stdout.trim() || null : null;
|
|
@@ -239,7 +268,7 @@ export async function preflightHindsight(config, { newKey = "", run = execComman
|
|
|
239
268
|
let container = null;
|
|
240
269
|
try { container = await inspectContainer(config.containerName, run); } catch (error) { checks.push("Warning: " + error.message); }
|
|
241
270
|
if (container) {
|
|
242
|
-
const owner = container.managed ? "created by aih" : "not created by aih" + (container.composeProject ? " (compose project '" + container.composeProject + "')" : "") + "; it is reused as is and the settings above do not change it";
|
|
271
|
+
const owner = container.managed ? "created by aih" : "not created by aih" + (container.composeProject ? " (compose project '" + container.composeProject + "')" : "") + "; it is reused as is and the settings above do not change it. To manage it from aih, adopt it: press u on hindsight in the dashboard";
|
|
243
272
|
checks.push("Container '" + config.containerName + "' " + container.status + ", " + owner);
|
|
244
273
|
if (container.managed && container.configHash !== hindsightConfigHash(config, newKey || saved.key)) {
|
|
245
274
|
checks.push("Settings changed: aih recreates the container on its next start (data volume kept)");
|
package/src/index.js
CHANGED
|
@@ -66,12 +66,16 @@ ${bold("HINDSIGHT (DOCKER):")}
|
|
|
66
66
|
Configure container, ports, LLM provider/model/base URL and API key in status --ui (c),
|
|
67
67
|
after selecting hindsight in the Startup step. The key is kept in ~/.aih/hindsight.env;
|
|
68
68
|
HINDSIGHT_API_LLM_API_KEY from the environment is used when no key is saved.
|
|
69
|
-
update
|
|
69
|
+
update moves a version tag of the official image to the latest release (other tags are pulled
|
|
70
|
+
again), archives the data volume in ~/.aih/backups and recreates the container. A container
|
|
71
|
+
not created by aih (e.g. docker compose) is left alone until adopted: update hindsight --adopt
|
|
72
|
+
imports its image, ports, volume and environment and recreates it on the same volume.
|
|
70
73
|
|
|
71
74
|
${bold("OPTIONS:")}
|
|
72
75
|
${gray("-n, --lines <num>")} Number of log lines to show (logs only; default: 50)
|
|
73
76
|
${gray("-f, --follow")} Follow log output in real-time (logs only)
|
|
74
77
|
${gray("--json")} JSON for status, start/up, restart, update and stats
|
|
78
|
+
${gray("--adopt")} Take over a Hindsight container not created by aih (update only)
|
|
75
79
|
${gray("--repo")} Open GitHub repositories instead of dashboards (open only)
|
|
76
80
|
${gray("--gpt")} Start the configured Windows Astra chain (start/up only)
|
|
77
81
|
${gray("-ui, --ui")} Open the interactive dashboard (status only, requires a TTY)
|
|
@@ -345,12 +349,13 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
345
349
|
case "update": {
|
|
346
350
|
const ids = [...new Set(targets)];
|
|
347
351
|
const invalid = ids.filter(id => !SERVICE_IDS.includes(id));
|
|
348
|
-
const
|
|
352
|
+
const adopt = rawArgs.includes("--adopt");
|
|
353
|
+
const invalidOption = rawArgs.find(arg => arg.startsWith("-") && arg !== "--json" && arg !== "--adopt");
|
|
349
354
|
let results;
|
|
350
355
|
// Validate the entire request before updating anything, including the
|
|
351
356
|
// service-first alias (which accepts exactly one service).
|
|
352
357
|
if (invalidOption) {
|
|
353
|
-
results = [{ id: targets[0] || null, success: false, message: `Unsupported update option '${invalidOption}'. Only --json
|
|
358
|
+
results = [{ id: targets[0] || null, success: false, message: `Unsupported update option '${invalidOption}'. Only --json and --adopt are supported.` }];
|
|
354
359
|
} else if (serviceFirstUpdate && positionalArgs.length !== 2) {
|
|
355
360
|
results = [{ id: targets[0], success: false, message: `Usage: ${CLI_NAME} <service> update [--json]; use '${CLI_NAME} update <services...>' for multiple services.` }];
|
|
356
361
|
} else if (invalid.length) {
|
|
@@ -364,7 +369,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
364
369
|
if (!jsonOutput) process.stdout.write(` Updating ${bold(id)}... `);
|
|
365
370
|
let result;
|
|
366
371
|
try {
|
|
367
|
-
result = id === CLI_NAME ? await updateSelfImpl() : await manager.updateService(id);
|
|
372
|
+
result = id === CLI_NAME ? await updateSelfImpl() : await manager.updateService(id, { adopt });
|
|
368
373
|
} catch (err) {
|
|
369
374
|
result = { success: false, message: err?.message || String(err) };
|
|
370
375
|
}
|
package/src/manager.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync, readdirSync, rmSync } from "node:fs";
|
|
2
2
|
import { execFileSync, spawn } from "node:child_process";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -11,6 +11,8 @@ import { installServiceUpdate, serviceStartCommand } from "./service-updates.js"
|
|
|
11
11
|
import { configureCodexForProxy } from "./codex-routing.js";
|
|
12
12
|
import {
|
|
13
13
|
HINDSIGHT_DEFAULTS,
|
|
14
|
+
HINDSIGHT_REPOSITORY,
|
|
15
|
+
adoptedHindsightSettings,
|
|
14
16
|
describeHealth,
|
|
15
17
|
dockerInfo,
|
|
16
18
|
dockerLogged,
|
|
@@ -62,8 +64,8 @@ export class ServiceManager {
|
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
/** Explicit update: fresh check, stop if needed, install, verify, restore runtime state. */
|
|
65
|
-
async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate } = {}) {
|
|
66
|
-
if (isDocker(serviceId)) return this.updateDockerService(serviceId);
|
|
67
|
+
async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate, adopt = false } = {}) {
|
|
68
|
+
if (isDocker(serviceId)) return this.updateDockerService(serviceId, { getVersions, adopt });
|
|
67
69
|
if (!Object.hasOwn(SERVICE_PACKAGES, serviceId)) {
|
|
68
70
|
return { success: false, message: serviceId === "proxy"
|
|
69
71
|
? "The built-in proxy is part of ai-helper; update ai-helper itself to update it."
|
|
@@ -557,39 +559,71 @@ export class ServiceManager {
|
|
|
557
559
|
return { success: true, message: `Hindsight container '${config.containerName}' stopped (data kept)` };
|
|
558
560
|
}
|
|
559
561
|
|
|
560
|
-
/**
|
|
561
|
-
|
|
562
|
+
/**
|
|
563
|
+
* Pull, back up the data, then recreate. Only containers aih created are replaced:
|
|
564
|
+
* any other container belongs to its owner until the user explicitly adopts it.
|
|
565
|
+
*/
|
|
566
|
+
async updateDockerService(id, { getVersions = getServiceVersions, adopt = false } = {}) {
|
|
562
567
|
if (this.updatesInProgress.has(id)) return { success: false, message: `An update for '${id}' is already in progress` };
|
|
563
568
|
this.updatesInProgress.add(id);
|
|
564
569
|
try {
|
|
565
570
|
const config = this.hindsightConfig(this.readState(), { strict: true });
|
|
571
|
+
const name = config.containerName;
|
|
566
572
|
const docker = await dockerInfo(this.runDocker);
|
|
567
573
|
if (!docker.available) return { success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
|
|
568
|
-
const container = await inspectContainer(
|
|
574
|
+
const container = await inspectContainer(name, this.runDocker, 10000);
|
|
569
575
|
if (container && !container.managed) {
|
|
570
|
-
|
|
576
|
+
if (adopt) return await this.adoptDockerService(id, name, container);
|
|
577
|
+
return { success: false, adoptable: true, message: `Container '${name}' was not created by aih${container.composeProject ? ` (docker compose project '${container.composeProject}')` : ""}. To adopt it run 'aih update ${id} --adopt' (dashboard: press u again): aih imports its settings and recreates it on the same data volume.` };
|
|
571
578
|
}
|
|
572
579
|
const previousVersion = container?.running ? (await this.probeHealth(hindsightUrls(config).api)).version ?? null : null;
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
580
|
+
// A release tag of the official image moves to the latest GitHub release; any other tag is pulled again.
|
|
581
|
+
const tag = config.image.startsWith(HINDSIGHT_REPOSITORY + ":") ? config.image.slice(HINDSIGHT_REPOSITORY.length + 1) : "";
|
|
582
|
+
let image = config.image;
|
|
583
|
+
if (compareVersions(tag, tag) !== null) {
|
|
584
|
+
const latest = (await getVersions([{ id }]))[id]?.latestVersion;
|
|
585
|
+
const comparison = compareVersions(tag, latest);
|
|
586
|
+
if (comparison === null) return { success: false, previousVersion, message: "Cannot determine the latest Hindsight release; no changes made. Check your connection and retry." };
|
|
587
|
+
if (comparison >= 0) {
|
|
588
|
+
return { success: true, updated: false, alreadyUpToDate: true, previousVersion, version: previousVersion,
|
|
589
|
+
message: `'${id}' is already up to date (${config.image})` };
|
|
590
|
+
}
|
|
591
|
+
image = HINDSIGHT_REPOSITORY + ":" + latest;
|
|
592
|
+
}
|
|
593
|
+
const pulled = await dockerLogged(id, ["pull", image], this.runDocker, 30 * 60000);
|
|
594
|
+
if (pulled.exitCode !== 0) return { success: false, previousVersion, message: `docker pull ${image} failed: ${dockerError(pulled)}` };
|
|
595
|
+
const saveImage = () => { if (image !== config.image) this.saveHindsightConfiguration({ config: { ...config, image } }); };
|
|
596
|
+
if (!container) {
|
|
597
|
+
saveImage();
|
|
598
|
+
return { success: true, updated: true, previousVersion, message: `Image ${image} pulled; the container is created on the next start` };
|
|
599
|
+
}
|
|
600
|
+
const pulledImage = await imageId(image, this.runDocker);
|
|
601
|
+
if (image === config.image && pulledImage && pulledImage === container.imageId) {
|
|
578
602
|
return { success: true, updated: false, alreadyUpToDate: true, previousVersion, version: previousVersion,
|
|
579
|
-
message: `'${id}' already uses the latest ${
|
|
603
|
+
message: `'${id}' already uses the latest ${image}` };
|
|
580
604
|
}
|
|
581
|
-
|
|
582
|
-
|
|
605
|
+
// Stop first: the archive needs a quiet database, and 'rm -f' would SIGKILL it.
|
|
606
|
+
const stopped = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
|
|
607
|
+
const backup = stopped.exitCode === 0 ? await this.backupHindsightVolume(id, config.volume, container.imageId)
|
|
608
|
+
: { success: false, message: dockerError(stopped) };
|
|
609
|
+
const removed = backup.success ? await dockerLogged(id, ["rm", name], this.runDocker, 60000) : null;
|
|
610
|
+
if (removed?.exitCode !== 0) {
|
|
611
|
+
if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
|
|
612
|
+
await this.syncState();
|
|
613
|
+
return { success: false, previousVersion, message: (backup.success ? `Cannot replace the container: ${dockerError(removed)}`
|
|
614
|
+
: `Data backup failed: ${backup.message}`) + "; the current container is kept" };
|
|
615
|
+
}
|
|
616
|
+
saveImage();
|
|
583
617
|
if (!container.running) {
|
|
584
618
|
await this.syncState();
|
|
585
|
-
return { success: true, updated: true, restarted: false, previousVersion,
|
|
586
|
-
message: `Image ${
|
|
619
|
+
return { success: true, updated: true, restarted: false, previousVersion, backup: backup.path,
|
|
620
|
+
message: `Image ${image} updated; the container is recreated on the next start (data backup: ${backup.path})` };
|
|
587
621
|
}
|
|
588
622
|
const started = await this.startDockerService(id);
|
|
589
623
|
const version = started.health?.version ?? null;
|
|
590
|
-
return { ...started, updated: true, restarted: started.success, previousVersion, version,
|
|
591
|
-
message: started.success ? `'${id}' updated${previousVersion && version ? ` from ${previousVersion} to ${version}` : ""} and restarted`
|
|
592
|
-
: `Image updated, but restart failed: ${started.message}` };
|
|
624
|
+
return { ...started, updated: true, restarted: started.success, previousVersion, version, backup: backup.path,
|
|
625
|
+
message: (started.success ? `'${id}' updated${previousVersion && version ? ` from ${previousVersion} to ${version}` : ""} and restarted`
|
|
626
|
+
: `Image updated, but restart failed: ${started.message}`) + ` (data backup: ${backup.path})` };
|
|
593
627
|
} catch (error) {
|
|
594
628
|
return { success: false, message: `Update failed: ${error.message}` };
|
|
595
629
|
} finally {
|
|
@@ -597,6 +631,58 @@ export class ServiceManager {
|
|
|
597
631
|
}
|
|
598
632
|
}
|
|
599
633
|
|
|
634
|
+
/** Archives a stopped container's data volume in ~/.aih/backups, keeping the two most recent archives. */
|
|
635
|
+
async backupHindsightVolume(id, volume, image) {
|
|
636
|
+
const dir = join(getAihDir(), "backups");
|
|
637
|
+
ensureDir(dir);
|
|
638
|
+
const file = `hindsight-${new Date().toISOString().replace(/[-:]|\..*/g, "")}.tgz`;
|
|
639
|
+
// The container's own image already has tar: nothing else to pull. Root, so the archive is writable on Linux.
|
|
640
|
+
const result = await dockerLogged(id, ["run", "--rm", "--user", "0", "--entrypoint", "tar", "-v", volume + ":/d:ro", "-v", dir + ":/b",
|
|
641
|
+
image, "czf", "/b/" + file, "-C", "/d", "."], this.runDocker, 30 * 60000);
|
|
642
|
+
if (result.exitCode !== 0) {
|
|
643
|
+
rmSync(join(dir, file), { force: true });
|
|
644
|
+
return { success: false, message: dockerError(result) };
|
|
645
|
+
}
|
|
646
|
+
for (const old of readdirSync(dir).filter(f => /^hindsight-.*\.tgz$/.test(f)).sort().slice(0, -2)) rmSync(join(dir, old), { force: true });
|
|
647
|
+
return { success: true, path: join(dir, file) };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Takes over a container aih did not create: imports its settings, then recreates it on the same volume. */
|
|
651
|
+
async adoptDockerService(id, name, container) {
|
|
652
|
+
const refuse = reason => ({ success: false, message: `Cannot adopt container '${name}': ${reason}. Nothing was changed.` });
|
|
653
|
+
// Variables already defined by the image are not settings: importing them would pin them across updates.
|
|
654
|
+
const imageEnv = await this.runDocker("docker", ["image", "inspect", "--format", "{{json .Config.Env}}", container.imageId], 10000);
|
|
655
|
+
if (imageEnv.exitCode !== 0) return refuse(dockerError(imageEnv));
|
|
656
|
+
let adopted;
|
|
657
|
+
try { adopted = adoptedHindsightSettings(name, container, JSON.parse(imageEnv.stdout) || []); }
|
|
658
|
+
catch (error) { return refuse(error.message); }
|
|
659
|
+
if (!adopted.key && !readHindsightApiKey().key && requiresApiKey(adopted.config)) {
|
|
660
|
+
return refuse(`it has no LLM API key for provider '${adopted.config.llmProvider}'; save one in setup (c) first`);
|
|
661
|
+
}
|
|
662
|
+
const envFile = adopted.extra.length ? join(getAihDir(), "hindsight-extra.env") : "";
|
|
663
|
+
if (envFile) {
|
|
664
|
+
ensureDir(getAihDir());
|
|
665
|
+
writeFileSync(envFile, adopted.extra.join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
|
|
666
|
+
}
|
|
667
|
+
this.saveHindsightConfiguration({ config: { ...adopted.config, envFile }, apiKey: adopted.key });
|
|
668
|
+
const stopped = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
|
|
669
|
+
const removed = stopped.exitCode === 0 ? await dockerLogged(id, ["rm", name], this.runDocker, 60000) : stopped;
|
|
670
|
+
if (removed.exitCode !== 0) {
|
|
671
|
+
if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
|
|
672
|
+
await this.syncState();
|
|
673
|
+
return { success: false, message: `Settings imported, but the container could not be replaced: ${dockerError(removed)}` };
|
|
674
|
+
}
|
|
675
|
+
const kept = `data volume '${adopted.config.volume}' kept`;
|
|
676
|
+
if (!container.running) {
|
|
677
|
+
await this.syncState();
|
|
678
|
+
return { success: true, adopted: true, message: `Container '${name}' adopted; aih recreates it on the next start (${kept})` };
|
|
679
|
+
}
|
|
680
|
+
const started = await this.startDockerService(id);
|
|
681
|
+
return { ...started, adopted: true, message: started.success
|
|
682
|
+
? `Container '${name}' adopted and recreated by aih (${kept}; ${describeHealth(started.health)}). Update it with u or 'aih update ${id}'.`
|
|
683
|
+
: `Settings imported and old container removed, but the new one failed: ${started.message}` };
|
|
684
|
+
}
|
|
685
|
+
|
|
600
686
|
/** Non-secret settings go to state.json; the key only to ~/.aih/hindsight.env. */
|
|
601
687
|
saveHindsightConfiguration({ config, apiKey = "" } = {}) {
|
|
602
688
|
const normalized = normalizeHindsightConfig(config);
|
|
@@ -618,7 +704,7 @@ export class ServiceManager {
|
|
|
618
704
|
catch (error) { return { success: true, warning: true, message: `Hindsight settings saved; Docker not available (${error.message})` }; }
|
|
619
705
|
if (!container?.running) return { success: true, message: "Hindsight settings saved for its next start" };
|
|
620
706
|
if (!container.managed) {
|
|
621
|
-
return { success: true, warning: true, message: `Hindsight settings saved; container '${config.containerName}' was not created by aih and is left unchanged` };
|
|
707
|
+
return { success: true, warning: true, message: `Hindsight settings saved; container '${config.containerName}' was not created by aih and is left unchanged (adopt it with u on the dashboard)` };
|
|
622
708
|
}
|
|
623
709
|
if (container.configHash === hindsightConfigHash(config, readHindsightApiKey().key)) return { success: true, message: "Hindsight unchanged" };
|
|
624
710
|
const stopped = await this.stopDockerService("hindsight");
|
package/src/proxy-presets.js
CHANGED
|
@@ -10,6 +10,28 @@ import { createPxpipePool } from "./pxpipe-pool.js";
|
|
|
10
10
|
export const PRESETS = Object.freeze(["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"]);
|
|
11
11
|
const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
|
|
12
12
|
...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
|
|
13
|
+
// Safety net, not load control: bodies this large would occupy a worker for minutes.
|
|
14
|
+
export const PXPIPE_MAX_INPUT_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
const requestFormat = path => {
|
|
17
|
+
const pathname = new URL(path, "http://localhost").pathname;
|
|
18
|
+
return /\/(?:v1\/|anthropic\/)?messages$/.test(pathname) ? "anthropic"
|
|
19
|
+
: /\/chat\/completions$/.test(pathname) ? "chat" : /\/responses$/.test(pathname) ? "responses" : null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function turnMetadata(headers) {
|
|
23
|
+
try {
|
|
24
|
+
const metadata = JSON.parse(headers?.["x-codex-turn-metadata"] || "{}");
|
|
25
|
+
return metadata && typeof metadata === "object" ? metadata : {};
|
|
26
|
+
} catch { return {}; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const text = value => typeof value === "string" && value.length ? value.slice(0, 128) : undefined;
|
|
30
|
+
const affinityOf = context => {
|
|
31
|
+
const metadata = turnMetadata(context.headers);
|
|
32
|
+
return { threadId: text(metadata.thread_id), sessionId: text(metadata.session_id) };
|
|
33
|
+
};
|
|
34
|
+
const skippedPxpipe = reason => tokenStage("pxpipe", 0, 0, false, reason, "not_measured");
|
|
13
35
|
|
|
14
36
|
export function normalizePresetOptions(options) {
|
|
15
37
|
const preset = options.preset || "none";
|
|
@@ -88,9 +110,44 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
88
110
|
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy/applicability") : null;
|
|
89
111
|
const pool = px ? createPxpipePool(config.maxBodyBytes) : null;
|
|
90
112
|
const models = config.models?.split(",");
|
|
113
|
+
const listed = model => models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m);
|
|
114
|
+
const pxpipeModel = model => models ? listed(model) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model);
|
|
91
115
|
const wsModels = new WeakMap();
|
|
92
116
|
const warnedEncodings = new Set();
|
|
93
117
|
|
|
118
|
+
function record(context, websocket, started, { model, changed, stages, error, timings = {} }) {
|
|
119
|
+
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
120
|
+
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
121
|
+
const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
|
|
122
|
+
let source = {};
|
|
123
|
+
try {
|
|
124
|
+
const metadata = turnMetadata(context.headers);
|
|
125
|
+
const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
|
|
126
|
+
const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
|
|
127
|
+
.replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
|
|
128
|
+
source = Object.fromEntries(Object.entries({ sessionId: text(metadata.session_id), threadId: text(metadata.thread_id), project: text(project) })
|
|
129
|
+
.filter(([, value]) => value !== undefined));
|
|
130
|
+
} catch {}
|
|
131
|
+
try {
|
|
132
|
+
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
133
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...timings },
|
|
134
|
+
...source, ...(requestId ? { requestId } : {}) });
|
|
135
|
+
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
136
|
+
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
137
|
+
} catch {}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// pxpipe-only HTTP: decide a capacity/size skip before parsing a multi-MB JSON body.
|
|
141
|
+
function skipBeforeParse(raw, context, started) {
|
|
142
|
+
if (!requestFormat(context.path)) return false;
|
|
143
|
+
// Only a leading top-level model is trusted; anything else takes the normal path.
|
|
144
|
+
const model = /^\s*\{\s*"model"\s*:\s*"([^"\\]{1,128})"/.exec(raw.subarray(0, 512).toString("latin1"))?.[1];
|
|
145
|
+
if (!model || !pxpipeModel(model)) return false;
|
|
146
|
+
const reason = raw.length > PXPIPE_MAX_INPUT_BYTES ? "body_too_large" : pool.full(affinityOf(context), raw.length) ? "queue_full" : null;
|
|
147
|
+
if (reason) record(context, false, started, { model, changed: false, stages: [skippedPxpipe(reason)], error: false });
|
|
148
|
+
return Boolean(reason);
|
|
149
|
+
}
|
|
150
|
+
|
|
94
151
|
async function headroom(body, model) {
|
|
95
152
|
// Responses items (reasoning, calls, IDs, images) stay native. Compress only their tool text.
|
|
96
153
|
const slots = Array.isArray(body.input) ? toolTexts(body) : null;
|
|
@@ -123,9 +180,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
123
180
|
}
|
|
124
181
|
|
|
125
182
|
async function transform(raw, context, websocket = false, started = performance.now()) {
|
|
126
|
-
const
|
|
127
|
-
const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
|
|
128
|
-
: /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
|
|
183
|
+
const format = requestFormat(context.path);
|
|
129
184
|
if (!format) return raw;
|
|
130
185
|
let envelope;
|
|
131
186
|
try { envelope = JSON.parse(raw.toString("utf8")); } catch { return raw; }
|
|
@@ -142,29 +197,9 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
142
197
|
let changed = false;
|
|
143
198
|
const stages = [];
|
|
144
199
|
let pxpipeTimings = {};
|
|
145
|
-
const report = error => {
|
|
146
|
-
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
147
|
-
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
148
|
-
const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
|
|
149
|
-
let source = {};
|
|
150
|
-
try {
|
|
151
|
-
const metadata = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}");
|
|
152
|
-
const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
|
|
153
|
-
const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
|
|
154
|
-
.replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
|
|
155
|
-
source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
|
|
156
|
-
.filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
|
|
157
|
-
} catch {}
|
|
158
|
-
try {
|
|
159
|
-
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
160
|
-
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...pxpipeTimings },
|
|
161
|
-
...source, ...(requestId ? { requestId } : {}) });
|
|
162
|
-
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
163
|
-
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
164
|
-
} catch {}
|
|
165
|
-
};
|
|
200
|
+
const report = error => record(context, websocket, started, { model, changed, stages, error, timings: pxpipeTimings });
|
|
166
201
|
// Preserve observability and byte-for-byte forwarding for excluded models.
|
|
167
|
-
if (models && !
|
|
202
|
+
if (models && !listed(model)) {
|
|
168
203
|
for (const stage of config.preset.split("-")) stages.push(tokenStage(stage, 0, 0, false, "model_excluded", "not_measured"));
|
|
169
204
|
report(false);
|
|
170
205
|
return raw;
|
|
@@ -192,15 +227,26 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
192
227
|
// A Headroom no-op must not discard changes already made by RTK.
|
|
193
228
|
changed = JSON.stringify(body) !== before || changed;
|
|
194
229
|
}
|
|
230
|
+
let result;
|
|
195
231
|
if (bypassPxpipe) {
|
|
196
232
|
stages.push(tokenStage("pxpipe", 0, 0, false, "native_images_present", "pxpipe_estimate"));
|
|
197
|
-
} else if (px && (
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
233
|
+
} else if (px && pxpipeModel(model) && raw.length > PXPIPE_MAX_INPUT_BYTES) {
|
|
234
|
+
stages.push(skippedPxpipe("body_too_large"));
|
|
235
|
+
} else if (px && pxpipeModel(model)) {
|
|
236
|
+
// An unchanged HTTP body already carries the model: skip a second multi-MB serialization.
|
|
237
|
+
const reuse = !changed && body === envelope && body.model === model;
|
|
238
|
+
const bytes = reuse ? raw : Buffer.from(JSON.stringify({ ...body, model }));
|
|
239
|
+
try {
|
|
240
|
+
result = await pool.run({ body: bytes, format, model }, { ...affinityOf(context), signal: context.signal, transfer: !reuse });
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (error.code !== "PXPIPE_BUSY") throw error;
|
|
243
|
+
// Availability over savings: forward without pxpipe instead of a 503 the client retries at once.
|
|
244
|
+
stages.push(skippedPxpipe(error.reason));
|
|
245
|
+
}
|
|
246
|
+
} else if (px) {
|
|
247
|
+
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
248
|
+
}
|
|
249
|
+
if (result) {
|
|
204
250
|
pxpipeTimings = Object.fromEntries(Object.entries(result.timings).map(([key, value]) => [key, Math.round(value * 10) / 10]));
|
|
205
251
|
stages.push(result.stage);
|
|
206
252
|
if (result.stage.applied) {
|
|
@@ -211,8 +257,6 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
211
257
|
else { for (const key of Object.keys(body)) delete body[key]; Object.assign(body, transformed); }
|
|
212
258
|
changed = true;
|
|
213
259
|
}
|
|
214
|
-
} else if (px) {
|
|
215
|
-
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
216
260
|
}
|
|
217
261
|
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
218
262
|
report(false);
|
|
@@ -233,7 +277,17 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
233
277
|
}
|
|
234
278
|
return;
|
|
235
279
|
}
|
|
236
|
-
|
|
280
|
+
let raw = context.body;
|
|
281
|
+
if (encoding !== "identity") {
|
|
282
|
+
try { raw = await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes }); }
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error.code !== "ERR_BUFFER_TOO_LARGE") throw error;
|
|
285
|
+
// Too large to inspect: forward the compressed bytes unchanged instead of failing the request.
|
|
286
|
+
console.warn(`[aih preset] Skipped presets: decompressed ${encoding} body exceeds maxBodyBytes`);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (config.preset === "pxpipe" && skipBeforeParse(raw, context, started)) return;
|
|
237
291
|
const body = await transform(raw, context, false, started);
|
|
238
292
|
if (body !== raw) {
|
|
239
293
|
context.body = body;
|
package/src/pxpipe-pool.js
CHANGED
|
@@ -1,12 +1,40 @@
|
|
|
1
1
|
import { Worker } from "node:worker_threads";
|
|
2
2
|
import { performance } from "node:perf_hooks";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// Sized from field data: ~50 MB screenshot-heavy bodies take 20-40 s of worker CPU each.
|
|
5
|
+
export const PXPIPE_POOL_DEFAULTS = Object.freeze({
|
|
6
|
+
lanes: 2, maxQueuedPerLane: 4, maxQueueWaitMs: 10000, abandonedJobMs: 120000, affinityEntries: 512,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
/** Capacity rejection: callers forward the request without pxpipe instead of failing it. */
|
|
10
|
+
const busy = reason => Object.assign(new Error(reason === "queue_timeout" ? "pxpipe queue wait exceeded" : "pxpipe queue is full"),
|
|
11
|
+
{ code: "PXPIPE_BUSY", reason, statusCode: 503 });
|
|
12
|
+
|
|
13
|
+
export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = new URL("./pxpipe-thread.js", import.meta.url), options = {}) {
|
|
14
|
+
const { lanes, maxQueuedPerLane, maxQueueWaitMs, abandonedJobMs, affinityEntries } = { ...PXPIPE_POOL_DEFAULTS, ...options };
|
|
15
|
+
// Memory guard only: waiting time is bounded by maxQueueWaitMs, not by the size of one request.
|
|
16
|
+
const maxQueuedBytes = options.maxQueuedBytes ?? 4 * maxBodyBytes;
|
|
5
17
|
// The standalone CLI embeds a separate bundle: runtime relative files do not exist there.
|
|
6
18
|
if (typeof AIH_PXPIPE_THREAD_SOURCE !== "undefined") workerUrl = new URL(`data:text/javascript,${encodeURIComponent(AIH_PXPIPE_THREAD_SOURCE)}`);
|
|
7
|
-
const slots = Array.from({ length:
|
|
19
|
+
const slots = Array.from({ length: lanes }, () => ({ worker: null, ready: false, job: null, queue: [] }));
|
|
20
|
+
const affinity = new Map();
|
|
8
21
|
let closed = false, sequence = 0, queuedBytes = 0;
|
|
9
22
|
const pendingTerminations = new Set();
|
|
23
|
+
const load = slot => slot.queue.length + Boolean(slot.job);
|
|
24
|
+
// Known threads keep their lane (warm caches). A new thread prefers its idle parent lane, else the least loaded.
|
|
25
|
+
const pick = (key, parent) => {
|
|
26
|
+
const known = key === undefined ? undefined : affinity.get(key);
|
|
27
|
+
if (known) return known;
|
|
28
|
+
const parentSlot = parent === undefined ? undefined : affinity.get(parent);
|
|
29
|
+
return parentSlot && !load(parentSlot) ? parentSlot : slots.reduce((best, slot) => load(slot) < load(best) ? slot : best);
|
|
30
|
+
};
|
|
31
|
+
const remember = (key, slot) => {
|
|
32
|
+
if (key === undefined) return;
|
|
33
|
+
affinity.delete(key);
|
|
34
|
+
affinity.set(key, slot);
|
|
35
|
+
if (affinity.size > affinityEntries) affinity.delete(affinity.keys().next().value);
|
|
36
|
+
};
|
|
37
|
+
const full = (slot, bytes) => slot.queue.length >= maxQueuedPerLane || queuedBytes + bytes > maxQueuedBytes;
|
|
10
38
|
const terminate = slot => {
|
|
11
39
|
const worker = slot.worker;
|
|
12
40
|
slot.worker = null;
|
|
@@ -17,6 +45,9 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
17
45
|
termination.then(() => pendingTerminations.delete(termination), () => pendingTerminations.delete(termination));
|
|
18
46
|
};
|
|
19
47
|
const settle = (job, error, result) => {
|
|
48
|
+
clearTimeout(job.timer);
|
|
49
|
+
if (job.settled) return; // abandoned jobs were already rejected
|
|
50
|
+
job.settled = true;
|
|
20
51
|
job.signal?.removeEventListener("abort", job.abort);
|
|
21
52
|
if (error) job.reject(error); else job.resolve(result);
|
|
22
53
|
};
|
|
@@ -27,11 +58,15 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
27
58
|
}
|
|
28
59
|
if (!slot.ready) return;
|
|
29
60
|
const job = slot.queue.shift();
|
|
61
|
+
clearTimeout(job.timer);
|
|
30
62
|
queuedBytes -= job.bytes;
|
|
31
63
|
slot.job = job;
|
|
32
64
|
job.queueMs = performance.now() - job.queuedAt;
|
|
33
65
|
slot.worker.ref();
|
|
34
|
-
|
|
66
|
+
const body = job.input.body;
|
|
67
|
+
// Move a private copy instead of cloning it; a caller-owned buffer must stay readable.
|
|
68
|
+
const transfer = job.transfer && body.byteOffset === 0 && body.byteLength === body.buffer.byteLength ? [body.buffer] : [];
|
|
69
|
+
try { slot.worker.postMessage({ ...job.input, id: job.id }, transfer); }
|
|
35
70
|
catch (error) { fail(slot, error); }
|
|
36
71
|
}
|
|
37
72
|
function fail(slot, error) {
|
|
@@ -49,6 +84,7 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
49
84
|
const job = slot.job;
|
|
50
85
|
if (!job || result.id !== job.id) return fail(slot, new Error("Unexpected pxpipe worker response"));
|
|
51
86
|
slot.job = null;
|
|
87
|
+
clearTimeout(job.watchdog);
|
|
52
88
|
worker.unref();
|
|
53
89
|
if (result.error) settle(job, new Error(result.error));
|
|
54
90
|
else settle(job, null, { ...result, timings: { ...result.timings, pxpipeQueueMs: job.queueMs } });
|
|
@@ -58,23 +94,41 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
58
94
|
worker.on("exit", code => { if (slot.worker === worker) fail(slot, new Error(`pxpipe worker exited (${code})`)); });
|
|
59
95
|
}
|
|
60
96
|
return {
|
|
61
|
-
run(
|
|
97
|
+
/** True when run() would reject for capacity; lets callers skip parsing a body pxpipe cannot take. */
|
|
98
|
+
full({ threadId, sessionId } = {}, bytes = 0) {
|
|
99
|
+
return full(pick(threadId || sessionId, sessionId), bytes);
|
|
100
|
+
},
|
|
101
|
+
run(input, { threadId, sessionId, signal, transfer = false } = {}) {
|
|
62
102
|
if (closed) return Promise.reject(new Error("pxpipe pool is closed"));
|
|
63
103
|
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const slot = sessionId ? slots[hash % slots.length]
|
|
70
|
-
: slots.reduce((best, current) => current.queue.length + Boolean(current.job) < best.queue.length + Boolean(best.job) ? current : best);
|
|
104
|
+
// Forked subagents share the parent's session_id: the thread is the affinity unit.
|
|
105
|
+
const key = threadId || sessionId;
|
|
106
|
+
const slot = pick(key, sessionId);
|
|
107
|
+
if (full(slot, input.body.byteLength)) return Promise.reject(busy("queue_full"));
|
|
108
|
+
remember(key, slot);
|
|
71
109
|
return new Promise((resolve, reject) => {
|
|
72
|
-
const job = { id: ++sequence, input, resolve, reject, signal, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
110
|
+
const job = { id: ++sequence, input, resolve, reject, signal, transfer, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
111
|
+
job.timer = setTimeout(() => {
|
|
112
|
+
const index = slot.queue.indexOf(job);
|
|
113
|
+
if (index < 0) return;
|
|
114
|
+
slot.queue.splice(index, 1);
|
|
115
|
+
queuedBytes -= job.bytes;
|
|
116
|
+
settle(job, busy("queue_timeout"));
|
|
117
|
+
}, maxQueueWaitMs);
|
|
118
|
+
job.timer.unref?.();
|
|
73
119
|
job.abort = () => {
|
|
74
|
-
if (slot.job === job) {
|
|
75
|
-
|
|
120
|
+
if (slot.job === job) {
|
|
121
|
+
// ponytail: the CPU transform cannot be interrupted; keep the warm worker and drop its result.
|
|
122
|
+
// The watchdog still replaces a worker stuck on an abandoned job.
|
|
123
|
+
job.watchdog = setTimeout(() => { if (slot.job === job) { slot.job = null; terminate(slot); dispatch(slot); } }, abandonedJobMs);
|
|
124
|
+
job.watchdog.unref?.();
|
|
125
|
+
} else {
|
|
126
|
+
const index = slot.queue.indexOf(job);
|
|
127
|
+
if (index < 0) return;
|
|
128
|
+
slot.queue.splice(index, 1);
|
|
129
|
+
queuedBytes -= job.bytes;
|
|
130
|
+
}
|
|
76
131
|
settle(job, signal.reason);
|
|
77
|
-
dispatch(slot);
|
|
78
132
|
};
|
|
79
133
|
signal?.addEventListener("abort", job.abort, { once: true });
|
|
80
134
|
slot.queue.push(job);
|
package/src/tui-proxy-setup.js
CHANGED
|
@@ -14,8 +14,8 @@ const STARTUP_FIELD = { key: "startServices", group: "Startup", label: "Services
|
|
|
14
14
|
|
|
15
15
|
/** Shown only when Hindsight is selected for start/up. "config" maps to the saved settings. */
|
|
16
16
|
export const HINDSIGHT_FIELDS = Object.freeze([
|
|
17
|
-
{ key: "hindsightContainer", config: "containerName", group: "Hindsight", label: "Hindsight container name", help: "Docker container started/stopped by aih. An existing container with this name is reused as is; the settings below apply only to containers aih creates." },
|
|
18
|
-
{ key: "hindsightImage", config: "image", group: "Hindsight", label: "Docker image", help: "Default ghcr.io/vectorize-io/hindsight:latest. Pin a
|
|
17
|
+
{ key: "hindsightContainer", config: "containerName", group: "Hindsight", label: "Hindsight container name", help: "Docker container started/stopped by aih. An existing container with this name is reused as is; the settings below apply only to containers aih creates or adopts (u on hindsight in the dashboard imports an existing container's settings)." },
|
|
18
|
+
{ key: "hindsightImage", config: "image", group: "Hindsight", label: "Docker image", help: "Default ghcr.io/vectorize-io/hindsight:latest. Pin a version (e.g. :1.2.0) for repeatable installs: update (u) moves it to the latest release." },
|
|
19
19
|
{ key: "hindsightApiPort", config: "apiPort", group: "Hindsight", label: "API port", help: "Loopback port for the Hindsight API and its /health check. Default 8888." },
|
|
20
20
|
{ key: "hindsightUiPort", config: "uiPort", group: "Hindsight", label: "Web UI port", help: "Loopback port of the Hindsight control plane, opened with o in the dashboard. Default 9999." },
|
|
21
21
|
{ key: "hindsightVolume", config: "volume", group: "Hindsight", label: "Data volume", help: "Docker volume holding the memory database (/home/hindsight/.pg0). Kept when the container is recreated or updated." },
|
|
@@ -216,7 +216,7 @@ export class ProxySetupWizard {
|
|
|
216
216
|
const after = this.draft[f.key];
|
|
217
217
|
return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || "(none)"}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
|
|
218
218
|
}));
|
|
219
|
-
body.push(...wrap("Hindsight: settings are saved; apply recreates a running container created by aih (data volume kept). Other containers are left unchanged."));
|
|
219
|
+
body.push(...wrap("Hindsight: settings are saved; apply recreates a running container created by aih (data volume kept). Other containers are left unchanged until adopted (u on the dashboard)."));
|
|
220
220
|
}
|
|
221
221
|
body.push(...wrap(this.running ? "WARNING: apply now restarts the proxy and interrupts active requests/streams." : "Apply now starts the proxy. Save only leaves it stopped."));
|
|
222
222
|
body.push(...this.checks.flatMap(wrap));
|
package/src/tui.js
CHANGED
|
@@ -685,6 +685,9 @@ export class Dashboard {
|
|
|
685
685
|
return;
|
|
686
686
|
}
|
|
687
687
|
|
|
688
|
+
// Adopting a container needs a second, consecutive u on the same service.
|
|
689
|
+
const adopt = key === "u" && this.adoptPending === this.currentService()?.id;
|
|
690
|
+
this.adoptPending = null;
|
|
688
691
|
switch (key) {
|
|
689
692
|
case "c":
|
|
690
693
|
if (this.busy) return;
|
|
@@ -717,7 +720,9 @@ export class Dashboard {
|
|
|
717
720
|
return this.runAction("Update", async svc => {
|
|
718
721
|
this.invalidateVersions();
|
|
719
722
|
try {
|
|
720
|
-
|
|
723
|
+
const result = await manager.updateService(svc.id, { adopt });
|
|
724
|
+
if (result.adoptable) this.adoptPending = svc.id;
|
|
725
|
+
return result;
|
|
721
726
|
} finally {
|
|
722
727
|
// Drop pre-update and mid-update checks even if installation failed.
|
|
723
728
|
this.invalidateVersions();
|