@wirecat/cli-core 0.620.0 → 0.622.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 +47 -0
- package/dist/cli/command-server-argv.d.ts +7 -0
- package/dist/cli/command-server-argv.js +7 -0
- package/dist/cli/command-server-entry.d.ts +12 -0
- package/dist/cli/command-server-entry.js +122 -0
- package/dist/cli/command-server.d.ts +29 -0
- package/dist/cli/command-server.js +100 -0
- package/dist/cli/entry.d.ts +2 -0
- package/dist/cli/entry.js +24 -18
- package/dist/cli/program.js +2 -0
- package/dist/cli/search-harder-consents-command.d.ts +4 -1
- package/dist/cli/search-harder-consents-command.js +49 -20
- package/dist/crm/source.d.ts +8 -0
- package/dist/crm/sync.d.ts +1 -1
- package/dist/crm/sync.js +13 -1
- package/dist/domain/relations.d.ts +1 -0
- package/dist/domain/relations.js +5 -1
- package/dist/errors/reasons.js +1 -0
- package/dist/services/enrichment-setting.d.ts +6 -0
- package/dist/services/enrichment-setting.js +5 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/search-all.js +2 -1
- package/dist/services/search-harder.d.ts +34 -8
- package/dist/services/search-harder.js +152 -82
- package/dist/store/driver.d.ts +5 -1
- package/dist/store/driver.js +5 -0
- package/dist/store/sqlite/notes.js +10 -2
- package/dist/store/sqlite/ref-accounts.js +6 -3
- package/dist/store/sqlite/reported-relations.d.ts +0 -1
- package/dist/store/sqlite/reported-relations.js +1 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,53 @@ 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.622.0 — 09.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `<cli> commands --serve`, in every CLI that starts through `startCli`: one long-running process that runs command
|
|
13
|
+
after command, so WireCat Desktop no longer starts Node for each read on a page. One JSON request per line on stdin
|
|
14
|
+
(`{"id","argv"}`), one answer per line on stdout (`{"id","code","stdout","stderr"}`, what a spawned run would have
|
|
15
|
+
printed). Requests run one at a time; each is recorded as its own run, reads settings and keys again and leaves the
|
|
16
|
+
store closed. A command that runs until stopped, waits on a person or reads stdin is refused with code 2. The
|
|
17
|
+
server ends when stdin closes or after 10 minutes without a request. It is in no help, `commands --json` or MCP.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- The store's write-ahead file (`wirecat.db-wal`) no longer stays at the size of the biggest write it ever held: every
|
|
22
|
+
connection sets a 64 MiB journal size limit, so SQLite cuts the file back after a checkpoint. One large CRM sync had
|
|
23
|
+
left a 2.2 GB file behind.
|
|
24
|
+
|
|
25
|
+
## 0.621.0 — 09.11.2026
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- A CRM source may say which users in `crm.<provider>:<account>.unassigned` its sign-in may count as nobody's
|
|
30
|
+
(`CrmSource.unassigned`), asked at every sync under `scope mine`. The sync copies no deal or lead of a user it
|
|
31
|
+
leaves out, narrows the copy to match, and names them in an issue with the reason `crm.unassigned-dropped`.
|
|
32
|
+
- **`models search-consents set` takes `openai`, `anthropic` or an OpenAI-compatible API (`--base-url`, such as
|
|
33
|
+
OpenRouter).** Each provider has its own default model for `search all --harder` (`claude-haiku-5-5`,
|
|
34
|
+
`gpt-4o-mini`); another API needs `--model`. `show` proposes enrichment's provider and model when the owner chose
|
|
35
|
+
one there, but never gives this consent by itself. The answer's `harder` field names the `endpoint` too. Anthropic's
|
|
36
|
+
`thinking` and `output_config` go to Anthropic only; OpenAI gets its JSON mode, and any reply wrapped in a code block
|
|
37
|
+
is still read. See
|
|
38
|
+
[AI providers, "Search harder"](docs/search/ai-providers.md#search-harder-a-hosted-model-reorders-search-all-off-by-default).
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
|
|
42
|
+
- **A file's own relationship, such as a Drive document's owner, no longer waits for review.** `replaceFileLinks`
|
|
43
|
+
writes an unconfirmed relationship from a document with the document's account, so it is `reported` (what the
|
|
44
|
+
source says) instead of `proposed`. Before, every Drive document's owner and last editor stood in the owner's review
|
|
45
|
+
list. Links the file states that are not relationships, and the owner's own links, are unchanged. A source re-writes
|
|
46
|
+
its links on its next import: `drive <profile> catalog import --offline` moves the stored ones.
|
|
47
|
+
- **`search all --harder` sends the question as typed.** It sent the query parser's escaped copy (`deposit\?`), and a
|
|
48
|
+
`$&` in a question was read as a replacement pattern.
|
|
49
|
+
- **`relationships list include:ended` answers in about 0.2 seconds instead of minutes on a store with a busy
|
|
50
|
+
person.** The check for an owner's override of a link looked the override up by the link's target, so a person on
|
|
51
|
+
25,857 deals read every one of those links again for each relationship (325 seconds on a 108,000-link store). It now
|
|
52
|
+
looks it up by the relationship's own key. The same check runs in the deal's people, a thing's relationships and a
|
|
53
|
+
meeting's preparation, so those get faster too.
|
|
54
|
+
|
|
8
55
|
## 0.620.0 — 09.11.2026
|
|
9
56
|
|
|
10
57
|
### Added
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<cli> commands --serve`: one process that runs command after command for WireCat Desktop, which otherwise pays a
|
|
3
|
+
* whole Node start for each read on a page. Matched before the program loads, so it is in no help, no `commands`
|
|
4
|
+
* document and no MCP catalogue — and a flag, because `commands <path>` already describes every top-level word.
|
|
5
|
+
*/
|
|
6
|
+
export declare const COMMAND_SERVER_ARGV: readonly string[];
|
|
7
|
+
export declare const isCommandServer: (args: readonly string[]) => boolean;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<cli> commands --serve`: one process that runs command after command for WireCat Desktop, which otherwise pays a
|
|
3
|
+
* whole Node start for each read on a page. Matched before the program loads, so it is in no help, no `commands`
|
|
4
|
+
* document and no MCP catalogue — and a flag, because `commands <path>` already describes every top-level word.
|
|
5
|
+
*/
|
|
6
|
+
export const COMMAND_SERVER_ARGV = ["commands", "--serve"];
|
|
7
|
+
export const isCommandServer = (args) => args.length === COMMAND_SERVER_ARGV.length && COMMAND_SERVER_ARGV.every((word, at) => args[at] === word);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CliEntry, EntryIo, firstRunAt } from "./entry.js";
|
|
2
|
+
/** What `startCli` already has, handed in so the two modules do not import each other. */
|
|
3
|
+
export interface EntryParts {
|
|
4
|
+
firstRunAt: typeof firstRunAt;
|
|
5
|
+
commanderExit: (error: unknown) => number | undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* `startCli` for `<cli> commands --serve`: each request runs the CLI's own `run` as a spawned process would, and its
|
|
9
|
+
* output, which the process's streams would have carried, comes back in the answer. Between requests nothing reaches
|
|
10
|
+
* stdout but the protocol; a late write goes to stderr.
|
|
11
|
+
*/
|
|
12
|
+
export declare const serveEntry: (entry: CliEntry, io: EntryIo, { firstRunAt, commanderExit }: EntryParts) => Promise<void>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { PassThrough } from "node:stream";
|
|
2
|
+
import { CliError, catchCrashes } from "@wirecat/cli-base";
|
|
3
|
+
import { useAsProcessRun } from "../runs/scope.js";
|
|
4
|
+
import { ensureSqlite } from "../sqlite-runtime.js";
|
|
5
|
+
import { inCommandServerRequest, refuseInCommandServer, serveCommands } from "./command-server.js";
|
|
6
|
+
/**
|
|
7
|
+
* Every write to the process's stream goes to `sink()`. The stream's `write` is replaced, not the stream: the global
|
|
8
|
+
* console keeps the stream it first wrote to, and `complete` prints through it.
|
|
9
|
+
*/
|
|
10
|
+
const route = (stream, sink) => {
|
|
11
|
+
const original = stream.write;
|
|
12
|
+
stream.write = ((chunk, encoding, callback) => {
|
|
13
|
+
sink()(typeof chunk === "string"
|
|
14
|
+
? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8")
|
|
15
|
+
: Buffer.from(chunk));
|
|
16
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
17
|
+
if (done)
|
|
18
|
+
process.nextTick(done);
|
|
19
|
+
return true;
|
|
20
|
+
});
|
|
21
|
+
return () => {
|
|
22
|
+
stream.write = original;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
// As a spawned run that Desktop gave no input: anything that reads stdin sees it end at once.
|
|
26
|
+
const closedStdin = () => {
|
|
27
|
+
const stdin = new PassThrough();
|
|
28
|
+
stdin.end();
|
|
29
|
+
return stdin;
|
|
30
|
+
};
|
|
31
|
+
const useStdin = (stdin) => Object.defineProperty(process, "stdin", { value: stdin, configurable: true, enumerable: true, writable: true });
|
|
32
|
+
/**
|
|
33
|
+
* `startCli` for `<cli> commands --serve`: each request runs the CLI's own `run` as a spawned process would, and its
|
|
34
|
+
* output, which the process's streams would have carried, comes back in the answer. Between requests nothing reaches
|
|
35
|
+
* stdout but the protocol; a late write goes to stderr.
|
|
36
|
+
*/
|
|
37
|
+
export const serveEntry = async (entry, io, { firstRunAt, commanderExit }) => {
|
|
38
|
+
const release = catchCrashes({
|
|
39
|
+
cli: entry.app.command,
|
|
40
|
+
interactive: false,
|
|
41
|
+
...(entry.reasons ? { reasons: entry.reasons } : {}),
|
|
42
|
+
target: io.signals,
|
|
43
|
+
});
|
|
44
|
+
const stopper = new AbortController();
|
|
45
|
+
const stop = () => stopper.abort(new CliError("cancelled", "the command server was stopped", { retryable: false }));
|
|
46
|
+
const protocol = io.stdout.write.bind(io.stdout);
|
|
47
|
+
const ownStderr = io.stderr.write.bind(io.stderr);
|
|
48
|
+
const toStderr = (chunk) => {
|
|
49
|
+
ownStderr(chunk);
|
|
50
|
+
};
|
|
51
|
+
let current;
|
|
52
|
+
const unrouteOut = route(process.stdout, () => (current ? (chunk) => current?.stdout.push(chunk) : toStderr));
|
|
53
|
+
const unrouteErr = route(process.stderr, () => (current ? (chunk) => current?.stderr.push(chunk) : toStderr));
|
|
54
|
+
const stdin = Object.getOwnPropertyDescriptor(process, "stdin");
|
|
55
|
+
const requests = io.stdin;
|
|
56
|
+
useStdin(closedStdin());
|
|
57
|
+
io.signals.on("SIGINT", stop).on("SIGTERM", stop);
|
|
58
|
+
io.stdout.on("error", stop);
|
|
59
|
+
const run = async (argv) => {
|
|
60
|
+
const stdout = [];
|
|
61
|
+
const stderr = [];
|
|
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 };
|
|
69
|
+
const context = {
|
|
70
|
+
args: argv,
|
|
71
|
+
env: io.env,
|
|
72
|
+
tty: false,
|
|
73
|
+
signal: stopper.signal,
|
|
74
|
+
atStart: async (command) => {
|
|
75
|
+
refuseInCommandServer(command, entry.app.command);
|
|
76
|
+
await firstRunAt(entry, requestIo, () => true)(command);
|
|
77
|
+
},
|
|
78
|
+
ask: async () => false,
|
|
79
|
+
openBrowser: async () => undefined,
|
|
80
|
+
outputClosed: () => false,
|
|
81
|
+
};
|
|
82
|
+
let code;
|
|
83
|
+
try {
|
|
84
|
+
code = await inCommandServerRequest(async () => {
|
|
85
|
+
try {
|
|
86
|
+
const returned = await entry.run(context);
|
|
87
|
+
return typeof returned === "number" ? returned : Number(process.exitCode ?? 0);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
return commanderExit(error) ?? entry.fail(error, context);
|
|
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
|
+
};
|
|
100
|
+
try {
|
|
101
|
+
if (entry.sqlite)
|
|
102
|
+
await ensureSqlite();
|
|
103
|
+
await serveCommands({
|
|
104
|
+
input: requests,
|
|
105
|
+
write: (line) => new Promise((resolve) => (protocol(line) ? resolve() : io.stdout.once("drain", resolve))),
|
|
106
|
+
run,
|
|
107
|
+
cli: entry.app.command,
|
|
108
|
+
version: entry.app.version,
|
|
109
|
+
signal: stopper.signal,
|
|
110
|
+
});
|
|
111
|
+
io.setExitCode(0);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
io.signals.off("SIGINT", stop).off("SIGTERM", stop);
|
|
115
|
+
unrouteOut();
|
|
116
|
+
unrouteErr();
|
|
117
|
+
if (stdin)
|
|
118
|
+
Object.defineProperty(process, "stdin", stdin);
|
|
119
|
+
requests.destroy?.();
|
|
120
|
+
release();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Command } from "commander";
|
|
2
|
+
export declare const COMMAND_SERVER_PROTOCOL = 1;
|
|
3
|
+
/** An updated tool's old code must not answer for long. */
|
|
4
|
+
export declare const COMMAND_SERVER_IDLE_MS: number;
|
|
5
|
+
export declare const inCommandServerRequest: <T>(work: () => T) => T;
|
|
6
|
+
/** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
|
|
7
|
+
export declare const refuseInCommandServer: (command: Command, cli: string) => void;
|
|
8
|
+
export interface CommandAnswer {
|
|
9
|
+
code: number;
|
|
10
|
+
stdout: string;
|
|
11
|
+
stderr: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ServeOptions {
|
|
14
|
+
input: NodeJS.ReadableStream;
|
|
15
|
+
/** One protocol line, the newline included; resolves once it may be written again. */
|
|
16
|
+
write: (line: string) => Promise<void>;
|
|
17
|
+
run: (argv: string[]) => Promise<CommandAnswer>;
|
|
18
|
+
cli: string;
|
|
19
|
+
version: string;
|
|
20
|
+
idleMs?: number;
|
|
21
|
+
/** Ends the server after the request under way. */
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Says it is ready, then answers each line of `input` in order, one at a time: two runs at once in one process would
|
|
26
|
+
* open the store twice, and closing either descriptor drops the other's locks (BUG-557). Resolves with 0 when the
|
|
27
|
+
* input ends or nothing came for `idleMs`.
|
|
28
|
+
*/
|
|
29
|
+
export declare const serveCommands: ({ input, write, run, cli, version, idleMs, signal, }: ServeOptions) => Promise<number>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { CliError, errorObjectOf, renderError } from "@wirecat/cli-base";
|
|
4
|
+
import { metaOf } from "@wirecat/cli-base/commands";
|
|
5
|
+
import { commandPathOf } from "./command-contract.js";
|
|
6
|
+
import { isCommandServer } from "./command-server-argv.js";
|
|
7
|
+
import { stdinFieldOf } from "./stdin-field.js";
|
|
8
|
+
export const COMMAND_SERVER_PROTOCOL = 1;
|
|
9
|
+
/** An updated tool's old code must not answer for long. */
|
|
10
|
+
export const COMMAND_SERVER_IDLE_MS = 10 * 60_000;
|
|
11
|
+
const requests = new AsyncLocalStorage();
|
|
12
|
+
export const inCommandServerRequest = (work) => requests.run(true, work);
|
|
13
|
+
/** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
|
|
14
|
+
export const refuseInCommandServer = (command, cli) => {
|
|
15
|
+
if (requests.getStore() !== true)
|
|
16
|
+
return;
|
|
17
|
+
const typed = [cli, ...commandPathOf(command)].join(" ");
|
|
18
|
+
const { lifetime } = metaOf(command);
|
|
19
|
+
if (lifetime)
|
|
20
|
+
throw new CliError("validation_error", `\`${typed}\` ${lifetime === "persistent" ? "runs until it is stopped" : "waits on a person"}; ` +
|
|
21
|
+
"the command server runs only commands that return — start it as a process of its own");
|
|
22
|
+
if (stdinFieldOf(command))
|
|
23
|
+
throw new CliError("validation_error", `\`${typed}\` reads its input on stdin, which the command server does not pass on — start it as a process of its own`);
|
|
24
|
+
};
|
|
25
|
+
const refusal = (cli, message) => `${renderError(errorObjectOf(new CliError("validation_error", message)), { cli, interactive: false })}\n`;
|
|
26
|
+
const requestOf = (line, cli) => {
|
|
27
|
+
let parsed;
|
|
28
|
+
try {
|
|
29
|
+
parsed = JSON.parse(line);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return { id: null, error: "a request is one JSON object per line" };
|
|
33
|
+
}
|
|
34
|
+
const { id, argv } = (parsed ?? {});
|
|
35
|
+
// A request whose id is readable is answered under it, so the client never waits on it.
|
|
36
|
+
const known = typeof id === "number" && Number.isFinite(id) ? id : null;
|
|
37
|
+
if (known === null)
|
|
38
|
+
return { id: null, error: 'a request needs a numeric "id"' };
|
|
39
|
+
if (!Array.isArray(argv) || !argv.every((word) => typeof word === "string"))
|
|
40
|
+
return { id: known, error: '"argv" is a list of strings' };
|
|
41
|
+
if (isCommandServer(argv))
|
|
42
|
+
return { id: known, error: `\`${cli} commands --serve\` cannot run inside itself` };
|
|
43
|
+
return { id: known, argv };
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Says it is ready, then answers each line of `input` in order, one at a time: two runs at once in one process would
|
|
47
|
+
* open the store twice, and closing either descriptor drops the other's locks (BUG-557). Resolves with 0 when the
|
|
48
|
+
* input ends or nothing came for `idleMs`.
|
|
49
|
+
*/
|
|
50
|
+
export const serveCommands = async ({ input, write, run, cli, version, idleMs = COMMAND_SERVER_IDLE_MS, signal, }) => {
|
|
51
|
+
const send = (value) => write(`${JSON.stringify(value)}\n`);
|
|
52
|
+
await send({ ready: true, protocol: COMMAND_SERVER_PROTOCOL, version });
|
|
53
|
+
const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
let queue = Promise.resolve();
|
|
56
|
+
let waiting = 0;
|
|
57
|
+
let timer;
|
|
58
|
+
let done = false;
|
|
59
|
+
const finish = () => {
|
|
60
|
+
if (done)
|
|
61
|
+
return;
|
|
62
|
+
done = true;
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
lines.close();
|
|
65
|
+
resolve(0);
|
|
66
|
+
};
|
|
67
|
+
const idle = () => {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
timer = setTimeout(finish, idleMs);
|
|
70
|
+
};
|
|
71
|
+
const answer = async (line) => {
|
|
72
|
+
const request = requestOf(line, cli);
|
|
73
|
+
if ("error" in request)
|
|
74
|
+
return send({ id: request.id, code: 2, stdout: "", stderr: refusal(cli, request.error) });
|
|
75
|
+
const answered = await run(request.argv);
|
|
76
|
+
return send({ id: request.id, ...answered });
|
|
77
|
+
};
|
|
78
|
+
lines.on("line", (line) => {
|
|
79
|
+
if (done || line.trim() === "")
|
|
80
|
+
return;
|
|
81
|
+
waiting += 1;
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
queue = queue
|
|
84
|
+
.then(() => answer(line))
|
|
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);
|
|
94
|
+
});
|
|
95
|
+
if (signal?.aborted)
|
|
96
|
+
finish();
|
|
97
|
+
signal?.addEventListener("abort", () => (queue = queue.then(finish)), { once: true });
|
|
98
|
+
idle();
|
|
99
|
+
});
|
|
100
|
+
};
|
package/dist/cli/entry.d.ts
CHANGED
|
@@ -62,5 +62,7 @@ export interface CliEntry {
|
|
|
62
62
|
* output still flushes.
|
|
63
63
|
*/
|
|
64
64
|
export declare const startCli: (entry: CliEntry) => Promise<void>;
|
|
65
|
+
/** The first-run questions, before the command acts. A dry run writes nothing, and these write the shared config. */
|
|
66
|
+
export declare const firstRunAt: (entry: CliEntry, io: EntryIo, headless: (command: Command) => boolean) => (command: Command) => Promise<void>;
|
|
65
67
|
/** Opens `url` in the system browser, or in `browser` when given; resolves once the browser has started. */
|
|
66
68
|
export declare const openBrowser: (url: string, browser?: string, io?: Pick<EntryIo, "platform" | "spawn">) => Promise<void>;
|
package/dist/cli/entry.js
CHANGED
|
@@ -3,6 +3,7 @@ import { CliError, catchCrashes } from "@wirecat/cli-base";
|
|
|
3
3
|
import { envName, readOnlyLockOf } from "../ports/app.js";
|
|
4
4
|
import { ensureSqlite } from "../sqlite-runtime.js";
|
|
5
5
|
import { logVersion } from "./argv-log.js";
|
|
6
|
+
import { isCommandServer } from "./command-server-argv.js";
|
|
6
7
|
const processIo = () => ({
|
|
7
8
|
argv: process.argv,
|
|
8
9
|
env: process.env,
|
|
@@ -26,6 +27,10 @@ export const startCli = async (entry) => {
|
|
|
26
27
|
const args = io.argv.slice(2);
|
|
27
28
|
if (args.length === 1 && (args[0] === "--version" || args[0] === "-V"))
|
|
28
29
|
return printVersion(entry.app, io);
|
|
30
|
+
if (isCommandServer(args)) {
|
|
31
|
+
const { serveEntry } = await import("./command-server-entry.js");
|
|
32
|
+
return serveEntry(entry, io, { firstRunAt, commanderExit });
|
|
33
|
+
}
|
|
29
34
|
const tty = io.stdout.isTTY === true;
|
|
30
35
|
const release = catchCrashes({
|
|
31
36
|
cli: entry.app.command,
|
|
@@ -58,24 +63,7 @@ export const startCli = async (entry) => {
|
|
|
58
63
|
env: io.env,
|
|
59
64
|
tty,
|
|
60
65
|
signal: controller.signal,
|
|
61
|
-
atStart:
|
|
62
|
-
// The first-run questions write the shared config; a dry run writes nothing.
|
|
63
|
-
if (command.optsWithGlobals().dryRun === true)
|
|
64
|
-
return;
|
|
65
|
-
const [{ setupAtStart }, { commandPathOf }] = await Promise.all([
|
|
66
|
-
import("./first-run.js"),
|
|
67
|
-
import("./command-contract.js"),
|
|
68
|
-
]);
|
|
69
|
-
await setupAtStart({
|
|
70
|
-
command: entry.app.command,
|
|
71
|
-
env: io.env,
|
|
72
|
-
contentLanguages: entry.app.contentLanguages,
|
|
73
|
-
path: commandPathOf(command),
|
|
74
|
-
headless: headless(command),
|
|
75
|
-
readOnlyLock: readOnlyLockOf(entry.app, io.env),
|
|
76
|
-
input: io.stdin,
|
|
77
|
-
});
|
|
78
|
-
},
|
|
66
|
+
atStart: firstRunAt(entry, io, headless),
|
|
79
67
|
ask: async (question, command) => {
|
|
80
68
|
if (headless(command) || io.stdin.isTTY !== true)
|
|
81
69
|
return false;
|
|
@@ -120,6 +108,24 @@ export const startCli = async (entry) => {
|
|
|
120
108
|
else if (code !== undefined)
|
|
121
109
|
io.setExitCode(code);
|
|
122
110
|
};
|
|
111
|
+
/** The first-run questions, before the command acts. A dry run writes nothing, and these write the shared config. */
|
|
112
|
+
export const firstRunAt = (entry, io, headless) => async (command) => {
|
|
113
|
+
if (command.optsWithGlobals().dryRun === true)
|
|
114
|
+
return;
|
|
115
|
+
const [{ setupAtStart }, { commandPathOf }] = await Promise.all([
|
|
116
|
+
import("./first-run.js"),
|
|
117
|
+
import("./command-contract.js"),
|
|
118
|
+
]);
|
|
119
|
+
await setupAtStart({
|
|
120
|
+
command: entry.app.command,
|
|
121
|
+
env: io.env,
|
|
122
|
+
contentLanguages: entry.app.contentLanguages,
|
|
123
|
+
path: commandPathOf(command),
|
|
124
|
+
headless: headless(command),
|
|
125
|
+
readOnlyLock: readOnlyLockOf(entry.app, io.env),
|
|
126
|
+
input: io.stdin,
|
|
127
|
+
});
|
|
128
|
+
};
|
|
123
129
|
/**
|
|
124
130
|
* Answered before the program loads, which is most of a start: an agent asks for the version to learn whether the
|
|
125
131
|
* tool is there at all. Only the bare flag — anything else on the line goes through the program as before.
|
package/dist/cli/program.js
CHANGED
|
@@ -18,6 +18,7 @@ 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 { refuseInCommandServer } from "./command-server.js";
|
|
21
22
|
import { entityRows } from "./compact.js";
|
|
22
23
|
import { outputFor, provide } from "./context.js";
|
|
23
24
|
import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
|
|
@@ -308,6 +309,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
308
309
|
action.setOptionValue("dryRun", true);
|
|
309
310
|
refuseOfflineCommand(action, definition.app, flags.offline === true, flags.dryRun === true && localPreview);
|
|
310
311
|
const path = commandPathOf(action);
|
|
312
|
+
refuseInCommandServer(action, command);
|
|
311
313
|
const lock = readOnlyLockOf(definition.app, commandEnv);
|
|
312
314
|
const input = options.stdin ?? process.stdin;
|
|
313
315
|
// The first-run questions write the shared config; a dry run writes nothing.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type KeyringStore } from "@wirecat/cli-base";
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import type { AppIdentity } from "../ports/app.js";
|
|
4
|
+
import { type HarderSetting } from "../services/search-harder.js";
|
|
4
5
|
import { type Body } from "./envelope.js";
|
|
5
6
|
export interface HarderConsentsOptions {
|
|
6
7
|
env: () => NodeJS.ProcessEnv;
|
|
@@ -9,10 +10,12 @@ export interface HarderConsentsOptions {
|
|
|
9
10
|
output: (answer: Body, command: Command) => void;
|
|
10
11
|
diagnostic: (line: string) => void;
|
|
11
12
|
}
|
|
13
|
+
type Choice = Pick<HarderSetting, "provider" | "model" | "base_url">;
|
|
12
14
|
/** What the owner agrees to; a window can write the same text from the answer's fields. */
|
|
13
|
-
export declare const harderConsentWording: (command: string,
|
|
15
|
+
export declare const harderConsentWording: (command: string, chosen: Choice) => string;
|
|
14
16
|
/**
|
|
15
17
|
* The owner's consent that `search all --harder` may send a question and its hits to a hosted model. Off until
|
|
16
18
|
* `set … --yes`; with it, still only a search that asks with --harder sends anything.
|
|
17
19
|
*/
|
|
18
20
|
export declare const harderConsentsCommand: (app: AppIdentity, options: HarderConsentsOptions) => Command;
|
|
21
|
+
export {};
|
|
@@ -3,28 +3,45 @@ import { annotate } from "@wirecat/cli-base/commands";
|
|
|
3
3
|
import { Command } from "commander";
|
|
4
4
|
import { agentOf } from "../runs/run-context.js";
|
|
5
5
|
import { keyLookup, keyVariable } from "../services/enrichment.js";
|
|
6
|
-
import {
|
|
6
|
+
import { ENRICHMENT_PROVIDERS, enrichmentEndpoint, enrichmentPrice, isEnrichmentProvider, readEnrichmentSetting, } from "../services/enrichment-setting.js";
|
|
7
|
+
import { HARDER_CANDIDATES, HARDER_CHARS, HARDER_MODELS, readHarderSetting, writeHarderSetting, } from "../services/search-harder.js";
|
|
7
8
|
import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
|
|
8
9
|
import { itemOf } from "./envelope.js";
|
|
9
10
|
/** What the owner agrees to; a window can write the same text from the answer's fields. */
|
|
10
|
-
export const harderConsentWording = (command,
|
|
11
|
-
`date and up to ${HARDER_CHARS} characters of its text) to ${
|
|
12
|
-
`model ${model}, which puts the hits that answer it first.
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
export const harderConsentWording = (command, chosen) => `\`${command} search all --harder\` sends the question and its first ${HARDER_CANDIDATES} hits (each one's title, ` +
|
|
12
|
+
`date and up to ${HARDER_CHARS} characters of its text) to ${chosen.provider} ` +
|
|
13
|
+
`(${new URL(enrichmentEndpoint(chosen)).host}), model ${chosen.model}, which puts the hits that answer it first. ` +
|
|
14
|
+
"Only a search with --harder sends anything; with claude-haiku-5-5 one costs about $0.0003 and adds 1 to 2 seconds. " +
|
|
15
|
+
`\`${command} models search-consents revoke\` turns it off.`;
|
|
16
|
+
const state = (app, options, given) => {
|
|
15
17
|
const env = options.env();
|
|
16
18
|
const setting = readHarderSetting(env);
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
+
// Enrichment's choice is only proposed: this consent is the owner's own, given here.
|
|
20
|
+
const enrichment = setting === undefined && given === undefined ? readEnrichmentSetting(env) : undefined;
|
|
21
|
+
const chosen = given ??
|
|
22
|
+
setting ??
|
|
23
|
+
(enrichment
|
|
24
|
+
? {
|
|
25
|
+
provider: enrichment.provider,
|
|
26
|
+
model: enrichment.base_url === undefined ? HARDER_MODELS[enrichment.provider] : enrichment.model,
|
|
27
|
+
...(enrichment.base_url === undefined ? {} : { base_url: enrichment.base_url }),
|
|
28
|
+
}
|
|
29
|
+
: { provider: "anthropic", model: HARDER_MODELS.anthropic });
|
|
30
|
+
const found = keyLookup({ env, app, ...(options.keyring ? { keyring: options.keyring } : {}) }, chosen);
|
|
31
|
+
const price = enrichmentPrice(chosen.provider, chosen.model, chosen.base_url);
|
|
19
32
|
return {
|
|
20
33
|
on: setting !== undefined,
|
|
21
|
-
provider:
|
|
22
|
-
model: chosen,
|
|
23
|
-
endpoint:
|
|
34
|
+
provider: chosen.provider,
|
|
35
|
+
model: chosen.model,
|
|
36
|
+
endpoint: enrichmentEndpoint(chosen),
|
|
37
|
+
...(enrichment ? { proposed_from: "enrichment" } : {}),
|
|
24
38
|
consented_at: setting?.consented_at ?? null,
|
|
25
39
|
candidates: HARDER_CANDIDATES,
|
|
26
40
|
chars_per_hit: HARDER_CHARS,
|
|
27
|
-
|
|
41
|
+
usd_per_million: price
|
|
42
|
+
? { input: Math.round(price.input * 1e8) / 100, output: Math.round(price.output * 1e8) / 100 }
|
|
43
|
+
: null,
|
|
44
|
+
key: { present: found !== undefined, source: found?.source ?? null, env_var: keyVariable(chosen.provider) },
|
|
28
45
|
consent: harderConsentWording(app.command, chosen),
|
|
29
46
|
off_command: `${app.command} models search-consents revoke`,
|
|
30
47
|
};
|
|
@@ -42,29 +59,41 @@ export const harderConsentsCommand = (app, options) => {
|
|
|
42
59
|
});
|
|
43
60
|
grantsAuthority(annotate(consents.command("set"), {
|
|
44
61
|
effects: LOCAL_WRITE,
|
|
45
|
-
examples: [
|
|
62
|
+
examples: [
|
|
63
|
+
`${app.command} models search-consents set anthropic --yes`,
|
|
64
|
+
`${app.command} models search-consents set openai --base-url https://openrouter.ai/api/v1 --model deepseek/deepseek-chat`,
|
|
65
|
+
],
|
|
46
66
|
}))
|
|
47
67
|
.description("allow search all --harder to call the model; without --yes, say what it sends and change nothing")
|
|
48
|
-
.argument("<provider>",
|
|
49
|
-
.option("--model <model>",
|
|
68
|
+
.argument("<provider>", `the provider that receives the question and hits: ${ENRICHMENT_PROVIDERS.join(" or ")}`)
|
|
69
|
+
.option("--model <model>", `the provider's model; ${HARDER_MODELS.anthropic} or ${HARDER_MODELS.openai} if left out`)
|
|
70
|
+
.option("--base-url <url>", "the address of an OpenAI-compatible model API (OpenRouter…); needs --model")
|
|
50
71
|
.option("--yes", "agree that a --harder search sends its question and hits, and allow it")
|
|
51
72
|
.action(function (provider, given) {
|
|
52
|
-
if (provider
|
|
53
|
-
throw new CliError("validation_error", `search all --harder calls ${
|
|
73
|
+
if (!isEnrichmentProvider(provider))
|
|
74
|
+
throw new CliError("validation_error", `search all --harder calls ${ENRICHMENT_PROVIDERS.join(" or ")}, not ${provider}`);
|
|
75
|
+
// Another API's models have other names: a default from this list would be a guess.
|
|
76
|
+
if (given.baseUrl !== undefined && given.model === undefined)
|
|
77
|
+
throw new CliError("validation_error", "--base-url needs --model: name the model that API serves");
|
|
54
78
|
const env = options.env();
|
|
55
79
|
// An agent that turned this on would decide for the owner that his records may leave the machine.
|
|
56
80
|
if (agentOf(env) && given.yes)
|
|
57
81
|
throw new CliError("permission_error", "only the owner allows search all --harder, not an agent", {
|
|
58
82
|
reason: "search-harder.owner-only",
|
|
59
83
|
});
|
|
84
|
+
const chosen = {
|
|
85
|
+
provider,
|
|
86
|
+
model: given.model ?? HARDER_MODELS[provider],
|
|
87
|
+
...(given.baseUrl === undefined ? {} : { base_url: given.baseUrl }),
|
|
88
|
+
};
|
|
60
89
|
if (!given.yes) {
|
|
61
|
-
const now = state(app, options,
|
|
90
|
+
const now = state(app, options, chosen);
|
|
62
91
|
options.diagnostic(`${now.consent}\nNothing changed — add --yes to allow it.`);
|
|
63
92
|
options.output(itemOf({ ...now, changed: false }), this);
|
|
64
93
|
return;
|
|
65
94
|
}
|
|
66
|
-
writeHarderSetting(env, {
|
|
67
|
-
options.diagnostic(`search all --harder may now call ${
|
|
95
|
+
writeHarderSetting(env, { ...chosen, consented_at: new Date().toISOString() });
|
|
96
|
+
options.diagnostic(`search all --harder may now call ${provider} ${chosen.model}`);
|
|
68
97
|
options.output(itemOf({ ...state(app, options), changed: true }), this);
|
|
69
98
|
});
|
|
70
99
|
grantsAuthority(annotate(consents.command("revoke"), {
|
package/dist/crm/source.d.ts
CHANGED
|
@@ -68,6 +68,14 @@ export interface CrmSource {
|
|
|
68
68
|
* account's copy belongs to one user: another sign-in's user is refused.
|
|
69
69
|
*/
|
|
70
70
|
self?(): string | Promise<string>;
|
|
71
|
+
/**
|
|
72
|
+
* Which of the `unassigned` users this sign-in may count as nobody's, asked at every sync under `mine`; absent, all
|
|
73
|
+
* of them. The engine copies no deal or lead of a user left out, and names them with `message`, the CRM's reason.
|
|
74
|
+
*/
|
|
75
|
+
unassigned?(users: readonly string[]): Promise<{
|
|
76
|
+
kept: string[];
|
|
77
|
+
message?: string;
|
|
78
|
+
}>;
|
|
71
79
|
/** One kind's pipelines with their stages; a CRM whose leads have no pipelines answers one of its own making. */
|
|
72
80
|
pipelines(kind: DealKind, context?: CrmCallContext): Promise<CrmPipeline[]>;
|
|
73
81
|
/**
|
package/dist/crm/sync.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
|
|
|
50
50
|
export interface CrmSyncIssue {
|
|
51
51
|
/** `user`: the account's users and departments. */
|
|
52
52
|
kind: CrmKind | "user";
|
|
53
|
-
reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.not-reported" | "crm.pending-dropped";
|
|
53
|
+
reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped";
|
|
54
54
|
message: string;
|
|
55
55
|
externalId?: string;
|
|
56
56
|
}
|
package/dist/crm/sync.js
CHANGED
|
@@ -397,8 +397,13 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
397
397
|
`"config unset ${setting}" gives the copy to this sign-in`, { setting });
|
|
398
398
|
}
|
|
399
399
|
}
|
|
400
|
+
const listed = setting.mode === "mine" ? setting.also.map(normalCrmUserId) : [];
|
|
401
|
+
const allowed = self !== undefined && source.unassigned && listed.length && listed.every(isCrmUserId)
|
|
402
|
+
? await source.unassigned(listed)
|
|
403
|
+
: { kept: listed };
|
|
404
|
+
const dropped = listed.filter((id) => !allowed.kept.includes(id));
|
|
400
405
|
const scope = self !== undefined && setting.mode === "mine"
|
|
401
|
-
? { mode: "mine", self, also:
|
|
406
|
+
? { mode: "mine", self, also: listed.filter((id) => !dropped.includes(id)) }
|
|
402
407
|
: { mode: "all" };
|
|
403
408
|
const report = {
|
|
404
409
|
provider: source.provider,
|
|
@@ -412,6 +417,13 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
412
417
|
state: "complete",
|
|
413
418
|
progress: { requests: 0, saved: 0, steps: 0 },
|
|
414
419
|
};
|
|
420
|
+
if (dropped.length)
|
|
421
|
+
report.issues.push({
|
|
422
|
+
kind: "deal",
|
|
423
|
+
reason: "crm.unassigned-dropped",
|
|
424
|
+
message: `${crmSettingKey(account, "unassigned")} names user ${dropped.join(", ")}, not counted as nobody's: ` +
|
|
425
|
+
`${allowed.message ?? `${source.provider} refused them`}; their deals and leads are not copied`,
|
|
426
|
+
});
|
|
415
427
|
let steps = 0;
|
|
416
428
|
const run = {
|
|
417
429
|
source,
|
|
@@ -140,6 +140,7 @@ export declare const standingOf: (link: StandingFields, now: number) => Standing
|
|
|
140
140
|
/** A relationship a context or a traversal counts: the owner's, or a source's that still holds. */
|
|
141
141
|
export declare const isUsable: (standing: Standing) => boolean;
|
|
142
142
|
export declare const usableLink: (link: StandingFields, now: number) => boolean;
|
|
143
|
+
export declare const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
|
|
143
144
|
/**
|
|
144
145
|
* The `links` row aliased `alias` has no owner link overriding it (`metadata.overrides`, an owner's edit of a link a
|
|
145
146
|
* source reported): where one does, the override is the answer.
|
package/dist/domain/relations.js
CHANGED
|
@@ -129,11 +129,15 @@ export const standingOf = (link, now) => {
|
|
|
129
129
|
/** A relationship a context or a traversal counts: the owner's, or a source's that still holds. */
|
|
130
130
|
export const isUsable = (standing) => standing === "confirmed" || standing === "reported";
|
|
131
131
|
export const usableLink = (link, now) => isUsable(standingOf(link, now));
|
|
132
|
+
// links_relationship_key's WHERE, word for word: without it SQLite cannot use that partial index, picks
|
|
133
|
+
// (to_type, to_id) and reads every link of a busy end, such as a deal owner's, for each relationship (#2623).
|
|
134
|
+
export const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
|
|
132
135
|
/**
|
|
133
136
|
* The `links` row aliased `alias` has no owner link overriding it (`metadata.overrides`, an owner's edit of a link a
|
|
134
137
|
* source reported): where one does, the override is the answer.
|
|
135
138
|
*/
|
|
136
|
-
export const notOverriddenSql = (alias) => `NOT EXISTS (SELECT 1 FROM links override WHERE
|
|
139
|
+
export const notOverriddenSql = (alias) => `NOT EXISTS (SELECT 1 FROM links override WHERE ${KEYED} AND override.kind = ${alias}.kind ` +
|
|
140
|
+
`AND override.from_type = ${alias}.from_type ` +
|
|
137
141
|
`AND override.from_id = ${alias}.from_id AND override.to_type = ${alias}.to_type AND override.to_id = ${alias}.to_id ` +
|
|
138
142
|
`AND json_extract(override.metadata, '$.overrides') = ${alias}.id)`;
|
|
139
143
|
/** `usableLink` as SQL over the `links` row aliased `alias`; without `now` an end date is not checked. */
|
package/dist/errors/reasons.js
CHANGED
|
@@ -317,6 +317,7 @@ const OTHERS = [
|
|
|
317
317
|
validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
|
|
318
318
|
validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
|
|
319
319
|
validation("crm.narrowing-held", "the default scope mine would mark most of a kind's stored rows deleted; none is, until the owner sets the scope"),
|
|
320
|
+
validation("crm.unassigned-dropped", "the CRM does not let this sign-in count a user in unassigned as nobody's; that user's deals are not copied"),
|
|
320
321
|
validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
|
|
321
322
|
validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
|
|
322
323
|
validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
2
|
export declare const ENRICHMENT_PROVIDERS: readonly ["openai", "anthropic"];
|
|
3
3
|
export type EnrichmentProvider = (typeof ENRICHMENT_PROVIDERS)[number];
|
|
4
|
+
/** A hosted model the owner chose: the provider, its model and, for an OpenAI-compatible API, its address. */
|
|
5
|
+
export declare const MODEL_CHOICE: {
|
|
6
|
+
provider: v.PicklistSchema<readonly ["openai", "anthropic"], undefined>;
|
|
7
|
+
model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
|
|
8
|
+
base_url: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "use an HTTP/S endpoint without credentials, query or fragment">]>, undefined>;
|
|
9
|
+
};
|
|
4
10
|
declare const Setting: v.StrictObjectSchema<{
|
|
5
11
|
readonly provider: v.PicklistSchema<readonly ["openai", "anthropic"], undefined>;
|
|
6
12
|
readonly model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
|
|
@@ -9,10 +9,14 @@ const DEFAULT_BASE_URLS = {
|
|
|
9
9
|
openai: "https://api.openai.com/v1",
|
|
10
10
|
anthropic: "https://api.anthropic.com",
|
|
11
11
|
};
|
|
12
|
-
|
|
12
|
+
/** A hosted model the owner chose: the provider, its model and, for an OpenAI-compatible API, its address. */
|
|
13
|
+
export const MODEL_CHOICE = {
|
|
13
14
|
provider: v.picklist(ENRICHMENT_PROVIDERS),
|
|
14
15
|
model: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(200)),
|
|
15
16
|
base_url: v.optional(v.pipe(v.string(), v.check((value) => endpoint(value), "use an HTTP/S endpoint without credentials, query or fragment"))),
|
|
17
|
+
};
|
|
18
|
+
const Setting = v.strictObject({
|
|
19
|
+
...MODEL_CHOICE,
|
|
16
20
|
/** When the owner agreed that records go to this provider and endpoint; the setting exists only with it. */
|
|
17
21
|
consented_at: v.pipe(v.string(), v.isoTimestamp()),
|
|
18
22
|
});
|
package/dist/services/index.d.ts
CHANGED
|
@@ -215,7 +215,7 @@ export { RESOURCES_SEARCHED, type SearchAllFound, type SearchAllItem, type Searc
|
|
|
215
215
|
export { type MeetingSearchCoverage, type MeetingSearchCursor, type ResourceWithMeetings, type SearchAllIncludingMeetingsFound, type SearchAllIncludingMeetingsRequest, searchAllIncludingMeetings, } from "./search-all-deprecated.js";
|
|
216
216
|
export { type MeetingAccountCoverage, type MeetingSearchItem, MOST_HITS_PER_MEETING, } from "./search-all-meetings.js";
|
|
217
217
|
export { CATCH_UP_BOUNDS, type CatchUpOptions, type CatchUpResult, catchUpSearch, validateCatchUp, } from "./search-catchup.js";
|
|
218
|
-
export { HARDER_REASON_IDS, type HarderOptions, type HarderReasonId, type HarderResult, readHarderSetting, writeHarderSetting, } from "./search-harder.js";
|
|
218
|
+
export { HARDER_MODELS, HARDER_REASON_IDS, type HarderOptions, type HarderReasonId, type HarderResult, readHarderSetting, writeHarderSetting, } from "./search-harder.js";
|
|
219
219
|
export { accountsOfKind, groupLockOf, listContextOf, type SearchKind } from "./search-kind.js";
|
|
220
220
|
export type { SearchRefreshed, SyncOptions } from "./search-refresh.js";
|
|
221
221
|
export { SYNC_BOUNDS, SYNC_KEY } from "./search-refresh.js";
|
package/dist/services/index.js
CHANGED
|
@@ -166,7 +166,7 @@ export { RESOURCES_SEARCHED, searchAll, } from "./search-all.js";
|
|
|
166
166
|
export { searchAllIncludingMeetings, } from "./search-all-deprecated.js";
|
|
167
167
|
export { MOST_HITS_PER_MEETING, } from "./search-all-meetings.js";
|
|
168
168
|
export { CATCH_UP_BOUNDS, catchUpSearch, validateCatchUp, } from "./search-catchup.js";
|
|
169
|
-
export { HARDER_REASON_IDS, readHarderSetting, writeHarderSetting, } from "./search-harder.js";
|
|
169
|
+
export { HARDER_MODELS, HARDER_REASON_IDS, readHarderSetting, writeHarderSetting, } from "./search-harder.js";
|
|
170
170
|
export { accountsOfKind, groupLockOf, listContextOf } from "./search-kind.js";
|
|
171
171
|
export { SYNC_BOUNDS, SYNC_KEY } from "./search-refresh.js";
|
|
172
172
|
export { SERVER_BOUNDS, SERVER_SEARCH_KEY, } from "./server-search.js";
|
|
@@ -396,7 +396,8 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
396
396
|
now: request.now ?? Date.now(),
|
|
397
397
|
...(command === undefined ? {} : { command }),
|
|
398
398
|
};
|
|
399
|
-
|
|
399
|
+
// The model reads the question as typed, not escaped for the query parser.
|
|
400
|
+
const done = await reorderHarder(asked.text, ordered, { ...asking, laterPage: offset > 0 });
|
|
400
401
|
ordered = done.items;
|
|
401
402
|
harder = done.harder;
|
|
402
403
|
}
|
|
@@ -2,15 +2,19 @@ import { type KeyringStore } from "@wirecat/cli-base";
|
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
import { type ModelAdapter } from "../models/index.js";
|
|
4
4
|
import type { AppIdentity } from "../ports/app.js";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
import { type EnrichmentProvider } from "./enrichment-setting.js";
|
|
6
|
+
/**
|
|
7
|
+
* Each provider's model when the owner names none: small and fast for a short answer. gpt-4o-mini, not a cheaper
|
|
8
|
+
* reasoning model, because the OpenAI adapter cannot turn reasoning down (pricing read 2026-11-09).
|
|
9
|
+
*/
|
|
10
|
+
export declare const HARDER_MODELS: Readonly<Record<EnrichmentProvider, string>>;
|
|
8
11
|
/** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
|
|
9
12
|
export declare const HARDER_CANDIDATES = 30;
|
|
10
13
|
export declare const HARDER_CHARS = 400;
|
|
11
14
|
declare const Setting: v.StrictObjectSchema<{
|
|
12
|
-
readonly provider: v.
|
|
15
|
+
readonly provider: v.PicklistSchema<readonly ["openai", "anthropic"], undefined>;
|
|
13
16
|
readonly model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
|
|
17
|
+
readonly base_url: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "use an HTTP/S endpoint without credentials, query or fragment">]>, undefined>;
|
|
14
18
|
/** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
|
|
15
19
|
readonly consented_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, undefined>]>;
|
|
16
20
|
}, undefined>;
|
|
@@ -25,6 +29,8 @@ export interface HarderResult {
|
|
|
25
29
|
applied: boolean;
|
|
26
30
|
provider: string;
|
|
27
31
|
model: string;
|
|
32
|
+
/** The API the question went to, or would have. */
|
|
33
|
+
endpoint: string;
|
|
28
34
|
/** Hits sent to the model; 0 when nothing left this machine. */
|
|
29
35
|
sent: number;
|
|
30
36
|
cost_usd: number | null;
|
|
@@ -47,16 +53,36 @@ export interface HarderHit {
|
|
|
47
53
|
timestamp: string | null;
|
|
48
54
|
text: string;
|
|
49
55
|
}
|
|
56
|
+
type Asking = HarderOptions & {
|
|
57
|
+
env: NodeJS.ProcessEnv;
|
|
58
|
+
now: number;
|
|
59
|
+
command?: string;
|
|
60
|
+
};
|
|
61
|
+
/** The consent and key a call needs, or why nothing may be sent. */
|
|
62
|
+
export type HarderAccess = {
|
|
63
|
+
ready: true;
|
|
64
|
+
provider: EnrichmentProvider;
|
|
65
|
+
model: string;
|
|
66
|
+
endpoint: string;
|
|
67
|
+
custom: boolean;
|
|
68
|
+
key?: string;
|
|
69
|
+
} | {
|
|
70
|
+
ready: false;
|
|
71
|
+
provider: string;
|
|
72
|
+
model: string;
|
|
73
|
+
endpoint: string;
|
|
74
|
+
reason_id: HarderReasonId;
|
|
75
|
+
reason: string;
|
|
76
|
+
};
|
|
77
|
+
export declare const harderAccess: ({ env, command, ...options }: Asking) => HarderAccess;
|
|
50
78
|
/**
|
|
51
79
|
* `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
|
|
52
80
|
* first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
|
|
53
81
|
* key nothing is sent.
|
|
54
82
|
*/
|
|
55
|
-
export declare const reorderHarder: <T extends HarderHit>(question: string, hits: readonly T[], {
|
|
56
|
-
env: NodeJS.ProcessEnv;
|
|
57
|
-
now: number;
|
|
58
|
-
command?: string;
|
|
83
|
+
export declare const reorderHarder: <T extends HarderHit>(question: string, hits: readonly T[], { laterPage, access: given, ...asking }: Asking & {
|
|
59
84
|
laterPage?: boolean;
|
|
85
|
+
access?: HarderAccess;
|
|
60
86
|
}) => Promise<{
|
|
61
87
|
items: T[];
|
|
62
88
|
harder: HarderResult;
|
|
@@ -3,18 +3,22 @@ import * as v from "valibot";
|
|
|
3
3
|
import { modelGateway } from "../models/index.js";
|
|
4
4
|
import { readSharedSection, writeSharedSection } from "../store/shared-config.js";
|
|
5
5
|
import { keyLookup, keyVariable } from "./enrichment.js";
|
|
6
|
-
import { costOf, enrichmentSettingPath } from "./enrichment-setting.js";
|
|
6
|
+
import { costOf, enrichmentEndpoint, enrichmentSettingPath, MODEL_CHOICE, } from "./enrichment-setting.js";
|
|
7
7
|
const SECTION = "search_harder";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Each provider's model when the owner names none: small and fast for a short answer. gpt-4o-mini, not a cheaper
|
|
10
|
+
* reasoning model, because the OpenAI adapter cannot turn reasoning down (pricing read 2026-11-09).
|
|
11
|
+
*/
|
|
12
|
+
export const HARDER_MODELS = {
|
|
13
|
+
anthropic: "claude-haiku-5-5",
|
|
14
|
+
openai: "gpt-4o-mini",
|
|
15
|
+
};
|
|
11
16
|
/** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
|
|
12
17
|
export const HARDER_CANDIDATES = 30;
|
|
13
18
|
export const HARDER_CHARS = 400;
|
|
14
19
|
const TIMEOUT_MS = 5_000;
|
|
15
20
|
const Setting = v.strictObject({
|
|
16
|
-
|
|
17
|
-
model: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(200)),
|
|
21
|
+
...MODEL_CHOICE,
|
|
18
22
|
/** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
|
|
19
23
|
consented_at: v.pipe(v.string(), v.isoTimestamp()),
|
|
20
24
|
});
|
|
@@ -49,6 +53,8 @@ const PROMPT = "Today is {as_of}. A person searches their own archive of message
|
|
|
49
53
|
"Question: {question}\n\n" +
|
|
50
54
|
"Which records help answer the question? List their numbers, most useful first, at most ten; an empty list if " +
|
|
51
55
|
"none does.";
|
|
56
|
+
// Only Anthropic takes the schema; another provider is told the shape, and its answer is read leniently.
|
|
57
|
+
const JSON_SHAPE = '\n\nAnswer with JSON only, in the form {"records": [numbers]}.';
|
|
52
58
|
const FORMAT = {
|
|
53
59
|
type: "json_schema",
|
|
54
60
|
schema: {
|
|
@@ -59,10 +65,23 @@ const FORMAT = {
|
|
|
59
65
|
},
|
|
60
66
|
};
|
|
61
67
|
const Reply = v.object({ records: v.array(v.pipe(v.number(), v.integer())) });
|
|
68
|
+
/** The JSON in an answer, also when a model wraps it in a code block or a sentence. */
|
|
69
|
+
const jsonOf = (text) => {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(text);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
const start = text.indexOf("{");
|
|
75
|
+
const end = text.lastIndexOf("}");
|
|
76
|
+
if (start < 0 || end <= start)
|
|
77
|
+
throw new Error("no JSON in the answer");
|
|
78
|
+
return JSON.parse(text.slice(start, end + 1));
|
|
79
|
+
}
|
|
80
|
+
};
|
|
62
81
|
const recordLine = (hit, i) => `[${i}] (${hit.timestamp?.slice(0, 10) ?? "undated"}) ${`${hit.title ? `${hit.title}\n` : ""}${hit.text.slice(0, HARDER_CHARS)}`.replace(/\s*\n\s*/g, " ")}`;
|
|
63
82
|
const REASON_TEXT = {
|
|
64
83
|
"harder.no-consent": "the owner has not agreed to send searches to a hosted model",
|
|
65
|
-
"harder.no-key": "no
|
|
84
|
+
"harder.no-key": "no key for the provider",
|
|
66
85
|
"harder.bad-setting": "the search_harder setting cannot be read; nothing was sent",
|
|
67
86
|
"harder.later-page": "--harder reorders the first page only; nothing was sent",
|
|
68
87
|
"harder.too-few": "fewer than two hits to reorder; nothing was sent",
|
|
@@ -86,109 +105,160 @@ const reasonOf = (error, timedOut) => {
|
|
|
86
105
|
return "harder.rate-limited";
|
|
87
106
|
return "harder.error";
|
|
88
107
|
};
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
export const
|
|
95
|
-
const started = Date.now();
|
|
108
|
+
const UNSET = {
|
|
109
|
+
provider: "anthropic",
|
|
110
|
+
model: HARDER_MODELS.anthropic,
|
|
111
|
+
endpoint: enrichmentEndpoint({ provider: "anthropic" }),
|
|
112
|
+
};
|
|
113
|
+
export const harderAccess = ({ env, command, ...options }) => {
|
|
96
114
|
let setting;
|
|
97
|
-
let unreadable;
|
|
98
115
|
try {
|
|
99
116
|
setting = readHarderSetting(env);
|
|
100
117
|
}
|
|
101
118
|
catch (error) {
|
|
102
|
-
unreadable = error instanceof CliError ? error.message : REASON_TEXT["harder.bad-setting"];
|
|
119
|
+
const unreadable = error instanceof CliError ? error.message : REASON_TEXT["harder.bad-setting"];
|
|
120
|
+
return { ready: false, ...UNSET, reason_id: "harder.bad-setting", reason: `${unreadable}; nothing was sent` };
|
|
103
121
|
}
|
|
104
|
-
const model = setting?.model ?? DEFAULT_HARDER_MODEL;
|
|
105
|
-
const plain = (reason_id, extra = {}, reason = REASON_TEXT[reason_id]) => ({
|
|
106
|
-
items: [...hits],
|
|
107
|
-
harder: {
|
|
108
|
-
applied: false,
|
|
109
|
-
provider: HARDER_PROVIDER,
|
|
110
|
-
model,
|
|
111
|
-
sent: 0,
|
|
112
|
-
cost_usd: 0,
|
|
113
|
-
ms: Date.now() - started,
|
|
114
|
-
...extra,
|
|
115
|
-
reason,
|
|
116
|
-
reason_id,
|
|
117
|
-
},
|
|
118
|
-
});
|
|
119
|
-
if (laterPage)
|
|
120
|
-
return plain("harder.later-page");
|
|
121
|
-
if (unreadable !== undefined)
|
|
122
|
-
return plain("harder.bad-setting", {}, `${unreadable}; nothing was sent`);
|
|
123
122
|
const tool = command ?? "memo";
|
|
124
123
|
if (!setting)
|
|
125
|
-
return
|
|
126
|
-
|
|
124
|
+
return {
|
|
125
|
+
ready: false,
|
|
126
|
+
...UNSET,
|
|
127
|
+
reason_id: "harder.no-consent",
|
|
128
|
+
reason: `${REASON_TEXT["harder.no-consent"]}: \`${tool} models search-consents set <provider> --yes\`; nothing was sent`,
|
|
129
|
+
};
|
|
130
|
+
const chosen = {
|
|
131
|
+
provider: setting.provider,
|
|
132
|
+
model: setting.model,
|
|
133
|
+
endpoint: enrichmentEndpoint(setting),
|
|
134
|
+
custom: setting.base_url !== undefined,
|
|
135
|
+
};
|
|
136
|
+
let key;
|
|
127
137
|
try {
|
|
128
|
-
|
|
138
|
+
key = keyLookup({ env, ...options }, setting)?.key;
|
|
129
139
|
}
|
|
130
140
|
catch {
|
|
131
|
-
return
|
|
141
|
+
return {
|
|
142
|
+
ready: false,
|
|
143
|
+
...chosen,
|
|
144
|
+
reason_id: "harder.error",
|
|
145
|
+
reason: `the ${setting.provider} key could not be read; nothing was sent`,
|
|
146
|
+
};
|
|
132
147
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
148
|
+
// A server of the owner's own may need no key; the public API would answer 401 only after the question left.
|
|
149
|
+
if (key === undefined && !chosen.custom)
|
|
150
|
+
return {
|
|
151
|
+
ready: false,
|
|
152
|
+
...chosen,
|
|
153
|
+
reason_id: "harder.no-key",
|
|
154
|
+
reason: `no ${setting.provider} key: \`${tool} models keys set ${setting.provider}\` or set ${keyVariable(setting.provider)}; nothing was sent`,
|
|
155
|
+
};
|
|
156
|
+
return { ready: true, ...chosen, ...(key === undefined ? {} : { key }) };
|
|
157
|
+
};
|
|
158
|
+
/** One call to the model under the 5 s limit; a failure comes back as its reason, never thrown. */
|
|
159
|
+
const ask = async (access, options, request) => {
|
|
138
160
|
const limit = new AbortController();
|
|
139
161
|
const timer = setTimeout(() => limit.abort(), options.timeoutMs ?? TIMEOUT_MS);
|
|
140
162
|
const gateway = modelGateway({
|
|
141
|
-
resolve: () => ({ provider:
|
|
142
|
-
consent: (_request, chosen) => chosen.provider ===
|
|
143
|
-
key: () =>
|
|
163
|
+
resolve: () => ({ provider: access.provider, model: access.model, baseUrl: access.endpoint }),
|
|
164
|
+
consent: (_request, chosen) => chosen.provider === access.provider && chosen.baseUrl === access.endpoint,
|
|
165
|
+
key: () => access.key,
|
|
144
166
|
signal: limit.signal,
|
|
145
167
|
...(options.adapters ? { adapters: options.adapters } : {}),
|
|
146
168
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
147
169
|
});
|
|
148
|
-
const
|
|
170
|
+
const { format, ...rest } = request;
|
|
171
|
+
// Each adapter refuses options it does not know, so Anthropic's never reach another provider.
|
|
172
|
+
const settings = access.provider === "anthropic"
|
|
173
|
+
? { thinking: { type: "disabled" }, output_config: { effort: "low", ...(format ? { format } : {}) } }
|
|
174
|
+
: access.custom
|
|
175
|
+
? undefined
|
|
176
|
+
: { temperature: 0, ...(format ? { response_format: { type: "json_object" } } : {}) };
|
|
149
177
|
try {
|
|
150
178
|
const answer = await gateway.complete({
|
|
151
|
-
|
|
152
|
-
prompt:
|
|
153
|
-
|
|
154
|
-
.replace("{question}", question),
|
|
155
|
-
data: candidates.map(recordLine).join("\n"),
|
|
156
|
-
maxTokens: 300,
|
|
157
|
-
options: { thinking: { type: "disabled" }, output_config: { effort: "low", format: FORMAT } },
|
|
179
|
+
...rest,
|
|
180
|
+
...(format && access.provider !== "anthropic" ? { prompt: `${rest.prompt}${JSON_SHAPE}` } : {}),
|
|
181
|
+
...(settings ? { options: settings } : {}),
|
|
158
182
|
});
|
|
159
183
|
const cost = costOf(answer.usage ?? { input: answer.tokens, output: 0 }, {
|
|
160
|
-
provider:
|
|
161
|
-
model:
|
|
184
|
+
provider: access.provider,
|
|
185
|
+
model: access.model,
|
|
186
|
+
...(access.custom ? { base_url: access.endpoint } : {}),
|
|
162
187
|
});
|
|
163
|
-
|
|
164
|
-
try {
|
|
165
|
-
picked = v.parse(Reply, JSON.parse(answer.text)).records;
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
return plain("harder.bad-reply", { ...sent, cost_usd: cost });
|
|
169
|
-
}
|
|
170
|
-
const first = [...new Set(picked.filter((i) => i >= 0 && i < candidates.length))];
|
|
171
|
-
const chosen = new Set(first);
|
|
172
|
-
return {
|
|
173
|
-
items: [
|
|
174
|
-
...first.map((i) => candidates[i]),
|
|
175
|
-
...candidates.filter((_, i) => !chosen.has(i)),
|
|
176
|
-
...hits.slice(HARDER_CANDIDATES),
|
|
177
|
-
],
|
|
178
|
-
harder: {
|
|
179
|
-
applied: true,
|
|
180
|
-
provider: HARDER_PROVIDER,
|
|
181
|
-
model: setting.model,
|
|
182
|
-
...sent,
|
|
183
|
-
cost_usd: cost,
|
|
184
|
-
ms: Date.now() - started,
|
|
185
|
-
},
|
|
186
|
-
};
|
|
188
|
+
return { text: answer.text, cost };
|
|
187
189
|
}
|
|
188
190
|
catch (error) {
|
|
189
|
-
return
|
|
191
|
+
return { reason_id: reasonOf(error, limit.signal.aborted) };
|
|
190
192
|
}
|
|
191
193
|
finally {
|
|
192
194
|
clearTimeout(timer);
|
|
193
195
|
}
|
|
194
196
|
};
|
|
197
|
+
/**
|
|
198
|
+
* `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
|
|
199
|
+
* first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
|
|
200
|
+
* key nothing is sent.
|
|
201
|
+
*/
|
|
202
|
+
export const reorderHarder = async (question, hits, { laterPage, access: given, ...asking }) => {
|
|
203
|
+
const started = Date.now();
|
|
204
|
+
const access = laterPage ? undefined : (given ?? harderAccess(asking));
|
|
205
|
+
const plain = (reason_id, extra = {}, reason = REASON_TEXT[reason_id]) => ({
|
|
206
|
+
items: [...hits],
|
|
207
|
+
harder: {
|
|
208
|
+
applied: false,
|
|
209
|
+
provider: (access ?? UNSET).provider,
|
|
210
|
+
model: (access ?? UNSET).model,
|
|
211
|
+
endpoint: (access ?? UNSET).endpoint,
|
|
212
|
+
sent: 0,
|
|
213
|
+
cost_usd: 0,
|
|
214
|
+
ms: Date.now() - started,
|
|
215
|
+
...extra,
|
|
216
|
+
reason,
|
|
217
|
+
reason_id,
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
if (!access)
|
|
221
|
+
return plain("harder.later-page");
|
|
222
|
+
if (!access.ready)
|
|
223
|
+
return plain(access.reason_id, {}, access.reason);
|
|
224
|
+
const candidates = hits.slice(0, HARDER_CANDIDATES);
|
|
225
|
+
if (candidates.length < 2)
|
|
226
|
+
return plain("harder.too-few");
|
|
227
|
+
const sent = { sent: candidates.length };
|
|
228
|
+
const answer = await ask(access, asking, {
|
|
229
|
+
purpose: "search-harder",
|
|
230
|
+
prompt: PROMPT.replace("{as_of}", new Date(asking.now).toISOString().slice(0, 10))
|
|
231
|
+
.replace("{n}", String(candidates.length))
|
|
232
|
+
.replace("{question}", () => question),
|
|
233
|
+
data: candidates.map(recordLine).join("\n"),
|
|
234
|
+
maxTokens: 300,
|
|
235
|
+
format: FORMAT,
|
|
236
|
+
});
|
|
237
|
+
if ("reason_id" in answer)
|
|
238
|
+
return plain(answer.reason_id, { ...sent, cost_usd: null });
|
|
239
|
+
let picked;
|
|
240
|
+
try {
|
|
241
|
+
picked = v.parse(Reply, jsonOf(answer.text)).records;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return plain("harder.bad-reply", { ...sent, cost_usd: answer.cost });
|
|
245
|
+
}
|
|
246
|
+
const first = [...new Set(picked.filter((i) => i >= 0 && i < candidates.length))];
|
|
247
|
+
const chosen = new Set(first);
|
|
248
|
+
return {
|
|
249
|
+
items: [
|
|
250
|
+
...first.map((i) => candidates[i]),
|
|
251
|
+
...candidates.filter((_, i) => !chosen.has(i)),
|
|
252
|
+
...hits.slice(HARDER_CANDIDATES),
|
|
253
|
+
],
|
|
254
|
+
harder: {
|
|
255
|
+
applied: true,
|
|
256
|
+
provider: access.provider,
|
|
257
|
+
model: access.model,
|
|
258
|
+
endpoint: access.endpoint,
|
|
259
|
+
...sent,
|
|
260
|
+
cost_usd: answer.cost,
|
|
261
|
+
ms: Date.now() - started,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
};
|
package/dist/store/driver.d.ts
CHANGED
|
@@ -44,7 +44,11 @@ export type OpenDatabase = (path: string) => CacheDatabase;
|
|
|
44
44
|
* a writer that finds the database busy fails immediately instead of waiting the moment out.
|
|
45
45
|
*
|
|
46
46
|
* `foreign_keys` is off by default in SQLite, which surprises everyone once.
|
|
47
|
+
*
|
|
48
|
+
* Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
|
|
49
|
+
* sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
|
|
47
50
|
*/
|
|
48
|
-
export declare const
|
|
51
|
+
export declare const JOURNAL_SIZE_LIMIT: number;
|
|
52
|
+
export declare const PRAGMAS = "\n PRAGMA busy_timeout = 5000;\n PRAGMA journal_mode = WAL;\n PRAGMA journal_size_limit = 67108864;\n PRAGMA foreign_keys = ON;\n";
|
|
49
53
|
/** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
|
|
50
54
|
export declare const isQueryOnly: (database: CacheDatabase) => boolean;
|
package/dist/store/driver.js
CHANGED
|
@@ -30,10 +30,15 @@ export const beforeTimeLimit = (until) => {
|
|
|
30
30
|
* a writer that finds the database busy fails immediately instead of waiting the moment out.
|
|
31
31
|
*
|
|
32
32
|
* `foreign_keys` is off by default in SQLite, which surprises everyone once.
|
|
33
|
+
*
|
|
34
|
+
* Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
|
|
35
|
+
* sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
|
|
33
36
|
*/
|
|
37
|
+
export const JOURNAL_SIZE_LIMIT = 64 * 1024 * 1024;
|
|
34
38
|
export const PRAGMAS = `
|
|
35
39
|
PRAGMA busy_timeout = 5000;
|
|
36
40
|
PRAGMA journal_mode = WAL;
|
|
41
|
+
PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT};
|
|
37
42
|
PRAGMA foreign_keys = ON;
|
|
38
43
|
`;
|
|
39
44
|
/** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
|
|
@@ -13,7 +13,7 @@ import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
|
|
|
13
13
|
import { deleteDocumentRow, forgetEvidenceToRow } from "./evidence-signature.js";
|
|
14
14
|
import { PREFERRED_FILE, syncFile } from "./files.js";
|
|
15
15
|
import { importedDocumentWhere } from "./imported-documents.js";
|
|
16
|
-
import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
|
|
16
|
+
import { LINK_KINDS, LINK_ORIGINS, linkKind, RELATION_KINDS } from "./link-kinds.js";
|
|
17
17
|
import { reviewLink } from "./link-reviews.js";
|
|
18
18
|
import { linkOf } from "./link-row.js";
|
|
19
19
|
export { linkOf, thingRef } from "./link-row.js";
|
|
@@ -26,6 +26,7 @@ import { thingOf } from "./things.js";
|
|
|
26
26
|
import { write } from "./transaction.js";
|
|
27
27
|
export const NOTE_FORMATS = ["obsidian", "markdown"];
|
|
28
28
|
export { LINK_ORIGINS } from "./link-kinds.js";
|
|
29
|
+
const RELATIONSHIPS = RELATION_KINDS.map(linkKind).join(", ");
|
|
29
30
|
const iso = (value) => new Date(Number(value)).toISOString();
|
|
30
31
|
const optionalIso = (value) => (value == null ? null : iso(value));
|
|
31
32
|
/** What a link's written target is matched by: case, accents and a leading `@` do not count. */
|
|
@@ -648,7 +649,14 @@ export const notesStoreOver = (context) => {
|
|
|
648
649
|
replaceFileLinks: async (documentId, links) => write(database, () => {
|
|
649
650
|
const id = Number(documentRow(documentId).id);
|
|
650
651
|
database.prepare("DELETE FROM links WHERE from_type = 'document' AND from_id = ? AND source = 'file'").run(id);
|
|
651
|
-
|
|
652
|
+
const written = links.map((link) => insertLink(context, { ...link, from: `document:${id}`, origin: "file" }));
|
|
653
|
+
// What a file's source says, such as a Drive owner, is reported by its account, not waiting for review.
|
|
654
|
+
database
|
|
655
|
+
.prepare("UPDATE links SET account_id = (SELECT account_id FROM documents WHERE id = ?) WHERE from_type = 'document' " +
|
|
656
|
+
`AND from_id = ? AND source = 'file' AND confirmed = 0 AND account_id IS NULL AND kind IN (${RELATIONSHIPS})`)
|
|
657
|
+
.run(id, id);
|
|
658
|
+
const reread = database.prepare("SELECT * FROM links WHERE id = ?");
|
|
659
|
+
return written.map((link) => linkOf(database, reread.get(Number(link.id))));
|
|
652
660
|
}),
|
|
653
661
|
linkMessages: async ({ documents, since }) => {
|
|
654
662
|
const after = since === undefined ? null : Date.parse(since);
|
|
@@ -15,16 +15,19 @@ const accountKeys = (database, ids) => {
|
|
|
15
15
|
? { provider: "notes", account: String(id) }
|
|
16
16
|
: { provider: String(provider), account: String(external_id) });
|
|
17
17
|
};
|
|
18
|
-
|
|
18
|
+
// Per connection: a long-lived process (`commands --serve`) outlives a migration another CLI runs on the store.
|
|
19
|
+
const hasAccountColumn = new WeakMap();
|
|
19
20
|
const accountColumnIn = (database, table) => {
|
|
20
|
-
const
|
|
21
|
+
const tables = hasAccountColumn.get(database) ?? new Map();
|
|
22
|
+
hasAccountColumn.set(database, tables);
|
|
23
|
+
const known = tables.get(table);
|
|
21
24
|
if (known !== undefined)
|
|
22
25
|
return known;
|
|
23
26
|
const has = database
|
|
24
27
|
.prepare(`PRAGMA table_info(${table})`)
|
|
25
28
|
.all()
|
|
26
29
|
.some((column) => column.name === "account_id");
|
|
27
|
-
|
|
30
|
+
tables.set(table, has);
|
|
28
31
|
return has;
|
|
29
32
|
};
|
|
30
33
|
const ids = (rows) => rows.flatMap(({ account_id }) => (account_id === null || account_id === undefined ? [] : [Number(account_id)]));
|
|
@@ -68,7 +68,6 @@ export interface RelationsStore {
|
|
|
68
68
|
*/
|
|
69
69
|
syncReported(key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, options?: ReportedOptions): Promise<ReportedSync>;
|
|
70
70
|
}
|
|
71
|
-
export declare const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
|
|
72
71
|
/** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
|
|
73
72
|
export declare const syncReportedIn: (context: StoreContext, key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, { source, by, onOutcome }?: ReportedOptions) => ReportedSync;
|
|
74
73
|
export declare const relationsStoreOver: (context: StoreContext) => RelationsStore;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import { checkEnds, isSymmetric } from "../../domain/relations.js";
|
|
2
|
+
import { checkEnds, isSymmetric, KEYED } from "../../domain/relations.js";
|
|
3
3
|
import { accountPk } from "./accounts.js";
|
|
4
4
|
import { crmLinkMode } from "./crm-settings.js";
|
|
5
5
|
import { linkKind } from "./link-kinds.js";
|
|
@@ -9,9 +9,6 @@ import { checkStoredRole } from "./relation-roles.js";
|
|
|
9
9
|
import { referenceOfThing, thingOf } from "./things.js";
|
|
10
10
|
import { write } from "./transaction.js";
|
|
11
11
|
const keyOf = (kind, fromType, fromId, toType, toId, role) => `${String(kind)}|${String(fromType)}:${String(fromId)}|${String(toType)}:${String(toId)}|${role == null ? "" : String(role)}`;
|
|
12
|
-
// links_relationship_key's WHERE, word for word: without it SQLite cannot use that partial index, picks
|
|
13
|
-
// (to_type, to_id) and reads every link of a busy end, such as a deal owner's, for each relationship (#2623).
|
|
14
|
-
export const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
|
|
15
12
|
const metadataOf = (relation) => relation.metadata && Object.keys(relation.metadata).length ? JSON.stringify(relation.metadata) : null;
|
|
16
13
|
/** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
|
|
17
14
|
export const syncReportedIn = (context, key, relationships, scope, { source = "import", by = { bot: key.provider, kind: "rule" }, onOutcome } = {}) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.622.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",
|