@wirecat/cli-core 0.626.0 → 0.628.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 +37 -0
- package/dist/cli/ai-model-command.js +39 -17
- 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/program.js +4 -3
- package/dist/cli/search-harder-consents-command.js +10 -1
- package/dist/documents.d.ts +1 -1
- package/dist/documents.js +1 -1
- package/dist/errors/reasons.js +5 -1
- package/dist/models/ai.d.ts +18 -2
- package/dist/models/ai.js +18 -4
- 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,43 @@ 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.628.0 — 10.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`aiTextReader` in `@wirecat/cli-core/documents`** sends text to the model chosen with `models ai set`, with the
|
|
13
|
+
key kept for that address. It says `ai.not-set` or `ai.key-missing` when it cannot, and whether the text leaves this
|
|
14
|
+
computer. memo's `ai-model` source reader uses it, so one key and one model serve images and text.
|
|
15
|
+
|
|
16
|
+
### Changed — may break callers
|
|
17
|
+
|
|
18
|
+
- **`models ai` uses the shared command words.** `off` is now `unset` and `forget` is now `remove`. The key is
|
|
19
|
+
read with `--secret-stdin` (was `--key-stdin`). Image consent is `--allow-remote` (was `--images`), given for that
|
|
20
|
+
call's address and model: a `set` without it takes it back, and so does the new `models ai revoke`. `--no-images`
|
|
21
|
+
is gone. memo's command lint refused the old words. 0.626.0 shipped them for one day, and only WireCat Desktop
|
|
22
|
+
calls them.
|
|
23
|
+
|
|
24
|
+
## 0.627.0 — 10.11.2026
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- **`commands --serve` runs up to 8 requests at once** ([protocol](docs/REFERENCE.md#the-command-server)). The
|
|
29
|
+
ready line says how many (`"concurrent":8`); the protocol stays 1, so a client that sends one request at a time
|
|
30
|
+
works as before. Each request keeps its own output, stdin, exit code and run, and opens the store on its own
|
|
31
|
+
connection; a `store` command runs alone. WireCat Desktop's Memory page sends 7 reads together, and today a pool of
|
|
32
|
+
2 servers starts a fresh process for the other 5. `EntryContext.setExitCode(code)` sets a request's exit code in a
|
|
33
|
+
CLI with its own program; a direct `process.exitCode` write is one value for the whole process.
|
|
34
|
+
- **`memories.list`, `facts.list`, `proposedActions.list` and `agentActions.list` take an `offset`.** A caller pages
|
|
35
|
+
past the 500-row cap: `{ limit: 500, offset: 500 }` gives the next 500 in the same order, newest first with ties by
|
|
36
|
+
id, so no row shows twice and none is left out. memo's `--page` reads through it, so WireCat Desktop can show more
|
|
37
|
+
than 500 memories, facts or actions.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- **`models search-consents set` names the cost of the chosen model.** The consent text said "with claude-haiku-5-5
|
|
42
|
+
one costs about $0.0003" whatever model was chosen. It now prices one search with the chosen model (about $0.0005
|
|
43
|
+
with gpt-4o-mini), and says the cost is unknown for a model or address with no known price.
|
|
44
|
+
|
|
8
45
|
## 0.626.0 — 10.11.2026
|
|
9
46
|
|
|
10
47
|
### Added
|
|
@@ -55,6 +55,7 @@ export const aiModelCommand = (app, options) => {
|
|
|
55
55
|
output: { entity: "ai_model" },
|
|
56
56
|
examples: [`${app.command} models ai show`],
|
|
57
57
|
})
|
|
58
|
+
.summary("the chosen model, its key, and whether images may go to it")
|
|
58
59
|
.description("the chosen model, whether a key is stored for its address, and whether images may go to it")
|
|
59
60
|
.action(function () {
|
|
60
61
|
options.output(itemOf(view(app, options, readAiSetting(aiSettingPath(options.env())))), this);
|
|
@@ -64,18 +65,19 @@ export const aiModelCommand = (app, options) => {
|
|
|
64
65
|
mcp: false,
|
|
65
66
|
output: { entity: "ai_model", view: "chosen" },
|
|
66
67
|
examples: [
|
|
67
|
-
`${app.command} models ai set anthropic --model claude-haiku-4-5 --
|
|
68
|
-
`${app.command} models ai set openai --model openai/gpt-4o-mini --base-url https://openrouter.ai/api/v1 --
|
|
68
|
+
`${app.command} models ai set anthropic --model claude-haiku-4-5 --secret-stdin --allow-remote`,
|
|
69
|
+
`${app.command} models ai set openai --model openai/gpt-4o-mini --base-url https://openrouter.ai/api/v1 --secret-stdin`,
|
|
69
70
|
`${app.command} models ai set ollama --model llama3.2-vision`,
|
|
70
71
|
],
|
|
71
72
|
}))
|
|
73
|
+
.summary("choose the AI model: anthropic, openai or compatible, or ollama (beta)")
|
|
72
74
|
.description("choose the model: anthropic, openai (or any service that works like it, with --base-url) or ollama (beta)")
|
|
73
75
|
.argument("<provider>", AI_PROVIDERS.join(", "))
|
|
74
76
|
.requiredOption("--model <model>", "the model's name as the provider writes it")
|
|
75
77
|
.option("--base-url <url>", "the service's address; https, or http only on this computer")
|
|
76
|
-
.option("--
|
|
77
|
-
.option("--
|
|
78
|
-
|
|
78
|
+
.option("--secret-stdin", "read the API key from stdin, or ask for it; kept for this address only")
|
|
79
|
+
.option("--allow-remote", "let images you add to memory go to this model to be read; they leave this computer. Without it, a set " +
|
|
80
|
+
"takes back an earlier yes")
|
|
79
81
|
.option("--from-app", "you did this in WireCat Desktop")
|
|
80
82
|
.action(async function (provider, given) {
|
|
81
83
|
const env = options.env();
|
|
@@ -86,10 +88,9 @@ export const aiModelCommand = (app, options) => {
|
|
|
86
88
|
provider,
|
|
87
89
|
model: given.model,
|
|
88
90
|
baseUrl: given.baseUrl,
|
|
89
|
-
|
|
90
|
-
before,
|
|
91
|
+
allowImages: given.allowRemote,
|
|
91
92
|
});
|
|
92
|
-
if (given.
|
|
93
|
+
if (given.secretStdin) {
|
|
93
94
|
if (!aiNeedsKey(setting))
|
|
94
95
|
throw new CliError("validation_error", "Ollama on this computer takes no key");
|
|
95
96
|
const input = options.stdin?.();
|
|
@@ -101,38 +102,38 @@ export const aiModelCommand = (app, options) => {
|
|
|
101
102
|
writeAiSetting(path, setting);
|
|
102
103
|
if (setting.images)
|
|
103
104
|
options.diagnostic(imagesNote(setting));
|
|
104
|
-
const changed = JSON.stringify(before === undefined ? null : { ...before, images: before
|
|
105
|
-
JSON.stringify({ ...setting, images: setting
|
|
105
|
+
const changed = JSON.stringify(before === undefined ? null : { ...before, images: aiImagesAllowed(before) }) !==
|
|
106
|
+
JSON.stringify({ ...setting, images: aiImagesAllowed(setting) });
|
|
106
107
|
options.output(itemOf({ ...view(app, options, setting), changed }), this);
|
|
107
108
|
});
|
|
108
|
-
grantsAuthority(annotate(ai.command("
|
|
109
|
+
grantsAuthority(annotate(ai.command("unset"), {
|
|
109
110
|
effects: LOCAL_WRITE,
|
|
110
111
|
mcp: false,
|
|
111
112
|
output: { entity: "ai_model", view: "off" },
|
|
112
|
-
examples: [`${app.command} models ai
|
|
113
|
+
examples: [`${app.command} models ai unset`],
|
|
113
114
|
}))
|
|
114
|
-
.description("stop using a model; its key stays until models ai
|
|
115
|
+
.description("stop using a model; its key stays until models ai remove")
|
|
115
116
|
.option("--from-app", "you did this in WireCat Desktop")
|
|
116
117
|
.action(function () {
|
|
117
118
|
const env = options.env();
|
|
118
|
-
ownerOnly(this, env, "
|
|
119
|
+
ownerOnly(this, env, "unset");
|
|
119
120
|
const path = aiSettingPath(env);
|
|
120
121
|
const before = previous(path);
|
|
121
122
|
writeAiSetting(path, undefined);
|
|
122
123
|
options.output(itemOf({ changed: before !== undefined, key_kept: true }), this);
|
|
123
124
|
});
|
|
124
|
-
grantsAuthority(annotate(ai.command("
|
|
125
|
+
grantsAuthority(annotate(ai.command("remove"), {
|
|
125
126
|
effects: LOCAL_WRITE,
|
|
126
127
|
mcp: false,
|
|
127
128
|
output: { entity: "ai_model", view: "key-removed" },
|
|
128
|
-
examples: [`${app.command} models ai
|
|
129
|
+
examples: [`${app.command} models ai remove https://api.anthropic.com`],
|
|
129
130
|
}))
|
|
130
131
|
.description("remove the key stored for an address")
|
|
131
132
|
.argument("[origin]", "the address, for example https://openrouter.ai; the chosen model's when absent")
|
|
132
133
|
.option("--from-app", "you did this in WireCat Desktop")
|
|
133
134
|
.action(function (given) {
|
|
134
135
|
const env = options.env();
|
|
135
|
-
ownerOnly(this, env, "
|
|
136
|
+
ownerOnly(this, env, "remove");
|
|
136
137
|
const setting = given ? undefined : previous(aiSettingPath(env));
|
|
137
138
|
let origin = setting ? aiOrigin(setting) : "";
|
|
138
139
|
if (given) {
|
|
@@ -151,12 +152,33 @@ export const aiModelCommand = (app, options) => {
|
|
|
151
152
|
options.diagnostic(`a key for ${origin} is still found in ${still}; remove it there too`);
|
|
152
153
|
options.output(itemOf({ origin, removed: removed.length > 0, still_found: still }), this);
|
|
153
154
|
});
|
|
155
|
+
grantsAuthority(annotate(ai.command("revoke"), {
|
|
156
|
+
effects: LOCAL_WRITE,
|
|
157
|
+
mcp: false,
|
|
158
|
+
output: { entity: "ai_model", view: "chosen" },
|
|
159
|
+
examples: [`${app.command} models ai revoke`],
|
|
160
|
+
}))
|
|
161
|
+
.description("stop sending images to the AI model; the model itself stays chosen")
|
|
162
|
+
.option("--from-app", "you did this in WireCat Desktop")
|
|
163
|
+
.action(function () {
|
|
164
|
+
const env = options.env();
|
|
165
|
+
ownerOnly(this, env, "revoke");
|
|
166
|
+
const path = aiSettingPath(env);
|
|
167
|
+
const setting = readAiSetting(path);
|
|
168
|
+
if (!setting)
|
|
169
|
+
throw new CliError("configuration_error", "no AI model is chosen", { reason: "ai.not-set" });
|
|
170
|
+
const { images, ...kept } = setting;
|
|
171
|
+
if (images !== undefined)
|
|
172
|
+
writeAiSetting(path, kept);
|
|
173
|
+
options.output(itemOf({ ...view(app, options, kept), changed: images !== undefined }), this);
|
|
174
|
+
});
|
|
154
175
|
annotate(ai.command("check"), {
|
|
155
176
|
effects: FETCH,
|
|
156
177
|
mcp: false,
|
|
157
178
|
output: { entity: "ai_model_check" },
|
|
158
179
|
examples: [`${app.command} models ai check`],
|
|
159
180
|
})
|
|
181
|
+
.summary("send one short paid request and say what is wrong")
|
|
160
182
|
.description("send one short request (billed by the provider, usually under a cent) and say what is wrong")
|
|
161
183
|
.option("--from-app", "you did this in WireCat Desktop")
|
|
162
184
|
.action(async function () {
|
|
@@ -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
|
};
|
package/dist/cli/entry.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface EntryContext {
|
|
|
24
24
|
openBrowser: (url: string, browser?: string, command?: Command) => Promise<void>;
|
|
25
25
|
/** True once a reader closed the output (`| head`): nothing more reaches the terminal. */
|
|
26
26
|
outputClosed: () => boolean;
|
|
27
|
+
/** The exit code of an answer that is not a failure, a partial one; under `commands --serve`, of this request alone. */
|
|
28
|
+
setExitCode: (code: number) => void;
|
|
27
29
|
}
|
|
28
30
|
/** The parts of the process `startCli` touches, replaced in tests. */
|
|
29
31
|
export interface EntryIo {
|
package/dist/cli/entry.js
CHANGED
package/dist/cli/program.js
CHANGED
|
@@ -18,7 +18,8 @@ import { liftOptionsAfterDashes } from "./after-dashes.js";
|
|
|
18
18
|
import { logParsedArgv, logVersion } from "./argv-log.js";
|
|
19
19
|
import { commandAvailability } from "./command-availability.js";
|
|
20
20
|
import { commandPathOf } from "./command-contract.js";
|
|
21
|
-
import {
|
|
21
|
+
import { enterCommandServer } from "./command-server.js";
|
|
22
|
+
import { exitCodeSet } from "./command-server-request.js";
|
|
22
23
|
import { entityRows } from "./compact.js";
|
|
23
24
|
import { outputFor, provide } from "./context.js";
|
|
24
25
|
import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
|
|
@@ -312,7 +313,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
312
313
|
action.setOptionValue("dryRun", true);
|
|
313
314
|
refuseOfflineCommand(action, definition.app, flags.offline === true, flags.dryRun === true && localPreview);
|
|
314
315
|
const path = commandPathOf(action);
|
|
315
|
-
|
|
316
|
+
await enterCommandServer(action, command);
|
|
316
317
|
const lock = readOnlyLockOf(definition.app, commandEnv);
|
|
317
318
|
const input = options.stdin ?? process.stdin;
|
|
318
319
|
// The first-run questions write the shared config; a dry run writes nothing.
|
|
@@ -509,7 +510,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
509
510
|
}
|
|
510
511
|
try {
|
|
511
512
|
await control.race(() => program.parseAsync(rest, { from: "user" }));
|
|
512
|
-
const code = exit.code ?? (
|
|
513
|
+
const code = exit.code ?? exitCodeSet() ?? 0;
|
|
513
514
|
const refreshed = code === 0 ? refreshFor(definition, program, rest, options) : undefined;
|
|
514
515
|
if (refreshed && !rest.includes("--quiet"))
|
|
515
516
|
streams.diagnostic(refreshed);
|
|
@@ -7,11 +7,20 @@ import { ENRICHMENT_PROVIDERS, enrichmentEndpoint, enrichmentPrice, isEnrichment
|
|
|
7
7
|
import { HARDER_CANDIDATES, HARDER_CHARS, HARDER_MODELS, readHarderSetting, writeHarderSetting, } from "../services/search-harder.js";
|
|
8
8
|
import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
|
|
9
9
|
import { itemOf } from "./envelope.js";
|
|
10
|
+
// One search: 30 hits of up to 400 characters plus the prompt, and a short list of hit numbers back.
|
|
11
|
+
const SEARCH_TOKENS = { input: 3_000, output: 60 };
|
|
12
|
+
const searchCost = (chosen) => {
|
|
13
|
+
const price = enrichmentPrice(chosen.provider, chosen.model, chosen.base_url);
|
|
14
|
+
if (!price)
|
|
15
|
+
return "the cost of one is unknown (no price for this model)";
|
|
16
|
+
const usd = SEARCH_TOKENS.input * price.input + SEARCH_TOKENS.output * price.output;
|
|
17
|
+
return `one costs about $${Number(usd.toPrecision(1))}`;
|
|
18
|
+
};
|
|
10
19
|
/** What the owner agrees to; a window can write the same text from the answer's fields. */
|
|
11
20
|
export const harderConsentWording = (command, chosen) => `\`${command} search all --harder\` sends the question and its first ${HARDER_CANDIDATES} hits (each one's title, ` +
|
|
12
21
|
`date and up to ${HARDER_CHARS} characters of its text) to ${chosen.provider} ` +
|
|
13
22
|
`(${new URL(enrichmentEndpoint(chosen)).host}), model ${chosen.model}, which puts the hits that answer it first. ` +
|
|
14
|
-
|
|
23
|
+
`Only a search with --harder sends anything; ${searchCost(chosen)}, and it adds 1 to 2 seconds. ` +
|
|
15
24
|
`\`${command} models search-consents revoke\` turns it off.`;
|
|
16
25
|
const state = (app, options, given) => {
|
|
17
26
|
const env = options.env();
|
package/dist/documents.d.ts
CHANGED
|
@@ -8,6 +8,6 @@ export { columnName, sheetText } from "./attachments/sheets.js";
|
|
|
8
8
|
export * from "./documents/index.js";
|
|
9
9
|
export { isPublicAddress } from "./fetch/addresses.js";
|
|
10
10
|
export { type FetchedPage, type FetchPageOptions, fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, type PageLimits, type PageLookup, type PageRequest, type PageResponse, type PageTransport, type ResolvedAddress, } from "./fetch/page.js";
|
|
11
|
-
export { AI_PROVIDERS, type AiImageRefusal, type AiProvider, type AiSetting, aiImageReader, aiSettingPath, readAiSetting, } from "./models/ai.js";
|
|
11
|
+
export { AI_PROVIDERS, type AiImageRefusal, type AiProvider, type AiSetting, type AiTextReader, type AiTextRefusal, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, } from "./models/ai.js";
|
|
12
12
|
export { registerReader } from "./readers/registry.js";
|
|
13
13
|
export type { ReadContext, Reader, Section } from "./readers/types.js";
|
package/dist/documents.js
CHANGED
|
@@ -6,5 +6,5 @@ export { columnName, sheetText } from "./attachments/sheets.js";
|
|
|
6
6
|
export * from "./documents/index.js";
|
|
7
7
|
export { isPublicAddress } from "./fetch/addresses.js";
|
|
8
8
|
export { fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, } from "./fetch/page.js";
|
|
9
|
-
export { AI_PROVIDERS, aiImageReader, aiSettingPath, readAiSetting, } from "./models/ai.js";
|
|
9
|
+
export { AI_PROVIDERS, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, } from "./models/ai.js";
|
|
10
10
|
export { registerReader } from "./readers/registry.js";
|
package/dist/errors/reasons.js
CHANGED
|
@@ -63,7 +63,11 @@ const OTHERS = [
|
|
|
63
63
|
["model.offline", "permission_error", "downloading a model needs the network; --offline was requested"],
|
|
64
64
|
["model.key-rejected", "invalid_response", "the model provider refused the API key (401 or 403)"],
|
|
65
65
|
["model.unreachable", "invalid_response", "the model provider could not be reached over the network"],
|
|
66
|
-
[
|
|
66
|
+
[
|
|
67
|
+
"ai.owner-only",
|
|
68
|
+
"permission_error",
|
|
69
|
+
"only the owner chooses, unsets, checks or removes the AI model and its key, or revokes its consent",
|
|
70
|
+
],
|
|
67
71
|
["ai.setting-invalid", "configuration_error", "the ai section or the model given is not one WireCat can use"],
|
|
68
72
|
validation("ai.address-refused", "the model address must be https, or http only on this computer"),
|
|
69
73
|
["ai.not-set", "configuration_error", "no AI model is chosen; models ai set chooses one"],
|
package/dist/models/ai.d.ts
CHANGED
|
@@ -25,8 +25,7 @@ export declare const aiSettingOf: (given: {
|
|
|
25
25
|
provider: string;
|
|
26
26
|
model: string;
|
|
27
27
|
baseUrl?: string | undefined;
|
|
28
|
-
|
|
29
|
-
before?: AiSetting | undefined;
|
|
28
|
+
allowImages?: boolean | undefined;
|
|
30
29
|
}) => AiSetting;
|
|
31
30
|
export declare const aiBaseUrl: (setting: Pick<AiSetting, "provider" | "base_url">) => string;
|
|
32
31
|
export declare const aiOrigin: (setting: Pick<AiSetting, "provider" | "base_url">) => string;
|
|
@@ -65,6 +64,23 @@ export declare const aiImageReader: (deps: AiCallDeps) => {
|
|
|
65
64
|
} | {
|
|
66
65
|
refused: AiImageRefusal;
|
|
67
66
|
};
|
|
67
|
+
/** False only for a model on this computer: Ollama, or any address on loopback. */
|
|
68
|
+
export declare const aiLeavesComputer: (setting: AiSetting) => boolean;
|
|
69
|
+
export type AiTextRefusal = "ai.not-set" | "ai.key-missing";
|
|
70
|
+
export interface AiTextReader {
|
|
71
|
+
by: string;
|
|
72
|
+
leavesComputer: boolean;
|
|
73
|
+
complete(request: {
|
|
74
|
+
purpose: string;
|
|
75
|
+
system: string;
|
|
76
|
+
prompt: string;
|
|
77
|
+
maxTokens: number;
|
|
78
|
+
}): Promise<string>;
|
|
79
|
+
}
|
|
80
|
+
/** The chosen model for text a tool sends on purpose; picking this reader by name is the owner's consent, as for images. */
|
|
81
|
+
export declare const aiTextReader: (deps: AiCallDeps) => AiTextReader | {
|
|
82
|
+
refused: AiTextRefusal;
|
|
83
|
+
};
|
|
68
84
|
export type AiCheckReason = "ai.ok" | "ai.not-set" | "ai.key-missing" | "ai.key-rejected" | "ai.no-credit" | "ai.model-unknown" | "ai.rate-limited" | "ai.unreachable" | "ai.provider-error" | "ai.failed";
|
|
69
85
|
/** One tiny paid request that proves the key, the model and the credit together; the provider's own text is never kept. */
|
|
70
86
|
export declare const checkAi: (deps: AiCallDeps) => Promise<{
|
package/dist/models/ai.js
CHANGED
|
@@ -65,10 +65,7 @@ export const aiSettingOf = (given) => {
|
|
|
65
65
|
}
|
|
66
66
|
if (checked.output.provider === "ollama" && !loopback(new URL(aiBaseUrl(checked.output)).hostname))
|
|
67
67
|
throw new CliError("validation_error", "Ollama is read only on this computer", { reason: "ai.address-refused" });
|
|
68
|
-
|
|
69
|
-
if (kept && kept.origin === aiOrigin(checked.output) && kept.model === checked.output.model)
|
|
70
|
-
return { ...checked.output, images: kept };
|
|
71
|
-
return given.images
|
|
68
|
+
return given.allowImages
|
|
72
69
|
? {
|
|
73
70
|
...checked.output,
|
|
74
71
|
images: { origin: aiOrigin(checked.output), model: checked.output.model, at: new Date().toISOString() },
|
|
@@ -153,6 +150,23 @@ export const aiImageReader = (deps) => {
|
|
|
153
150
|
},
|
|
154
151
|
};
|
|
155
152
|
};
|
|
153
|
+
/** False only for a model on this computer: Ollama, or any address on loopback. */
|
|
154
|
+
export const aiLeavesComputer = (setting) => !loopback(new URL(aiBaseUrl(setting)).hostname);
|
|
155
|
+
/** The chosen model for text a tool sends on purpose; picking this reader by name is the owner's consent, as for images. */
|
|
156
|
+
export const aiTextReader = (deps) => {
|
|
157
|
+
const setting = readAiSetting(aiSettingPath(deps.env));
|
|
158
|
+
if (!setting)
|
|
159
|
+
return { refused: "ai.not-set" };
|
|
160
|
+
const key = keyFor(setting, deps);
|
|
161
|
+
if (aiNeedsKey(setting) && !key)
|
|
162
|
+
return { refused: "ai.key-missing" };
|
|
163
|
+
const gateway = gatewayFor(setting, deps, key);
|
|
164
|
+
return {
|
|
165
|
+
by: `${setting.provider}/${setting.model}`,
|
|
166
|
+
leavesComputer: aiLeavesComputer(setting),
|
|
167
|
+
complete: async (request) => (await gateway.complete(request)).text,
|
|
168
|
+
};
|
|
169
|
+
};
|
|
156
170
|
const reasonOf = (error) => {
|
|
157
171
|
if (!(error instanceof CliError))
|
|
158
172
|
return "ai.failed";
|
package/dist/runs/scope.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface RunScope {
|
|
|
11
11
|
/** The run's event sink, for a transport far below the command (a wire middleware) that is not handed one. */
|
|
12
12
|
events?: EventSink;
|
|
13
13
|
}
|
|
14
|
+
/** Runs `body` as if in a fresh process: the process's run starts unset, apart from the one around it. */
|
|
15
|
+
export declare const asOwnProcess: <T>(body: () => T) => T;
|
|
14
16
|
/**
|
|
15
17
|
* The run a log line written now belongs to, for a writer that is not handed one — the send journal,
|
|
16
18
|
* the serve log. Outside any run, one id for the whole process, so its lines still group together.
|
package/dist/runs/scope.js
CHANGED
|
@@ -4,6 +4,10 @@ import { traceIdOf } from "@wirecat/cli-base/standards";
|
|
|
4
4
|
import { newRunId } from "./run.js";
|
|
5
5
|
const scopes = new AsyncLocalStorage();
|
|
6
6
|
let processScope;
|
|
7
|
+
// A command server's request is a process of its own, and several run at once.
|
|
8
|
+
const ownProcesses = new AsyncLocalStorage();
|
|
9
|
+
/** Runs `body` as if in a fresh process: the process's run starts unset, apart from the one around it. */
|
|
10
|
+
export const asOwnProcess = (body) => ownProcesses.run({}, body);
|
|
7
11
|
/**
|
|
8
12
|
* The run a log line written now belongs to, for a writer that is not handed one — the send journal,
|
|
9
13
|
* the serve log. Outside any run, one id for the whole process, so its lines still group together.
|
|
@@ -12,12 +16,18 @@ export const currentRun = () => {
|
|
|
12
16
|
const scope = scopes.getStore();
|
|
13
17
|
if (scope)
|
|
14
18
|
return scope;
|
|
15
|
-
|
|
19
|
+
const own = ownProcesses.getStore();
|
|
20
|
+
const fresh = () => ({
|
|
16
21
|
runId: newRunId(new Date(), "process"),
|
|
17
22
|
command: "",
|
|
18
23
|
startedAt: Date.now(),
|
|
19
24
|
...traceOf(process.env),
|
|
20
|
-
};
|
|
25
|
+
});
|
|
26
|
+
if (own) {
|
|
27
|
+
own.scope ??= fresh();
|
|
28
|
+
return own.scope;
|
|
29
|
+
}
|
|
30
|
+
processScope ??= fresh();
|
|
21
31
|
return processScope;
|
|
22
32
|
};
|
|
23
33
|
export const inRun = (scope, body) => scopes.run(scope, body);
|
|
@@ -33,10 +43,17 @@ export const typedCommand = (tool, words, profile = currentRun().profile) => [to
|
|
|
33
43
|
* cannot wrap the action — so its answers' `meta.run_id` names the run `runs show` finds. Never in a server.
|
|
34
44
|
*/
|
|
35
45
|
export const useAsProcessRun = (scope) => {
|
|
36
|
-
|
|
46
|
+
const own = ownProcesses.getStore();
|
|
47
|
+
if (own)
|
|
48
|
+
own.scope = scope;
|
|
49
|
+
else
|
|
50
|
+
processScope = scope;
|
|
37
51
|
};
|
|
38
52
|
/** The run `useAsProcessRun` named, if any: a command run in-process puts it back when it ends. */
|
|
39
|
-
export const processRun = () =>
|
|
53
|
+
export const processRun = () => {
|
|
54
|
+
const own = ownProcesses.getStore();
|
|
55
|
+
return own ? own.scope : processScope;
|
|
56
|
+
};
|
|
40
57
|
/** The trace of the run this one is opened inside — an MCP call's command keeps its caller's trace. */
|
|
41
58
|
export const enclosingTraceId = () => scopes.getStore()?.traceId;
|
|
42
59
|
/**
|
|
@@ -44,6 +44,7 @@ export interface AgentActionsStore {
|
|
|
44
44
|
tool?: string;
|
|
45
45
|
agent?: string;
|
|
46
46
|
limit?: number;
|
|
47
|
+
offset?: number;
|
|
47
48
|
}): Promise<AgentAction[]>;
|
|
48
49
|
}
|
|
49
50
|
export declare const agentActionsStoreOver: (context: StoreContext, afterRecord?: () => void) => AgentActionsStore;
|
|
@@ -41,9 +41,9 @@ export const agentActionsStoreOver = (context, afterRecord = () => { }) => {
|
|
|
41
41
|
afterRecord();
|
|
42
42
|
return actionOf(database.prepare(`${NAMED} WHERE a.id = ?`).get(Number(row?.id)));
|
|
43
43
|
},
|
|
44
|
-
list: async ({ tool, agent, limit = 100 } = {}) => database
|
|
45
|
-
.prepare(`${NAMED} WHERE (? IS NULL OR a.tool = ?) AND (? IS NULL OR b.name = ?) ORDER BY a.started_at DESC, a.id DESC LIMIT ?`)
|
|
46
|
-
.all(tool ?? null, tool ?? null, agent ?? null, agent ?? null, Math.min(Math.max(limit, 1), 500))
|
|
44
|
+
list: async ({ tool, agent, limit = 100, offset = 0 } = {}) => database
|
|
45
|
+
.prepare(`${NAMED} WHERE (? IS NULL OR a.tool = ?) AND (? IS NULL OR b.name = ?) ORDER BY a.started_at DESC, a.id DESC LIMIT ? OFFSET ?`)
|
|
46
|
+
.all(tool ?? null, tool ?? null, agent ?? null, agent ?? null, Math.min(Math.max(limit, 1), 500), Math.max(offset, 0))
|
|
47
47
|
.map(actionOf),
|
|
48
48
|
};
|
|
49
49
|
};
|
|
@@ -69,6 +69,8 @@ export interface FactsStore {
|
|
|
69
69
|
/** `created` lists the newest written first; by default the newest by when it happened. */
|
|
70
70
|
order?: "occurred" | "created";
|
|
71
71
|
limit?: number;
|
|
72
|
+
/** Rows to skip, for the next page in the same order, ties by id. */
|
|
73
|
+
offset?: number;
|
|
72
74
|
}): Promise<Fact[]>;
|
|
73
75
|
/** The owner, or an agent for the owner, accepts a proposed fact; the fact it supersedes stops holding. */
|
|
74
76
|
accept(reference: string, by: Decider, reason?: string): Promise<Fact>;
|
|
@@ -141,8 +141,8 @@ export const factOperationsOver = (context) => {
|
|
|
141
141
|
return database
|
|
142
142
|
.prepare(`${NAMED} WHERE f.deleted_at IS NULL AND (? IS NULL OR f.type = ?) AND (? IS NULL OR f.project_id = ?) ` +
|
|
143
143
|
"AND (? IS NULL OR (f.subject_type = ? AND f.subject_id IN (SELECT value FROM json_each(?)))) AND (? IS NULL OR f.status = ?) " +
|
|
144
|
-
`AND ${by.sql} ORDER BY ${order} DESC, f.id DESC LIMIT ?`)
|
|
145
|
-
.all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, options.status ?? null, options.status ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
|
|
144
|
+
`AND ${by.sql} ORDER BY ${order} DESC, f.id DESC LIMIT ? OFFSET ?`)
|
|
145
|
+
.all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, options.status ?? null, options.status ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500), Math.max(options.offset ?? 0, 0))
|
|
146
146
|
.map(factOf);
|
|
147
147
|
},
|
|
148
148
|
accept: (reference, by, reason) => {
|
|
@@ -72,6 +72,8 @@ export interface MemoriesStore {
|
|
|
72
72
|
scope?: Memory["scope"];
|
|
73
73
|
proposedBy?: ProposedByFilter;
|
|
74
74
|
limit?: number;
|
|
75
|
+
/** Rows to skip, for the next page: newest first, ties by id, so pages do not overlap. */
|
|
76
|
+
offset?: number;
|
|
75
77
|
}): Promise<Memory[]>;
|
|
76
78
|
/** Moves it to another project, or to none with `null`. */
|
|
77
79
|
update(reference: string, change: {
|
|
@@ -272,8 +272,8 @@ export const memoriesStoreOver = (context) => {
|
|
|
272
272
|
return database
|
|
273
273
|
.prepare(`${NAMED} WHERE m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) ` +
|
|
274
274
|
"AND (? IS NULL OR m.project_id = ?) AND (? IS NULL OR m.kind = ?) AND (? IS NULL OR m.status = ?) AND (? IS NULL OR m.scope = ?) " +
|
|
275
|
-
`AND ${by.sql} ORDER BY m.created_at DESC, m.id DESC LIMIT ?`)
|
|
276
|
-
.all(subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
|
|
275
|
+
`AND ${by.sql} ORDER BY m.created_at DESC, m.id DESC LIMIT ? OFFSET ?`)
|
|
276
|
+
.all(subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500), Math.max(options.offset ?? 0, 0))
|
|
277
277
|
.map(memoryOf);
|
|
278
278
|
},
|
|
279
279
|
update: async (reference, change) => write(database, () => {
|
|
@@ -56,6 +56,8 @@ export interface ProposedActionsStore {
|
|
|
56
56
|
list(options?: {
|
|
57
57
|
status?: ProposedAction["status"];
|
|
58
58
|
limit?: number;
|
|
59
|
+
/** Rows to skip, for the next page: newest first, ties by id. */
|
|
60
|
+
offset?: number;
|
|
59
61
|
kinds?: readonly string[];
|
|
60
62
|
except?: readonly string[];
|
|
61
63
|
proposedBy?: ProposedByFilter;
|
|
@@ -132,7 +132,7 @@ export const proposalOperationsOver = (context) => {
|
|
|
132
132
|
.prepare(`${NAMED} WHERE p.status = 'proposed' ORDER BY p.created_at, p.id LIMIT ?`)
|
|
133
133
|
.all(Math.min(Math.max(limit, 1), 500))
|
|
134
134
|
.map(actionOf),
|
|
135
|
-
list: ({ status, limit = 100, kinds, except, proposedBy, project, evidence } = {}) => {
|
|
135
|
+
list: ({ status, limit = 100, offset = 0, kinds, except, proposedBy, project, evidence } = {}) => {
|
|
136
136
|
if (status !== undefined && !PROPOSAL_STATUSES.includes(status))
|
|
137
137
|
throw new CliError("validation_error", `a status is one of ${PROPOSAL_STATUSES.join(", ")}`);
|
|
138
138
|
const by = proposedBySql("p.proposed_by_type", "p.proposed_by_id", proposedBy);
|
|
@@ -141,8 +141,8 @@ export const proposalOperationsOver = (context) => {
|
|
|
141
141
|
"AND p.kind NOT IN (SELECT value FROM json_each(?)) AND (? IS NULL OR (p.target_type = 'project' AND " +
|
|
142
142
|
"'project:' || p.target_id = ?) OR json_extract(p.payload, '$.to') = ? OR json_extract(p.payload, '$.from') = ? " +
|
|
143
143
|
`OR json_extract(p.payload, '$.project') = ?) AND (? IS NULL OR EXISTS (SELECT 1 FROM json_each(p.payload, '$.evidence') ` +
|
|
144
|
-
`WHERE value = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
|
|
145
|
-
.all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, Math.min(Math.max(limit, 1), 500))
|
|
144
|
+
`WHERE value = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ? OFFSET ?`)
|
|
145
|
+
.all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, Math.min(Math.max(limit, 1), 500), Math.max(offset, 0))
|
|
146
146
|
.map(actionOf);
|
|
147
147
|
},
|
|
148
148
|
approve: (id, result, by) => decide(id, "approved", result, by),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.628.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|