@wirecat/cli-core 0.625.0 → 0.627.0
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 +38 -0
- package/dist/cli/ai-model-command.d.ts +14 -0
- package/dist/cli/ai-model-command.js +175 -0
- package/dist/cli/command-server-entry.js +48 -34
- package/dist/cli/command-server-request.d.ts +16 -0
- package/dist/cli/command-server-request.js +17 -0
- package/dist/cli/command-server.d.ts +15 -7
- package/dist/cli/command-server.js +112 -36
- package/dist/cli/context.js +4 -0
- package/dist/cli/entry.d.ts +2 -0
- package/dist/cli/entry.js +1 -0
- package/dist/cli/model-catalogue-command.js +2 -0
- package/dist/cli/program.js +4 -3
- package/dist/cli/search-harder-consents-command.js +10 -1
- package/dist/documents.d.ts +2 -0
- package/dist/documents.js +2 -0
- package/dist/errors/reasons.js +6 -0
- package/dist/models/ai.d.ts +75 -0
- package/dist/models/ai.js +196 -0
- package/dist/models/index.js +6 -1
- package/dist/runs/scope.d.ts +2 -0
- package/dist/runs/scope.js +21 -4
- package/dist/store/sqlite/agent-actions.d.ts +1 -0
- package/dist/store/sqlite/agent-actions.js +3 -3
- package/dist/store/sqlite/facts.d.ts +2 -0
- package/dist/store/sqlite/facts.js +2 -2
- package/dist/store/sqlite/memories.d.ts +2 -0
- package/dist/store/sqlite/memories.js +2 -2
- package/dist/store/sqlite/proposed-actions.d.ts +2 -0
- package/dist/store/sqlite/proposed-actions.js +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,44 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.627.0 — 10.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`commands --serve` runs up to 8 requests at once** ([protocol](docs/REFERENCE.md#the-command-server)). The
|
|
13
|
+
ready line says how many (`"concurrent":8`); the protocol stays 1, so a client that sends one request at a time
|
|
14
|
+
works as before. Each request keeps its own output, stdin, exit code and run, and opens the store on its own
|
|
15
|
+
connection; a `store` command runs alone. WireCat Desktop's Memory page sends 7 reads together, and today a pool of
|
|
16
|
+
2 servers starts a fresh process for the other 5. `EntryContext.setExitCode(code)` sets a request's exit code in a
|
|
17
|
+
CLI with its own program; a direct `process.exitCode` write is one value for the whole process.
|
|
18
|
+
- **`memories.list`, `facts.list`, `proposedActions.list` and `agentActions.list` take an `offset`.** A caller pages
|
|
19
|
+
past the 500-row cap: `{ limit: 500, offset: 500 }` gives the next 500 in the same order, newest first with ties by
|
|
20
|
+
id, so no row shows twice and none is left out. memo's `--page` reads through it, so WireCat Desktop can show more
|
|
21
|
+
than 500 memories, facts or actions.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **`models search-consents set` names the cost of the chosen model.** The consent text said "with claude-haiku-5-5
|
|
26
|
+
one costs about $0.0003" whatever model was chosen. It now prices one search with the chosen model (about $0.0005
|
|
27
|
+
with gpt-4o-mini), and says the cost is unknown for a model or address with no known price.
|
|
28
|
+
|
|
29
|
+
## 0.626.0 — 10.11.2026
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- **One AI model for every WireCat tool, `models ai show|set|off|forget|check`** (memo). The owner picks Anthropic,
|
|
34
|
+
OpenAI or a service that works like it (OpenRouter and others, through `--base-url`), or Ollama on this computer
|
|
35
|
+
(beta). The choice lives in the `ai` section of `~/.config/WireCat/config.json`. The key is read from stdin, kept
|
|
36
|
+
in the system keyring under service `WireCat`, account `ai:<origin>`, and sent only to that address. The address
|
|
37
|
+
must be https, or http only on this computer. `set`, `off`, `forget` and `check` refuse an agent's shell unless
|
|
38
|
+
`--from-app`, and stay out of MCP. `check` sends one short paid request and names what is wrong: a refused key,
|
|
39
|
+
no credit (HTTP 402 only: OpenAI's empty-balance 429 still reads as a rate limit), an unknown model, an
|
|
40
|
+
unreachable address or the provider's own failure.
|
|
41
|
+
- **Images can be read by that model.** `models ai set … --images` records that the owner agreed images go to this
|
|
42
|
+
address and model. Any later change of either closes it, and `--no-images` withdraws it. `aiImageReader` and `ocrImage` are exported from
|
|
43
|
+
`@wirecat/cli-core/documents` for `memo sources add`.
|
|
44
|
+
- **A failed model call carries its HTTP status** in `details.status`, never the provider's text.
|
|
45
|
+
|
|
8
46
|
## 0.625.0 — 09.11.2026
|
|
9
47
|
|
|
10
48
|
### Added
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type KeyringStore } from "@wirecat/cli-base";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import type { AppIdentity } from "../ports/app.js";
|
|
4
|
+
import { type Body } from "./envelope.js";
|
|
5
|
+
export interface AiModelCommandOptions {
|
|
6
|
+
env: () => NodeJS.ProcessEnv;
|
|
7
|
+
keyring?: KeyringStore;
|
|
8
|
+
stdin?: () => NodeJS.ReadableStream | undefined;
|
|
9
|
+
fetch?: typeof globalThis.fetch;
|
|
10
|
+
output: (answer: Body, command: Command) => void;
|
|
11
|
+
diagnostic: (line: string) => void;
|
|
12
|
+
}
|
|
13
|
+
/** `models ai`: the one model every WireCat tool may use in place of an agent, kept in the shared config. */
|
|
14
|
+
export declare const aiModelCommand: (app: AppIdentity, options: AiModelCommandOptions) => Command;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { annotate } from "@wirecat/cli-base/commands";
|
|
3
|
+
import { Command } from "commander";
|
|
4
|
+
import { AI_PROVIDERS, aiBaseUrl, aiImagesAllowed, aiKeys, aiNeedsKey, aiOrigin, aiSettingOf, aiSettingPath, checkAi, readAiSetting, writeAiSetting, } from "../models/ai.js";
|
|
5
|
+
import { agentOf } from "../runs/run-context.js";
|
|
6
|
+
import { readSecret } from "../terminal/prompt.js";
|
|
7
|
+
import { environmentOf } from "./context.js";
|
|
8
|
+
import { FETCH, grantsAuthority, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS } from "./effects.js";
|
|
9
|
+
import { itemOf } from "./envelope.js";
|
|
10
|
+
const imagesNote = (setting) => `images you add to memory are sent to ${new URL(aiBaseUrl(setting)).host} to be read${setting.provider === "ollama" ? " (on this computer)" : ", so they leave this computer"}`;
|
|
11
|
+
const view = (app, options, setting) => {
|
|
12
|
+
if (!setting)
|
|
13
|
+
return {
|
|
14
|
+
provider: null,
|
|
15
|
+
model: null,
|
|
16
|
+
base_url: null,
|
|
17
|
+
origin: null,
|
|
18
|
+
beta: false,
|
|
19
|
+
images: false,
|
|
20
|
+
key: { stored: false, source: null },
|
|
21
|
+
};
|
|
22
|
+
const key = aiNeedsKey(setting) ? aiKeys(app, options.env(), options.keyring).read(aiOrigin(setting)) : undefined;
|
|
23
|
+
return {
|
|
24
|
+
provider: setting.provider,
|
|
25
|
+
model: setting.model,
|
|
26
|
+
base_url: aiBaseUrl(setting),
|
|
27
|
+
origin: aiOrigin(setting),
|
|
28
|
+
beta: setting.provider === "ollama",
|
|
29
|
+
images: aiImagesAllowed(setting),
|
|
30
|
+
key: { stored: key !== undefined, source: key?.source ?? null },
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
// An agent that pointed the model elsewhere, or spent the owner's credit, would act for the owner; only they may.
|
|
34
|
+
// --from-app is Desktop saying the owner clicked; like the other owner-only guards, it stops mistakes, not attacks.
|
|
35
|
+
const ownerOnly = (command, env, what) => {
|
|
36
|
+
if ((environmentOf(command).agent || agentOf(env)) && !command.opts().fromApp)
|
|
37
|
+
throw new CliError("permission_error", `only the owner runs models ai ${what}, not an agent`, {
|
|
38
|
+
reason: "ai.owner-only",
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
// A broken or newer section must not stop the owner from replacing or clearing it.
|
|
42
|
+
const previous = (path) => {
|
|
43
|
+
try {
|
|
44
|
+
return readAiSetting(path);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/** `models ai`: the one model every WireCat tool may use in place of an agent, kept in the shared config. */
|
|
51
|
+
export const aiModelCommand = (app, options) => {
|
|
52
|
+
const ai = annotate(new Command("ai"), { effects: NO_EFFECTS }).description("the AI model WireCat may use instead of your agent: provider, model and its key");
|
|
53
|
+
annotate(ai.command("show"), {
|
|
54
|
+
effects: LOCAL_READ,
|
|
55
|
+
output: { entity: "ai_model" },
|
|
56
|
+
examples: [`${app.command} models ai show`],
|
|
57
|
+
})
|
|
58
|
+
.description("the chosen model, whether a key is stored for its address, and whether images may go to it")
|
|
59
|
+
.action(function () {
|
|
60
|
+
options.output(itemOf(view(app, options, readAiSetting(aiSettingPath(options.env())))), this);
|
|
61
|
+
});
|
|
62
|
+
grantsAuthority(annotate(ai.command("set"), {
|
|
63
|
+
effects: LOCAL_WRITE,
|
|
64
|
+
mcp: false,
|
|
65
|
+
output: { entity: "ai_model", view: "chosen" },
|
|
66
|
+
examples: [
|
|
67
|
+
`${app.command} models ai set anthropic --model claude-haiku-4-5 --key-stdin < key.txt`,
|
|
68
|
+
`${app.command} models ai set openai --model openai/gpt-4o-mini --base-url https://openrouter.ai/api/v1 --key-stdin`,
|
|
69
|
+
`${app.command} models ai set ollama --model llama3.2-vision`,
|
|
70
|
+
],
|
|
71
|
+
}))
|
|
72
|
+
.description("choose the model: anthropic, openai (or any service that works like it, with --base-url) or ollama (beta)")
|
|
73
|
+
.argument("<provider>", AI_PROVIDERS.join(", "))
|
|
74
|
+
.requiredOption("--model <model>", "the model's name as the provider writes it")
|
|
75
|
+
.option("--base-url <url>", "the service's address; https, or http only on this computer")
|
|
76
|
+
.option("--key-stdin", "read the API key from stdin and keep it for this address only")
|
|
77
|
+
.option("--images", "let images you add to memory go to this model to be read; they leave this computer")
|
|
78
|
+
.option("--no-images", "stop sending images to it; without either flag an earlier yes for this model stays")
|
|
79
|
+
.option("--from-app", "you did this in WireCat Desktop")
|
|
80
|
+
.action(async function (provider, given) {
|
|
81
|
+
const env = options.env();
|
|
82
|
+
ownerOnly(this, env, "set");
|
|
83
|
+
const path = aiSettingPath(env);
|
|
84
|
+
const before = previous(path);
|
|
85
|
+
const setting = aiSettingOf({
|
|
86
|
+
provider,
|
|
87
|
+
model: given.model,
|
|
88
|
+
baseUrl: given.baseUrl,
|
|
89
|
+
images: given.images,
|
|
90
|
+
before,
|
|
91
|
+
});
|
|
92
|
+
if (given.keyStdin) {
|
|
93
|
+
if (!aiNeedsKey(setting))
|
|
94
|
+
throw new CliError("validation_error", "Ollama on this computer takes no key");
|
|
95
|
+
const input = options.stdin?.();
|
|
96
|
+
const secret = (await readSecret("API key: ", input ? { input } : {})).trim();
|
|
97
|
+
if (!secret)
|
|
98
|
+
throw new CliError("validation_error", "no key was given; nothing was changed");
|
|
99
|
+
aiKeys(app, env, options.keyring).write(aiOrigin(setting), secret);
|
|
100
|
+
}
|
|
101
|
+
writeAiSetting(path, setting);
|
|
102
|
+
if (setting.images)
|
|
103
|
+
options.diagnostic(imagesNote(setting));
|
|
104
|
+
const changed = JSON.stringify(before === undefined ? null : { ...before, images: before.images !== undefined }) !==
|
|
105
|
+
JSON.stringify({ ...setting, images: setting.images !== undefined });
|
|
106
|
+
options.output(itemOf({ ...view(app, options, setting), changed }), this);
|
|
107
|
+
});
|
|
108
|
+
grantsAuthority(annotate(ai.command("off"), {
|
|
109
|
+
effects: LOCAL_WRITE,
|
|
110
|
+
mcp: false,
|
|
111
|
+
output: { entity: "ai_model", view: "off" },
|
|
112
|
+
examples: [`${app.command} models ai off`],
|
|
113
|
+
}))
|
|
114
|
+
.description("stop using a model; its key stays until models ai forget")
|
|
115
|
+
.option("--from-app", "you did this in WireCat Desktop")
|
|
116
|
+
.action(function () {
|
|
117
|
+
const env = options.env();
|
|
118
|
+
ownerOnly(this, env, "off");
|
|
119
|
+
const path = aiSettingPath(env);
|
|
120
|
+
const before = previous(path);
|
|
121
|
+
writeAiSetting(path, undefined);
|
|
122
|
+
options.output(itemOf({ changed: before !== undefined, key_kept: true }), this);
|
|
123
|
+
});
|
|
124
|
+
grantsAuthority(annotate(ai.command("forget"), {
|
|
125
|
+
effects: LOCAL_WRITE,
|
|
126
|
+
mcp: false,
|
|
127
|
+
output: { entity: "ai_model", view: "key-removed" },
|
|
128
|
+
examples: [`${app.command} models ai forget https://api.anthropic.com`],
|
|
129
|
+
}))
|
|
130
|
+
.description("remove the key stored for an address")
|
|
131
|
+
.argument("[origin]", "the address, for example https://openrouter.ai; the chosen model's when absent")
|
|
132
|
+
.option("--from-app", "you did this in WireCat Desktop")
|
|
133
|
+
.action(function (given) {
|
|
134
|
+
const env = options.env();
|
|
135
|
+
ownerOnly(this, env, "forget");
|
|
136
|
+
const setting = given ? undefined : previous(aiSettingPath(env));
|
|
137
|
+
let origin = setting ? aiOrigin(setting) : "";
|
|
138
|
+
if (given) {
|
|
139
|
+
const url = URL.canParse(given) ? new URL(given) : undefined;
|
|
140
|
+
if (!url || !["https:", "http:"].includes(url.protocol))
|
|
141
|
+
throw new CliError("validation_error", "give the address as https://host");
|
|
142
|
+
origin = url.origin;
|
|
143
|
+
}
|
|
144
|
+
if (!origin)
|
|
145
|
+
throw new CliError("validation_error", "no model is chosen; name the address");
|
|
146
|
+
const keys = aiKeys(app, env, options.keyring);
|
|
147
|
+
const removed = keys.remove(origin);
|
|
148
|
+
// An older per-tool key or OPENAI_API_KEY/ANTHROPIC_API_KEY still answers for the official addresses.
|
|
149
|
+
const still = keys.read(origin)?.source ?? null;
|
|
150
|
+
if (still)
|
|
151
|
+
options.diagnostic(`a key for ${origin} is still found in ${still}; remove it there too`);
|
|
152
|
+
options.output(itemOf({ origin, removed: removed.length > 0, still_found: still }), this);
|
|
153
|
+
});
|
|
154
|
+
annotate(ai.command("check"), {
|
|
155
|
+
effects: FETCH,
|
|
156
|
+
mcp: false,
|
|
157
|
+
output: { entity: "ai_model_check" },
|
|
158
|
+
examples: [`${app.command} models ai check`],
|
|
159
|
+
})
|
|
160
|
+
.description("send one short request (billed by the provider, usually under a cent) and say what is wrong")
|
|
161
|
+
.option("--from-app", "you did this in WireCat Desktop")
|
|
162
|
+
.action(async function () {
|
|
163
|
+
const env = options.env();
|
|
164
|
+
ownerOnly(this, env, "check");
|
|
165
|
+
const setting = readAiSetting(aiSettingPath(env));
|
|
166
|
+
const result = await checkAi({ app, env, keyring: options.keyring, fetch: options.fetch });
|
|
167
|
+
options.output(itemOf({
|
|
168
|
+
...result,
|
|
169
|
+
provider: setting?.provider ?? null,
|
|
170
|
+
model: setting?.model ?? null,
|
|
171
|
+
origin: setting ? aiOrigin(setting) : null,
|
|
172
|
+
}), this);
|
|
173
|
+
});
|
|
174
|
+
return ai;
|
|
175
|
+
};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { PassThrough } from "node:stream";
|
|
2
2
|
import { CliError, catchCrashes } from "@wirecat/cli-base";
|
|
3
|
-
import {
|
|
3
|
+
import { asOwnProcess } from "../runs/scope.js";
|
|
4
4
|
import { ensureSqlite } from "../sqlite-runtime.js";
|
|
5
|
-
import {
|
|
5
|
+
import { COMMAND_SERVER_CONCURRENT, enterCommandServer, serveCommands } from "./command-server.js";
|
|
6
|
+
import { commandServerRequest, exitCodeSet, inCommandServerRequest, } from "./command-server-request.js";
|
|
6
7
|
/**
|
|
7
8
|
* Every write to the process's stream goes to `sink()`. The stream's `write` is replaced, not the stream: the global
|
|
8
9
|
* console keeps the stream it first wrote to, and `complete` prints through it.
|
|
@@ -28,7 +29,23 @@ const closedStdin = () => {
|
|
|
28
29
|
stdin.end();
|
|
29
30
|
return stdin;
|
|
30
31
|
};
|
|
31
|
-
|
|
32
|
+
// Each request reads its own stream: commands keep per-stream state, such as the input policy, under it.
|
|
33
|
+
const useStdin = (outside) => Object.defineProperty(process, "stdin", {
|
|
34
|
+
get: () => commandServerRequest()?.stdin ?? outside,
|
|
35
|
+
configurable: true,
|
|
36
|
+
enumerable: true,
|
|
37
|
+
});
|
|
38
|
+
// Each run adds its own signal and stdout `error` listeners, so a full server passes Node's warning at 10.
|
|
39
|
+
const roomFor = (runs) => {
|
|
40
|
+
const emitters = [process, process.stdout, process.stderr];
|
|
41
|
+
const before = emitters.map((emitter) => emitter.getMaxListeners());
|
|
42
|
+
for (const emitter of emitters)
|
|
43
|
+
emitter.setMaxListeners(emitter.getMaxListeners() + 2 * runs);
|
|
44
|
+
return () => {
|
|
45
|
+
for (const [at, emitter] of emitters.entries())
|
|
46
|
+
emitter.setMaxListeners(before[at]);
|
|
47
|
+
};
|
|
48
|
+
};
|
|
32
49
|
/**
|
|
33
50
|
* `startCli` for `<cli> commands --serve`: each request runs the CLI's own `run` as a spawned process would, and its
|
|
34
51
|
* output, which the process's streams would have carried, comes back in the answer. Between requests nothing reaches
|
|
@@ -48,54 +65,49 @@ export const serveEntry = async (entry, io, { firstRunAt, commanderExit }) => {
|
|
|
48
65
|
const toStderr = (chunk) => {
|
|
49
66
|
ownStderr(chunk);
|
|
50
67
|
};
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
68
|
+
const sink = (pick) => () => {
|
|
69
|
+
const request = commandServerRequest();
|
|
70
|
+
return request ? (chunk) => pick(request).push(chunk) : toStderr;
|
|
71
|
+
};
|
|
72
|
+
const unrouteOut = route(process.stdout, sink((request) => request.stdout));
|
|
73
|
+
const unrouteErr = route(process.stderr, sink((request) => request.stderr));
|
|
54
74
|
const stdin = Object.getOwnPropertyDescriptor(process, "stdin");
|
|
55
75
|
const requests = io.stdin;
|
|
56
76
|
useStdin(closedStdin());
|
|
77
|
+
const unroom = roomFor(COMMAND_SERVER_CONCURRENT);
|
|
57
78
|
io.signals.on("SIGINT", stop).on("SIGTERM", stop);
|
|
58
79
|
io.stdout.on("error", stop);
|
|
59
|
-
const run = async (argv) => {
|
|
60
|
-
const
|
|
61
|
-
const
|
|
62
|
-
current = { stdout, stderr };
|
|
63
|
-
process.exitCode = undefined;
|
|
64
|
-
// Lines written outside a run name the process's run; each request is a process of its own.
|
|
65
|
-
useAsProcessRun(undefined);
|
|
66
|
-
const input = closedStdin();
|
|
67
|
-
useStdin(input);
|
|
68
|
-
const requestIo = { ...io, argv: [...io.argv.slice(0, 2), ...argv], stdin: input };
|
|
80
|
+
const run = async (argv, alone) => {
|
|
81
|
+
const request = { stdout: [], stderr: [], stdin: closedStdin(), alone };
|
|
82
|
+
const requestIo = { ...io, argv: [...io.argv.slice(0, 2), ...argv], stdin: request.stdin };
|
|
69
83
|
const context = {
|
|
70
84
|
args: argv,
|
|
71
85
|
env: io.env,
|
|
72
86
|
tty: false,
|
|
73
87
|
signal: stopper.signal,
|
|
74
88
|
atStart: async (command) => {
|
|
75
|
-
|
|
89
|
+
await enterCommandServer(command, entry.app.command);
|
|
76
90
|
await firstRunAt(entry, requestIo, () => true)(command);
|
|
77
91
|
},
|
|
78
92
|
ask: async () => false,
|
|
79
93
|
openBrowser: async () => undefined,
|
|
80
94
|
outputClosed: () => false,
|
|
95
|
+
setExitCode: (code) => {
|
|
96
|
+
request.exitCode = code;
|
|
97
|
+
},
|
|
81
98
|
};
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
finally {
|
|
95
|
-
current = undefined;
|
|
96
|
-
process.exitCode = undefined;
|
|
97
|
-
}
|
|
98
|
-
return { code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") };
|
|
99
|
+
// Lines written outside a run name the process's run; each request is a process of its own.
|
|
100
|
+
const code = await inCommandServerRequest(request, () => asOwnProcess(async () => {
|
|
101
|
+
try {
|
|
102
|
+
const returned = await entry.run(context);
|
|
103
|
+
return typeof returned === "number" ? returned : (exitCodeSet() ?? 0);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
return commanderExit(error) ?? entry.fail(error, context);
|
|
107
|
+
}
|
|
108
|
+
}));
|
|
109
|
+
const text = (chunks) => Buffer.concat(chunks).toString("utf8");
|
|
110
|
+
return { code, stdout: text(request.stdout), stderr: text(request.stderr) };
|
|
99
111
|
};
|
|
100
112
|
try {
|
|
101
113
|
if (entry.sqlite)
|
|
@@ -105,6 +117,7 @@ export const serveEntry = async (entry, io, { firstRunAt, commanderExit }) => {
|
|
|
105
117
|
write: (line) => new Promise((resolve) => (protocol(line) ? resolve() : io.stdout.once("drain", resolve))),
|
|
106
118
|
run,
|
|
107
119
|
cli: entry.app.command,
|
|
120
|
+
concurrent: COMMAND_SERVER_CONCURRENT,
|
|
108
121
|
version: entry.app.version,
|
|
109
122
|
signal: stopper.signal,
|
|
110
123
|
});
|
|
@@ -112,6 +125,7 @@ export const serveEntry = async (entry, io, { firstRunAt, commanderExit }) => {
|
|
|
112
125
|
}
|
|
113
126
|
finally {
|
|
114
127
|
io.signals.off("SIGINT", stop).off("SIGTERM", stop);
|
|
128
|
+
unroom();
|
|
115
129
|
unrouteOut();
|
|
116
130
|
unrouteErr();
|
|
117
131
|
if (stdin)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** What a spawned process would own alone: its output, its stdin and its exit code. */
|
|
2
|
+
export interface CommandServerRequest {
|
|
3
|
+
stdout: Buffer[];
|
|
4
|
+
stderr: Buffer[];
|
|
5
|
+
stdin: NodeJS.ReadableStream;
|
|
6
|
+
exitCode?: number;
|
|
7
|
+
/** Resolves once no other request runs, and keeps new ones waiting until this one ends. */
|
|
8
|
+
alone: () => Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export declare const inCommandServerRequest: <T>(request: CommandServerRequest, work: () => T) => T;
|
|
11
|
+
export declare const commandServerRequest: () => CommandServerRequest | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* The exit code a command set without returning it. In a request, a direct `process.exitCode` write is taken and
|
|
14
|
+
* cleared, since the process's one value is shared by every request in flight; `setExitCode` keeps it per request.
|
|
15
|
+
*/
|
|
16
|
+
export declare const exitCodeSet: () => number | undefined;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
const requests = new AsyncLocalStorage();
|
|
3
|
+
export const inCommandServerRequest = (request, work) => requests.run(request, work);
|
|
4
|
+
export const commandServerRequest = () => requests.getStore();
|
|
5
|
+
/**
|
|
6
|
+
* The exit code a command set without returning it. In a request, a direct `process.exitCode` write is taken and
|
|
7
|
+
* cleared, since the process's one value is shared by every request in flight; `setExitCode` keeps it per request.
|
|
8
|
+
*/
|
|
9
|
+
export const exitCodeSet = () => {
|
|
10
|
+
const request = requests.getStore();
|
|
11
|
+
if (request?.exitCode !== undefined)
|
|
12
|
+
return request.exitCode;
|
|
13
|
+
const direct = process.exitCode === undefined ? undefined : Number(process.exitCode);
|
|
14
|
+
if (request)
|
|
15
|
+
process.exitCode = undefined;
|
|
16
|
+
return direct;
|
|
17
|
+
};
|
|
@@ -2,7 +2,13 @@ import type { Command } from "commander";
|
|
|
2
2
|
export declare const COMMAND_SERVER_PROTOCOL = 1;
|
|
3
3
|
/** An updated tool's old code must not answer for long. */
|
|
4
4
|
export declare const COMMAND_SERVER_IDLE_MS: number;
|
|
5
|
-
|
|
5
|
+
/** Requests one server runs at once; Desktop's Memory page asks for 7 reads together. */
|
|
6
|
+
export declare const COMMAND_SERVER_CONCURRENT = 8;
|
|
7
|
+
/**
|
|
8
|
+
* Refuses inside a request a command that never returns, waits on a person, or reads stdin; a `store` command then
|
|
9
|
+
* waits until it is the only request running.
|
|
10
|
+
*/
|
|
11
|
+
export declare const enterCommandServer: (command: Command, cli: string) => Promise<void>;
|
|
6
12
|
/** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
|
|
7
13
|
export declare const refuseInCommandServer: (command: Command, cli: string) => void;
|
|
8
14
|
export interface CommandAnswer {
|
|
@@ -14,16 +20,18 @@ export interface ServeOptions {
|
|
|
14
20
|
input: NodeJS.ReadableStream;
|
|
15
21
|
/** One protocol line, the newline included; resolves once it may be written again. */
|
|
16
22
|
write: (line: string) => Promise<void>;
|
|
17
|
-
|
|
23
|
+
/** `alone` resolves once no other request runs; new requests wait until this one ends. */
|
|
24
|
+
run: (argv: string[], alone: () => Promise<void>) => Promise<CommandAnswer>;
|
|
18
25
|
cli: string;
|
|
19
26
|
version: string;
|
|
20
27
|
idleMs?: number;
|
|
21
|
-
|
|
28
|
+
concurrent?: number;
|
|
29
|
+
/** Ends the server after the requests under way. */
|
|
22
30
|
signal?: AbortSignal;
|
|
23
31
|
}
|
|
24
32
|
/**
|
|
25
|
-
* Says it is ready, then
|
|
26
|
-
*
|
|
27
|
-
* input ends or nothing came for `idleMs
|
|
33
|
+
* Says it is ready, then runs up to `concurrent` requests at once and answers each as it ends, under its `id`. SQLite
|
|
34
|
+
* keeps the requests' connections apart in one process; a `store` command, which swaps the file, runs alone. Resolves
|
|
35
|
+
* with 0 once the input ends or nothing came for `idleMs`, after the requests under way.
|
|
28
36
|
*/
|
|
29
|
-
export declare const serveCommands: ({ input, write, run, cli, version, idleMs, signal, }: ServeOptions) => Promise<number>;
|
|
37
|
+
export declare const serveCommands: ({ input, write, run, cli, version, idleMs, concurrent, signal, }: ServeOptions) => Promise<number>;
|
|
@@ -1,18 +1,32 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
1
|
import { createInterface } from "node:readline";
|
|
3
2
|
import { CliError, errorObjectOf, renderError } from "@wirecat/cli-base";
|
|
4
3
|
import { metaOf } from "@wirecat/cli-base/commands";
|
|
5
4
|
import { commandPathOf } from "./command-contract.js";
|
|
6
5
|
import { isCommandServer } from "./command-server-argv.js";
|
|
6
|
+
import { commandServerRequest } from "./command-server-request.js";
|
|
7
7
|
import { stdinFieldOf } from "./stdin-field.js";
|
|
8
8
|
export const COMMAND_SERVER_PROTOCOL = 1;
|
|
9
9
|
/** An updated tool's old code must not answer for long. */
|
|
10
10
|
export const COMMAND_SERVER_IDLE_MS = 10 * 60_000;
|
|
11
|
-
|
|
12
|
-
export const
|
|
11
|
+
/** Requests one server runs at once; Desktop's Memory page asks for 7 reads together. */
|
|
12
|
+
export const COMMAND_SERVER_CONCURRENT = 8;
|
|
13
|
+
// They swap or rewrite the store's file, which the connections of the other requests in this process hold open.
|
|
14
|
+
const runsAlone = (command) => commandPathOf(command)[0] === "store";
|
|
15
|
+
/**
|
|
16
|
+
* Refuses inside a request a command that never returns, waits on a person, or reads stdin; a `store` command then
|
|
17
|
+
* waits until it is the only request running.
|
|
18
|
+
*/
|
|
19
|
+
export const enterCommandServer = async (command, cli) => {
|
|
20
|
+
const request = commandServerRequest();
|
|
21
|
+
if (!request)
|
|
22
|
+
return;
|
|
23
|
+
refuseInCommandServer(command, cli);
|
|
24
|
+
if (runsAlone(command))
|
|
25
|
+
await request.alone();
|
|
26
|
+
};
|
|
13
27
|
/** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
|
|
14
28
|
export const refuseInCommandServer = (command, cli) => {
|
|
15
|
-
if (
|
|
29
|
+
if (!commandServerRequest())
|
|
16
30
|
return;
|
|
17
31
|
const typed = [cli, ...commandPathOf(command)].join(" ");
|
|
18
32
|
const { lifetime } = metaOf(command);
|
|
@@ -43,18 +57,24 @@ const requestOf = (line, cli) => {
|
|
|
43
57
|
return { id: known, argv };
|
|
44
58
|
};
|
|
45
59
|
/**
|
|
46
|
-
* Says it is ready, then
|
|
47
|
-
*
|
|
48
|
-
* input ends or nothing came for `idleMs
|
|
60
|
+
* Says it is ready, then runs up to `concurrent` requests at once and answers each as it ends, under its `id`. SQLite
|
|
61
|
+
* keeps the requests' connections apart in one process; a `store` command, which swaps the file, runs alone. Resolves
|
|
62
|
+
* with 0 once the input ends or nothing came for `idleMs`, after the requests under way.
|
|
49
63
|
*/
|
|
50
|
-
export const serveCommands = async ({ input, write, run, cli, version, idleMs = COMMAND_SERVER_IDLE_MS, signal, }) => {
|
|
64
|
+
export const serveCommands = async ({ input, write, run, cli, version, idleMs = COMMAND_SERVER_IDLE_MS, concurrent = COMMAND_SERVER_CONCURRENT, signal, }) => {
|
|
51
65
|
const send = (value) => write(`${JSON.stringify(value)}\n`);
|
|
52
|
-
await send({ ready: true, protocol: COMMAND_SERVER_PROTOCOL, version });
|
|
66
|
+
await send({ ready: true, protocol: COMMAND_SERVER_PROTOCOL, version, concurrent });
|
|
53
67
|
const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
|
|
54
68
|
return new Promise((resolve) => {
|
|
55
|
-
|
|
56
|
-
|
|
69
|
+
const waiting = [];
|
|
70
|
+
// Started and not answered; `running` leaves out a request waiting to run alone, which holds no place.
|
|
71
|
+
let active = 0;
|
|
72
|
+
let running = 0;
|
|
73
|
+
let gated = false;
|
|
74
|
+
let drained;
|
|
75
|
+
let turns = Promise.resolve();
|
|
57
76
|
let timer;
|
|
77
|
+
let ending = false;
|
|
58
78
|
let done = false;
|
|
59
79
|
const finish = () => {
|
|
60
80
|
if (done)
|
|
@@ -64,37 +84,93 @@ export const serveCommands = async ({ input, write, run, cli, version, idleMs =
|
|
|
64
84
|
lines.close();
|
|
65
85
|
resolve(0);
|
|
66
86
|
};
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
87
|
+
const settle = () => {
|
|
88
|
+
if (running === 0 && drained) {
|
|
89
|
+
const go = drained;
|
|
90
|
+
drained = undefined;
|
|
91
|
+
go();
|
|
92
|
+
}
|
|
93
|
+
pump();
|
|
94
|
+
if (active > 0 || waiting.length > 0 || done)
|
|
95
|
+
return;
|
|
96
|
+
if (ending)
|
|
97
|
+
finish();
|
|
98
|
+
else {
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
timer = setTimeout(finish, idleMs);
|
|
101
|
+
}
|
|
70
102
|
};
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
103
|
+
const start = (line) => {
|
|
104
|
+
active += 1;
|
|
105
|
+
running += 1;
|
|
106
|
+
let holdsPlace = true;
|
|
107
|
+
let ended = false;
|
|
108
|
+
let turn;
|
|
109
|
+
let release;
|
|
110
|
+
// A request that ended while it waited (its --timeout, a signal) gives its turn up without taking it.
|
|
111
|
+
const alone = () => {
|
|
112
|
+
if (turn)
|
|
113
|
+
return turn;
|
|
114
|
+
holdsPlace = false;
|
|
115
|
+
running -= 1;
|
|
116
|
+
turn = turns.then(() => new Promise((go) => {
|
|
117
|
+
if (ended)
|
|
118
|
+
return go();
|
|
119
|
+
gated = true;
|
|
120
|
+
drained = () => {
|
|
121
|
+
if (ended)
|
|
122
|
+
gated = false;
|
|
123
|
+
else {
|
|
124
|
+
holdsPlace = true;
|
|
125
|
+
running += 1;
|
|
126
|
+
}
|
|
127
|
+
go();
|
|
128
|
+
};
|
|
129
|
+
settle();
|
|
130
|
+
}));
|
|
131
|
+
turns = turn.then(() => (ended && !holdsPlace ? undefined : new Promise((free) => (release = free))));
|
|
132
|
+
return turn;
|
|
133
|
+
};
|
|
134
|
+
const answer = async () => {
|
|
135
|
+
const request = requestOf(line, cli);
|
|
136
|
+
if ("error" in request)
|
|
137
|
+
return send({ id: request.id, code: 2, stdout: "", stderr: refusal(cli, request.error) });
|
|
138
|
+
const answered = await run(request.argv, alone);
|
|
139
|
+
return send({ id: request.id, ...answered });
|
|
140
|
+
};
|
|
141
|
+
answer()
|
|
142
|
+
.catch(finish)
|
|
143
|
+
.finally(() => {
|
|
144
|
+
ended = true;
|
|
145
|
+
active -= 1;
|
|
146
|
+
if (holdsPlace)
|
|
147
|
+
running -= 1;
|
|
148
|
+
if (release) {
|
|
149
|
+
gated = false;
|
|
150
|
+
release();
|
|
151
|
+
}
|
|
152
|
+
settle();
|
|
153
|
+
});
|
|
154
|
+
};
|
|
155
|
+
const pump = () => {
|
|
156
|
+
while (!done && !gated && running < concurrent && waiting.length > 0)
|
|
157
|
+
start(waiting.shift());
|
|
77
158
|
};
|
|
78
159
|
lines.on("line", (line) => {
|
|
79
|
-
if (done || line.trim() === "")
|
|
160
|
+
if (done || ending || line.trim() === "")
|
|
80
161
|
return;
|
|
81
|
-
waiting += 1;
|
|
82
162
|
clearTimeout(timer);
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
.catch(finish)
|
|
86
|
-
.then(() => {
|
|
87
|
-
waiting -= 1;
|
|
88
|
-
if (waiting === 0 && !done)
|
|
89
|
-
idle();
|
|
90
|
-
});
|
|
91
|
-
});
|
|
92
|
-
lines.on("close", () => {
|
|
93
|
-
queue = queue.then(finish);
|
|
163
|
+
waiting.push(line);
|
|
164
|
+
pump();
|
|
94
165
|
});
|
|
166
|
+
const end = () => {
|
|
167
|
+
ending = true;
|
|
168
|
+
settle();
|
|
169
|
+
};
|
|
170
|
+
lines.on("close", end);
|
|
95
171
|
if (signal?.aborted)
|
|
96
|
-
|
|
97
|
-
signal?.addEventListener("abort",
|
|
98
|
-
|
|
172
|
+
end();
|
|
173
|
+
signal?.addEventListener("abort", end, { once: true });
|
|
174
|
+
settle();
|
|
99
175
|
});
|
|
100
176
|
};
|
package/dist/cli/context.js
CHANGED
|
@@ -6,6 +6,7 @@ import { runBudget } from "../background/budget.js";
|
|
|
6
6
|
import { resolveOutput } from "../output.js";
|
|
7
7
|
import { recorded } from "../runs/recording.js";
|
|
8
8
|
import { currentCaller, keepsSuccess, runContextOf } from "../runs/run-context.js";
|
|
9
|
+
import { commandServerRequest } from "./command-server-request.js";
|
|
9
10
|
import { withDeadline } from "./deadline.js";
|
|
10
11
|
import { withAbort } from "./execution.js";
|
|
11
12
|
import { rootOf } from "./profile.js";
|
|
@@ -27,8 +28,11 @@ export const runBudgetOf = (command, requests) => {
|
|
|
27
28
|
/** A partial answer's exit code, for this run alone. */
|
|
28
29
|
export const setExitCode = (command, code) => {
|
|
29
30
|
const slot = environmentOf(command).exit;
|
|
31
|
+
const request = commandServerRequest();
|
|
30
32
|
if (slot)
|
|
31
33
|
slot.code = code;
|
|
34
|
+
else if (request)
|
|
35
|
+
request.exitCode = code;
|
|
32
36
|
else
|
|
33
37
|
process.exitCode = code;
|
|
34
38
|
};
|