@wirecat/cli-core 0.620.0 → 0.621.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 CHANGED
@@ -5,6 +5,36 @@ 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.621.0 — 09.11.2026
9
+
10
+ ### Added
11
+
12
+ - A CRM source may say which users in `crm.<provider>:<account>.unassigned` its sign-in may count as nobody's
13
+ (`CrmSource.unassigned`), asked at every sync under `scope mine`. The sync copies no deal or lead of a user it
14
+ leaves out, narrows the copy to match, and names them in an issue with the reason `crm.unassigned-dropped`.
15
+ - **`models search-consents set` takes `openai`, `anthropic` or an OpenAI-compatible API (`--base-url`, such as
16
+ OpenRouter).** Each provider has its own default model for `search all --harder` (`claude-haiku-5-5`,
17
+ `gpt-4o-mini`); another API needs `--model`. `show` proposes enrichment's provider and model when the owner chose
18
+ one there, but never gives this consent by itself. The answer's `harder` field names the `endpoint` too. Anthropic's
19
+ `thinking` and `output_config` go to Anthropic only; OpenAI gets its JSON mode, and any reply wrapped in a code block
20
+ is still read. See
21
+ [AI providers, "Search harder"](docs/search/ai-providers.md#search-harder-a-hosted-model-reorders-search-all-off-by-default).
22
+
23
+ ### Fixed
24
+
25
+ - **A file's own relationship, such as a Drive document's owner, no longer waits for review.** `replaceFileLinks`
26
+ writes an unconfirmed relationship from a document with the document's account, so it is `reported` (what the
27
+ source says) instead of `proposed`. Before, every Drive document's owner and last editor stood in the owner's review
28
+ list. Links the file states that are not relationships, and the owner's own links, are unchanged. A source re-writes
29
+ its links on its next import: `drive <profile> catalog import --offline` moves the stored ones.
30
+ - **`search all --harder` sends the question as typed.** It sent the query parser's escaped copy (`deposit\?`), and a
31
+ `$&` in a question was read as a replacement pattern.
32
+ - **`relationships list include:ended` answers in about 0.2 seconds instead of minutes on a store with a busy
33
+ person.** The check for an owner's override of a link looked the override up by the link's target, so a person on
34
+ 25,857 deals read every one of those links again for each relationship (325 seconds on a 108,000-link store). It now
35
+ looks it up by the relationship's own key. The same check runs in the deal's people, a thing's relationships and a
36
+ meeting's preparation, so those get faster too.
37
+
8
38
  ## 0.620.0 — 09.11.2026
9
39
 
10
40
  ### Added
@@ -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, model: string) => 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 { DEFAULT_HARDER_MODEL, HARDER_CANDIDATES, HARDER_CHARS, HARDER_ENDPOINT, HARDER_PROVIDER, readHarderSetting, writeHarderSetting, } from "../services/search-harder.js";
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, model) => `\`${command} search all --harder\` sends the question and its first ${HARDER_CANDIDATES} hits (each one's title, ` +
11
- `date and up to ${HARDER_CHARS} characters of its text) to ${HARDER_PROVIDER} (${new URL(HARDER_ENDPOINT).host}), ` +
12
- `model ${model}, which puts the hits that answer it first. Only a search with --harder sends anything; one costs ` +
13
- `about $0.0004 with claude-haiku-5-5 and adds 1 to 2 seconds. \`${command} models search-consents revoke\` turns it off.`;
14
- const state = (app, options, model) => {
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
- const found = keyLookup({ env, app, ...(options.keyring ? { keyring: options.keyring } : {}) }, { provider: HARDER_PROVIDER });
18
- const chosen = model ?? setting?.model ?? DEFAULT_HARDER_MODEL;
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: HARDER_PROVIDER,
22
- model: chosen,
23
- endpoint: HARDER_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
- key: { present: found !== undefined, source: found?.source ?? null, env_var: keyVariable(HARDER_PROVIDER) },
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: [`${app.command} models search-consents set anthropic --yes`],
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>", "the provider that receives the question and hits: anthropic")
49
- .option("--model <model>", "the provider's model name", DEFAULT_HARDER_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 !== HARDER_PROVIDER)
53
- throw new CliError("validation_error", `search all --harder calls ${HARDER_PROVIDER} only, not ${provider}`);
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, given.model);
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, { provider: HARDER_PROVIDER, model: given.model, consented_at: new Date().toISOString() });
67
- options.diagnostic(`search all --harder may now call ${HARDER_PROVIDER} ${given.model}`);
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"), {
@@ -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
  /**
@@ -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: setting.also.map(normalCrmUserId) }
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.
@@ -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 override.kind = ${alias}.kind AND override.from_type = ${alias}.from_type ` +
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. */
@@ -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
- const Setting = v.strictObject({
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
  });
@@ -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";
@@ -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
- const done = await reorderHarder(request.text, ordered, { ...asking, laterPage: offset > 0 });
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
- export declare const HARDER_PROVIDER = "anthropic";
6
- export declare const DEFAULT_HARDER_MODEL = "claude-haiku-5-5";
7
- export declare const HARDER_ENDPOINT = "https://api.anthropic.com";
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.LiteralSchema<"anthropic", undefined>;
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[], { env, now, command, laterPage, ...options }: HarderOptions & {
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
- export const HARDER_PROVIDER = "anthropic";
9
- export const DEFAULT_HARDER_MODEL = "claude-haiku-5-5";
10
- export const HARDER_ENDPOINT = "https://api.anthropic.com";
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
- provider: v.literal(HARDER_PROVIDER),
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 Anthropic key",
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
- * `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
91
- * first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
92
- * key nothing is sent.
93
- */
94
- export const reorderHarder = async (question, hits, { env, now, command, laterPage, ...options }) => {
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 plain("harder.no-consent", {}, `${REASON_TEXT["harder.no-consent"]}: \`${tool} models search-consents set anthropic --yes\`; nothing was sent`);
126
- let apiKey;
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
- apiKey = keyLookup({ env, ...options }, { provider: HARDER_PROVIDER })?.key;
138
+ key = keyLookup({ env, ...options }, setting)?.key;
129
139
  }
130
140
  catch {
131
- return plain("harder.error", {}, "the Anthropic key could not be read; nothing was sent");
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
- if (apiKey === undefined)
134
- return plain("harder.no-key", {}, `no Anthropic key: \`${tool} models keys set anthropic\` or set ${keyVariable(HARDER_PROVIDER)}; nothing was sent`);
135
- const candidates = hits.slice(0, HARDER_CANDIDATES);
136
- if (candidates.length < 2)
137
- return plain("harder.too-few");
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: HARDER_PROVIDER, model: setting.model, baseUrl: HARDER_ENDPOINT }),
142
- consent: (_request, chosen) => chosen.provider === HARDER_PROVIDER && chosen.baseUrl === HARDER_ENDPOINT,
143
- key: () => apiKey,
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 sent = { sent: candidates.length };
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
- purpose: "search-harder",
152
- prompt: PROMPT.replace("{as_of}", new Date(now).toISOString().slice(0, 10))
153
- .replace("{n}", String(candidates.length))
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: HARDER_PROVIDER,
161
- model: setting.model,
184
+ provider: access.provider,
185
+ model: access.model,
186
+ ...(access.custom ? { base_url: access.endpoint } : {}),
162
187
  });
163
- let picked;
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 plain(reasonOf(error, limit.signal.aborted), { ...sent, cost_usd: null });
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
+ };
@@ -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
- return links.map((link) => insertLink(context, { ...link, from: `document:${id}`, origin: "file" }));
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);
@@ -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.620.0",
3
+ "version": "0.621.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",