@wirecat/cli-core 0.679.0 → 0.680.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/background/budget.d.ts +8 -1
  3. package/dist/background/budget.js +16 -2
  4. package/dist/calendar/cli/answers.d.ts +2 -0
  5. package/dist/calendar/cli/answers.js +7 -1
  6. package/dist/calendar/cli/index.js +3 -0
  7. package/dist/cli/documents/sync.d.ts +1 -1
  8. package/dist/cli/help/first-screen.d.ts +2 -10
  9. package/dist/cli/help/first-screen.js +2 -59
  10. package/dist/cli/setup-command.js +8 -2
  11. package/dist/cli/skill-refresh.js +4 -3
  12. package/dist/crm/index.d.ts +1 -0
  13. package/dist/crm/index.js +1 -0
  14. package/dist/mcp/app-server.js +4 -5
  15. package/dist/mcp/bot/server.js +4 -5
  16. package/dist/mcp/server.js +5 -6
  17. package/dist/ports/wirecat-tools.d.ts +12 -0
  18. package/dist/ports/wirecat-tools.js +81 -0
  19. package/dist/sends/upload.d.ts +4 -1
  20. package/dist/sends/upload.js +22 -8
  21. package/dist/services/documents/plan.js +3 -5
  22. package/dist/services/documents/ports.d.ts +2 -0
  23. package/dist/services/documents/sync.js +3 -5
  24. package/dist/services/notes-search.d.ts +8 -0
  25. package/dist/services/notes-search.js +29 -1
  26. package/dist/skills/validate.d.ts +2 -0
  27. package/dist/skills/validate.js +28 -5
  28. package/dist/store/sqlite/agent-links.js +2 -2
  29. package/dist/store/sqlite/event-search.d.ts +2 -0
  30. package/dist/store/sqlite/event-search.js +10 -0
  31. package/dist/store/sqlite/note-search.d.ts +2 -0
  32. package/dist/store/sqlite/note-search.js +10 -0
  33. package/dist/store/sqlite/person-match-scan.d.ts +5 -0
  34. package/dist/store/sqlite/person-match-scan.js +15 -8
  35. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -5,6 +5,38 @@ 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.680.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`embedNotes`, `embedEvents` and `embedMail` take `deadline` and `signal`.** They stop between batches at the
13
+ deadline less its margin, or on a cancel, and answer `stopped` and, for notes and events, `remaining`: the chunks
14
+ still without a vector. Enrichment before the embed gets the same limit. Calendar `sync --embed` passes its run's
15
+ deadline and signal, so a sync that ends late no longer runs into `command.timed-out` while it embeds. See
16
+ [Walks over several syncs](docs/dev/DOCUMENTS.md#walks-over-several-syncs).
17
+ - **`RunBudget.first()`**: whether a call's first request goes past a `deadline` stop.
18
+
19
+ ### Fixed
20
+
21
+ - **A documents sync no longer overruns its deadline after a slow first listing.** The first-request exception held
22
+ for the walk's first listing and again for the first file read, so a 4 s run could list for 1.9 s, read for 3 s
23
+ and end at 4.9 s. Now only one request per call goes past the margin, only before any other, sized by the CLI's
24
+ `requestMs` plus 0.5 s to answer, and timed by the budget's clock rather than a sync's fixed `now`.
25
+ - **`setup apply --dry-run` never opens the keyring.** 0.679.0 still read it when the answers reached a secret input
26
+ and left it empty, so the shared deny contract (`cli-contract`, WC-PERM-23) could still fail. A dry run now takes
27
+ each secret as kept: it never reports an unanswered secret as missing, so an edit that leaves the password alone can
28
+ continue, and it still refuses a secret answer of the wrong shape. `apply` checks the secret and keeps the saved
29
+ one when none is answered.
30
+
31
+ ### Security
32
+
33
+ - **A file to send is refused under `/proc`, `/sys` and `/dev`**, through any link and even with `--allow-any-file`:
34
+ `--file /proc/self/environ` sent the process's environment, which can hold a tool's token. `refusedPlace` refuses
35
+ those paths too, and `readUpload` still takes only a regular file.
36
+ - **`refusedPlace` covers every WireCat tool's folders.** It takes them from `WIRECAT_TOOLS`, which now names each
37
+ tool's `appName` and `envPrefix`, plus amo-cli and beeline-cli. zoom-cli's folders were missed: they
38
+ were listed under the name `zm`, not `zoom-cli`.
39
+
8
40
  ## 0.679.0 — 16.11.2026
9
41
 
10
42
  ### Added
@@ -14,6 +14,11 @@ export interface Deadline {
14
14
  export interface RunBudget {
15
15
  /** One more request: `null` when it may go, otherwise why not. Once it says no it keeps saying no. */
16
16
  take(): BudgetStop | null;
17
+ /**
18
+ * After `take()` said "deadline": whether the call's first request goes anyway. Only while nothing has gone yet,
19
+ * once, and when one request still ends before the deadline itself with time left to answer.
20
+ */
21
+ first?(): boolean;
17
22
  readonly used: number;
18
23
  /** `null`: no request limit, only the deadline. */
19
24
  readonly limit: number | null;
@@ -23,7 +28,9 @@ export declare const DEADLINE_MARGIN_MS = 5000;
23
28
  export declare const DEADLINE_MARGIN_SHARE = 0.15;
24
29
  /** How long one request to a provider is expected to take when the CLI does not say (`AppIdentity.requestMs`). */
25
30
  export declare const DEFAULT_REQUEST_MS = 2000;
26
- /** Whether one more request still ends before the deadline itself, inside its margin. */
31
+ /** Kept after a request for the answer, the catalog import and the state save. */
32
+ export declare const ANSWER_RESERVE_MS = 500;
33
+ /** Whether one more request still ends before the deadline itself, with time left to answer. */
27
34
  export declare const oneMoreFits: (deadline: Deadline | undefined, at: number, requestMs?: number) => boolean;
28
35
  export declare const deadlineMargin: (deadline: Deadline) => number;
29
36
  /** The requests that fit before the margin: `(deadline − margin) / requestMs`, at least one; none without a deadline. */
@@ -2,8 +2,10 @@ export const DEADLINE_MARGIN_MS = 5_000;
2
2
  export const DEADLINE_MARGIN_SHARE = 0.15;
3
3
  /** How long one request to a provider is expected to take when the CLI does not say (`AppIdentity.requestMs`). */
4
4
  export const DEFAULT_REQUEST_MS = 2_000;
5
- /** Whether one more request still ends before the deadline itself, inside its margin. */
6
- export const oneMoreFits = (deadline, at, requestMs = DEFAULT_REQUEST_MS) => deadline !== undefined && at + requestMs < deadline.endsAt;
5
+ /** Kept after a request for the answer, the catalog import and the state save. */
6
+ export const ANSWER_RESERVE_MS = 500;
7
+ /** Whether one more request still ends before the deadline itself, with time left to answer. */
8
+ export const oneMoreFits = (deadline, at, requestMs = DEFAULT_REQUEST_MS) => deadline !== undefined && at + requestMs + ANSWER_RESERVE_MS < deadline.endsAt;
7
9
  export const deadlineMargin = (deadline) => Math.max(DEADLINE_MARGIN_MS, deadline.ms * DEADLINE_MARGIN_SHARE);
8
10
  /** The requests that fit before the margin: `(deadline − margin) / requestMs`, at least one; none without a deadline. */
9
11
  export const requestsFor = (deadline, requestMs = DEFAULT_REQUEST_MS) => deadline === undefined ? null : Math.max(1, Math.floor((deadline.ms - deadlineMargin(deadline)) / requestMs));
@@ -16,6 +18,7 @@ export const runBudget = ({ requests, deadline, requestMs, signal, now = Date.no
16
18
  const limit = fits === null ? (requests ?? null) : Math.min(fits, requests ?? fits);
17
19
  const margin = deadline ? deadlineMargin(deadline) : 0;
18
20
  let used = 0;
21
+ let granted = false;
19
22
  let stopped = null;
20
23
  let last;
21
24
  // A request may page inside the source, so the gap between two asks is the honest measure of one.
@@ -39,6 +42,17 @@ export const runBudget = ({ requests, deadline, requestMs, signal, now = Date.no
39
42
  last = at;
40
43
  return null;
41
44
  },
45
+ first() {
46
+ if (granted || used > 0 || stopped !== "deadline")
47
+ return false;
48
+ const at = now();
49
+ if (!oneMoreFits(deadline, at, Math.max(requestMs ?? DEFAULT_REQUEST_MS, slowest)))
50
+ return false;
51
+ granted = true;
52
+ used += 1;
53
+ last = at;
54
+ return true;
55
+ },
42
56
  get used() {
43
57
  return used;
44
58
  },
@@ -100,6 +100,8 @@ export declare const calendarSync: v.StrictObjectSchema<{
100
100
  readonly model: v.StringSchema<undefined>;
101
101
  readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
102
102
  readonly left: v.BooleanSchema<undefined>;
103
+ readonly stopped: v.OptionalSchema<v.PicklistSchema<["deadline", "cancelled"], undefined>, undefined>;
104
+ readonly remaining: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
103
105
  }, undefined>, undefined>;
104
106
  /**
105
107
  * Each feed's events as read, and how many it could not take (`syncWithFeeds`); `unchanged` when the feed answered
@@ -71,7 +71,13 @@ export const calendarSync = v.strictObject({
71
71
  }),
72
72
  hint: v.optional(text),
73
73
  /** What `sync --embed` embedded: `embedEvents`' answer. */
74
- embeddings: v.optional(v.strictObject({ model: text, embedded: count, left: v.boolean() })),
74
+ embeddings: v.optional(v.strictObject({
75
+ model: text,
76
+ embedded: count,
77
+ left: v.boolean(),
78
+ stopped: v.optional(v.picklist(["deadline", "cancelled"])),
79
+ remaining: v.optional(count),
80
+ })),
75
81
  /**
76
82
  * Each feed's events as read, and how many it could not take (`syncWithFeeds`); `unchanged` when the feed answered
77
83
  * 304 and the counts are those of the read before.
@@ -191,6 +191,7 @@ const addCalendarCommandsDefinition = (program, options) => {
191
191
  if (command.optsWithGlobals().full)
192
192
  throw new CliError("validation_error", "sync starts over with --rescan; --full only widens output");
193
193
  const { signal } = environmentOf(command);
194
+ const deadline = environmentOf(command).deadline?.();
194
195
  await within(command, async (run) => {
195
196
  if (opts.embed && !run.messages)
196
197
  throw new CliError("configuration_error", "this tool cannot embed events");
@@ -206,6 +207,8 @@ const addCalendarCommandsDefinition = (program, options) => {
206
207
  const embeddings = opts.embed && !report.stopped && run.messages
207
208
  ? await embedEvents(run.messages, {
208
209
  maxChunks: EMBED_MAX,
210
+ ...(deadline ? { deadline } : {}),
211
+ ...(signal ? { signal } : {}),
209
212
  ...(run.env ? { env: run.env } : {}),
210
213
  command: options.app.command,
211
214
  })
@@ -9,7 +9,7 @@ export interface DocumentSyncArgs {
9
9
  embed?: boolean;
10
10
  /** Sized to the run's deadline; pass it to `syncDocuments` so a sync stops in time and says how to go on. */
11
11
  budget?: RunBudget;
12
- /** The run's hard limit; pass it to `syncDocuments` so its last step, the word index, ends before it. */
12
+ /** The run's hard limit; pass it to `syncDocuments`, and to `embedNotes` for `--embed`, so both end before it. */
13
13
  deadline?: Deadline;
14
14
  }
15
15
  export interface DocumentSyncAnswer {
@@ -1,4 +1,5 @@
1
1
  import { Command } from "commander";
2
+ import { WIRECAT_TOOLS } from "../../ports/wirecat-tools.js";
2
3
  export interface FirstScreenLine {
3
4
  /** The command without the tool's name or the profile: `review --since 1d`. */
4
5
  command: string;
@@ -15,15 +16,7 @@ export interface FirstScreen {
15
16
  /** The first command to run. Unset, `<tool> personal setup` when the tool has `setup`. */
16
17
  start?: string;
17
18
  }
18
- interface Tool {
19
- command: string;
20
- /** The npm package `setup` installs it from. */
21
- package: string;
22
- shown?: string;
23
- does: string;
24
- }
25
- /** Every WireCat tool, as "Works with" names it; a tool's own entry is left out of its screen. */
26
- export declare const WIRECAT_TOOLS: readonly Tool[];
19
+ export { WIRECAT_TOOLS };
27
20
  /**
28
21
  * The screen `<tool> --help` and a bare `<tool>` show: what the tool is for, what it does that a client would not,
29
22
  * the other tools, and where the full list, the scenarios and the options are. It never lists every command.
@@ -36,4 +29,3 @@ export declare const firstScreen: (program: Command, screen?: FirstScreen) => st
36
29
  * `createProgram` calls it for tg, max and wa.
37
30
  */
38
31
  export declare const installHelp: (program: Command, screen?: FirstScreen) => Command;
39
- export {};
@@ -2,68 +2,11 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command, Help, Option } from "commander";
4
4
  import wrapAnsi from "wrap-ansi";
5
+ import { WIRECAT_TOOLS } from "../../ports/wirecat-tools.js";
5
6
  import { NO_EFFECTS } from "../effects.js";
6
7
  import { commandAt } from "../steps.js";
7
8
  import { EXAMPLE_PROFILE, installCommandHelp } from "./command-help.js";
8
- /** Every WireCat tool, as "Works with" names it; a tool's own entry is left out of its screen. */
9
- export const WIRECAT_TOOLS = [
10
- {
11
- command: "tg",
12
- package: "@wirecat/tg-cli",
13
- does: "Telegram in the same local store: search, review and tasks offline",
14
- },
15
- {
16
- command: "max",
17
- package: "@wirecat/max-cli",
18
- does: "MAX in the same local store: search, review and tasks offline",
19
- },
20
- {
21
- command: "wa",
22
- package: "@wirecat/whatsapp-cli",
23
- does: "WhatsApp in the same local store: search, review and tasks offline",
24
- },
25
- {
26
- command: "zm",
27
- package: "@wirecat/zoom-cli",
28
- does: "Zoom meetings: transcripts and summaries, searchable with your other WireCat data",
29
- },
30
- {
31
- command: "drive",
32
- package: "@wirecat/drive-cli",
33
- does: "Google Drive and Docs as local text, searchable with your other WireCat data",
34
- },
35
- {
36
- command: "gcal",
37
- package: "@wirecat/gcal-cli",
38
- does: "Google Calendar events, searchable with your other WireCat data",
39
- },
40
- {
41
- command: "memo",
42
- package: "@wirecat/cli-memo",
43
- shown: "memo context <person>",
44
- does: "one person across messengers, mail, notes and meetings",
45
- },
46
- {
47
- command: "mail",
48
- package: "@wirecat/mail-cli",
49
- does: "IMAP mail in the same local store: search your mailbox offline, next to your other WireCat data",
50
- },
51
- {
52
- command: "b24",
53
- package: "@wirecat/bitrix24-cli",
54
- does: "Bitrix24 CRM: deals, leads and pipelines, searchable with your other WireCat data",
55
- },
56
- {
57
- command: "pbx",
58
- package: "@wirecat/asterisk-cli",
59
- does: "Asterisk PBX calls and recordings, searchable with your other WireCat data",
60
- },
61
- {
62
- command: "notion",
63
- package: "@wirecat/notion-cli",
64
- does: "Notion pages and databases as local text, searchable with your other WireCat data",
65
- },
66
- ];
9
+ export { WIRECAT_TOOLS };
67
10
  const WIDTH = 100;
68
11
  const widest = (texts) => texts.reduce((most, text) => Math.max(most, text.length), 0);
69
12
  const block = (title, rows, column) => rows.length === 0 ? [] : ["", `${title}:`, ...rows.map(([left, right]) => ` ${left.padEnd(column)}${right}`)];
@@ -45,7 +45,7 @@ export const setupCommand = (setup) => {
45
45
  warn,
46
46
  });
47
47
  };
48
- const currentOf = (command, context) => {
48
+ const currentOf = (command, context, { dryRun = false } = {}) => {
49
49
  const { settings, renderer } = context;
50
50
  const current = {};
51
51
  let store;
@@ -69,6 +69,12 @@ export const setupCommand = (setup) => {
69
69
  const secret = secretOf(field);
70
70
  if (secret === undefined || secret in current)
71
71
  continue;
72
+ // Only `apply` checks a secret, and it keeps the saved one when none is answered: a dry run takes it as kept, so
73
+ // an edit that leaves the password alone can continue, and the keyring stays shut (WC-PERM-23).
74
+ if (dryRun) {
75
+ current[secret] = { set: true };
76
+ continue;
77
+ }
72
78
  let read;
73
79
  Object.defineProperty(current, secret, {
74
80
  enumerable: true,
@@ -125,7 +131,7 @@ export const setupCommand = (setup) => {
125
131
  const context = contextFor(command, true, dryRun);
126
132
  const { settings, env } = context;
127
133
  const profile = settings.profile;
128
- const path = walk(setup, answers, { current: currentOf(command, context) });
134
+ const path = walk(setup, answers, { current: currentOf(command, context, { dryRun }) });
129
135
  const reached = path.stopped === "run" || path.stopped === "done";
130
136
  const told = {
131
137
  profile,
@@ -1,6 +1,7 @@
1
- import { lstatSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
2
3
  import { isMovedRun, loadConfigFile, saveConfigFile } from "@wirecat/cli-base";
3
- import { hermesCopyPath, installSkill, skillStatus, skillVersion, withVersion, } from "@wirecat/cli-base/skill";
4
+ import { hermesCopyPath, installSkill, skillStatus, skillVersion, writeSkillFolder, } from "@wirecat/cli-base/skill";
4
5
  import { isNewer } from "@wirecat/cli-base/update";
5
6
  import * as v from "valibot";
6
7
  import { envName } from "../ports/app.js";
@@ -38,7 +39,7 @@ const refreshHermesCopy = (app, skill, env) => {
38
39
  const installed = skillVersion(readFileSync(path, "utf8"));
39
40
  if (installed === undefined || !isNewer(app.version, installed))
40
41
  return false;
41
- writeFileSync(path, withVersion(readFileSync(skill, "utf8"), app.version));
42
+ writeSkillFolder(app, skill, dirname(path));
42
43
  return true;
43
44
  };
44
45
  /**
@@ -5,6 +5,7 @@ export type { CrmCallContext, CrmChanges, CrmCondition, CrmGap, CrmIdPage, CrmLi
5
5
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
6
6
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
7
  export * as crmValues from "./values.js";
8
+ export { type CrmViewing, crmViewerOf } from "./viewer.js";
8
9
  export { type CrmRows, type CrmWindow, crmWindowOf, walk } from "./walk.js";
9
10
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmDrafts, type CrmFields, type CrmOrganizationFields, type CrmPersonFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteFields, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
10
11
  export { type CrmFieldsInput, type CrmRecordInput, type CrmRecordKind, type CrmRecordWritten, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
package/dist/crm/index.js CHANGED
@@ -4,6 +4,7 @@ export { conditionsOf, customConditions, customNames, filterableFields, selected
4
4
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
5
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
6
  export * as crmValues from "./values.js";
7
+ export { crmViewerOf } from "./viewer.js";
7
8
  export { crmWindowOf, walk } from "./walk.js";
8
9
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
9
10
  export { closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
@@ -2,7 +2,7 @@ import { McpServer } from "@modelcontextprotocol/server";
2
2
  import { StdioServerTransport, serveStdio } from "@modelcontextprotocol/server/stdio";
3
3
  import { CliError, mcpErrorResult } from "@wirecat/cli-base";
4
4
  import { describeProgram } from "@wirecat/cli-base/commands";
5
- import { skillResource } from "@wirecat/cli-base/skill";
5
+ import { skillResources } from "@wirecat/cli-base/skill";
6
6
  import { environmentOf } from "../cli/context.js";
7
7
  import { changesAuthorityAt, fetchesOnlyAt, judgedTargets, readsOverMcpAt } from "../cli/effects.js";
8
8
  import { DEFAULT_OUTPUT_BYTES } from "../cli/execution.js";
@@ -105,7 +105,8 @@ export const createAppServer = (command, context, options) => {
105
105
  },
106
106
  },
107
107
  ]));
108
- const skill = options.skill ? skillResource(app, options.skill) : undefined;
108
+ const skills = options.skill ? skillResources(app, options.skill) : [];
109
+ const skill = skills[0];
109
110
  const build = () => {
110
111
  const server = new McpServer({ name: app.command, version: app.version }, {
111
112
  instructions: appInstructions({
@@ -117,10 +118,8 @@ export const createAppServer = (command, context, options) => {
117
118
  }),
118
119
  });
119
120
  registerCommands(server, app.command, commands, app.errors, undefined, app.messenger);
120
- if (skill) {
121
- const { uri, name, title, description, mimeType, read } = skill;
121
+ for (const { uri, name, title, description, mimeType, read } of skills)
122
122
  server.registerResource(name, uri, { title, description, mimeType }, read);
123
- }
124
123
  return server;
125
124
  };
126
125
  return { build, offered: Object.keys(commands) };
@@ -3,7 +3,7 @@ import { McpServer } from "@modelcontextprotocol/server";
3
3
  import { StdioServerTransport, serveStdio } from "@modelcontextprotocol/server/stdio";
4
4
  import { mcpErrorResult } from "@wirecat/cli-base";
5
5
  import { flatten } from "@wirecat/cli-base/commands";
6
- import { skillResource } from "@wirecat/cli-base/skill";
6
+ import { skillResources } from "@wirecat/cli-base/skill";
7
7
  import * as v from "valibot";
8
8
  import { changesMessenger } from "../../cli/effects.js";
9
9
  import { itemOf } from "../../cli/envelope.js";
@@ -50,7 +50,8 @@ export const createBotServer = (options) => {
50
50
  const writes = tools
51
51
  .filter((tool) => tool.writes && tool.availability?.().available !== false)
52
52
  .map((tool) => tool.command);
53
- const skill = options.skill ? skillResource(bot.app, options.skill) : undefined;
53
+ const skills = options.skill ? skillResources(bot.app, options.skill) : [];
54
+ const skill = skills[0];
54
55
  // One at a time: the commands share the journal, the registry and the local copy.
55
56
  let queue = Promise.resolve();
56
57
  const invoke = (path, input, caller) => {
@@ -78,10 +79,8 @@ export const createBotServer = (options) => {
78
79
  ...(skill ? { skill: skill.instruction } : {}),
79
80
  }),
80
81
  });
81
- if (skill) {
82
- const { uri, name, title, description, mimeType, read } = skill;
82
+ for (const { uri, name, title, description, mimeType, read } of skills)
83
83
  server.registerResource(name, uri, { title, description, mimeType }, read);
84
- }
85
84
  const commands = Object.fromEntries(tools.map((tool) => [
86
85
  tool.command,
87
86
  {
@@ -3,7 +3,7 @@ import { McpServer } from "@modelcontextprotocol/server";
3
3
  import { StdioServerTransport, serveStdio } from "@modelcontextprotocol/server/stdio";
4
4
  import { CliError, errorObjectOf, mcpErrorResult } from "@wirecat/cli-base";
5
5
  import { describeProgram } from "@wirecat/cli-base/commands";
6
- import { skillResource } from "@wirecat/cli-base/skill";
6
+ import { skillResources } from "@wirecat/cli-base/skill";
7
7
  import * as v from "valibot";
8
8
  import { findCommand } from "../cli/command-contract.js";
9
9
  import { environmentOf } from "../cli/context.js";
@@ -182,7 +182,8 @@ export const createServer = (command, context, messenger, sessionOptions) => {
182
182
  ...(messenger.diagnose ? { [messenger.provider]: await messenger.diagnose(command, context) } : {}),
183
183
  }),
184
184
  });
185
- const skill = messenger.skill ? skillResource(app, messenger.skill) : undefined;
185
+ const skills = messenger.skill ? skillResources(app, messenger.skill) : [];
186
+ const skill = skills[0];
186
187
  const log = agentLog(() => openStore({ env: context.env, command: app.command, version: app.version }));
187
188
  const audit = async (call, caller) => {
188
189
  if (!recalledAccount(app, provider, settings.profile, context.env))
@@ -370,10 +371,8 @@ export const createServer = (command, context, messenger, sessionOptions) => {
370
371
  });
371
372
  },
372
373
  });
373
- if (skill) {
374
- const { uri, name: resource, title, description, mimeType, read } = skill;
375
- server.registerResource(resource, uri, { title, description, mimeType }, read);
376
- }
374
+ for (const { uri, name, title, description, mimeType, read } of skills)
375
+ server.registerResource(name, uri, { title, description, mimeType }, read);
377
376
  return server;
378
377
  };
379
378
  return { session, embedders, build, log, offered: [...commands.map((one) => one.command), ...pictured] };
@@ -0,0 +1,12 @@
1
+ export interface WireCatTool {
2
+ command: string;
3
+ /** Its `AppIdentity.appName` and `envPrefix`: where its folders are, which no other tool may send. */
4
+ appName: string;
5
+ envPrefix: string;
6
+ /** The npm package `setup` installs it from. */
7
+ package: string;
8
+ shown?: string;
9
+ does: string;
10
+ }
11
+ /** Every WireCat tool, as "Works with" names it; a tool's own entry is left out of its screen. */
12
+ export declare const WIRECAT_TOOLS: readonly WireCatTool[];
@@ -0,0 +1,81 @@
1
+ /** Every WireCat tool, as "Works with" names it; a tool's own entry is left out of its screen. */
2
+ export const WIRECAT_TOOLS = [
3
+ {
4
+ command: "tg",
5
+ appName: "tg-cli",
6
+ envPrefix: "TG",
7
+ package: "@wirecat/tg-cli",
8
+ does: "Telegram in the same local store: search, review and tasks offline",
9
+ },
10
+ {
11
+ command: "max",
12
+ appName: "max-cli",
13
+ envPrefix: "MAX",
14
+ package: "@wirecat/max-cli",
15
+ does: "MAX in the same local store: search, review and tasks offline",
16
+ },
17
+ {
18
+ command: "wa",
19
+ appName: "whatsapp-cli",
20
+ envPrefix: "WA",
21
+ package: "@wirecat/whatsapp-cli",
22
+ does: "WhatsApp in the same local store: search, review and tasks offline",
23
+ },
24
+ {
25
+ command: "zm",
26
+ appName: "zoom-cli",
27
+ envPrefix: "ZM",
28
+ package: "@wirecat/zoom-cli",
29
+ does: "Zoom meetings: transcripts and summaries, searchable with your other WireCat data",
30
+ },
31
+ {
32
+ command: "drive",
33
+ appName: "drive-cli",
34
+ envPrefix: "DRIVE",
35
+ package: "@wirecat/drive-cli",
36
+ does: "Google Drive and Docs as local text, searchable with your other WireCat data",
37
+ },
38
+ {
39
+ command: "gcal",
40
+ appName: "gcal-cli",
41
+ envPrefix: "GCAL",
42
+ package: "@wirecat/gcal-cli",
43
+ does: "Google Calendar events, searchable with your other WireCat data",
44
+ },
45
+ {
46
+ command: "memo",
47
+ appName: "cli-memo",
48
+ envPrefix: "MEMO",
49
+ package: "@wirecat/cli-memo",
50
+ shown: "memo context <person>",
51
+ does: "one person across messengers, mail, notes and meetings",
52
+ },
53
+ {
54
+ command: "mail",
55
+ appName: "mail-cli",
56
+ envPrefix: "MAIL",
57
+ package: "@wirecat/mail-cli",
58
+ does: "IMAP mail in the same local store: search your mailbox offline, next to your other WireCat data",
59
+ },
60
+ {
61
+ command: "b24",
62
+ appName: "bitrix24-cli",
63
+ envPrefix: "B24",
64
+ package: "@wirecat/bitrix24-cli",
65
+ does: "Bitrix24 CRM: deals, leads and pipelines, searchable with your other WireCat data",
66
+ },
67
+ {
68
+ command: "pbx",
69
+ appName: "asterisk-cli",
70
+ envPrefix: "PBX",
71
+ package: "@wirecat/asterisk-cli",
72
+ does: "Asterisk PBX calls and recordings, searchable with your other WireCat data",
73
+ },
74
+ {
75
+ command: "notion",
76
+ appName: "notion-cli",
77
+ envPrefix: "WCNOTION",
78
+ package: "@wirecat/notion-cli",
79
+ does: "Notion pages and databases as local text, searchable with your other WireCat data",
80
+ },
81
+ ];
@@ -16,7 +16,10 @@ export declare const typesText: (types: readonly string[]) => string;
16
16
  * or another tool's settings. Locked with no run's folder, it writes no file.
17
17
  */
18
18
  export declare const refuseLockedOutput: (path: string, app: AppIdentity, env: NodeJS.ProcessEnv, flag: string) => void;
19
- /** Protect known credential/state paths without refusing ordinary hidden developer folders. */
19
+ /**
20
+ * Protect known credential/state paths and the kernel's and devices' files, through any link, without refusing
21
+ * ordinary hidden developer folders.
22
+ */
20
23
  export declare const refusedPlace: (path: string, app: AppIdentity, env: NodeJS.ProcessEnv, platform?: NodeJS.Platform) => boolean;
21
24
  export declare const readUpload: (kind: UploadKind, path: string, { app, env, anyFile, photoTypes, }: {
22
25
  app: AppIdentity;
@@ -3,6 +3,7 @@ import { open, stat } from "node:fs/promises";
3
3
  import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
4
4
  import { CliError, resolvePaths } from "@wirecat/cli-base";
5
5
  import { ancestorValue, envName, readOnlyLockOf } from "../ports/app.js";
6
+ import { WIRECAT_TOOLS } from "../ports/wirecat-tools.js";
6
7
  import { storePath, wirecatDirectory } from "../store/path.js";
7
8
  /** The most `uploadBytes` holds in memory; an adapter that can stream uses `uploadBlob` and has no such cap. */
8
9
  export const MAX_BUFFERED_UPLOAD_BYTES = 256 * 1024 * 1024;
@@ -107,17 +108,22 @@ const CREDENTIAL_RUNS = [
107
108
  ["AppData", "Roaming", "gcloud"],
108
109
  ["AppData", "Roaming", "GitHub CLI"],
109
110
  ];
110
- /** Every WireCat app's folders hold its sessions and tokens; `max` must not send `tg`'s, nor the other way round. */
111
+ /**
112
+ * Every WireCat app's folders hold its sessions and tokens; `max` must not send `tg`'s, nor the other way round. The
113
+ * tools come from `WIRECAT_TOOLS`, so a new tool is covered once it is listed there; the rest are apps no first
114
+ * screen names yet, the shared packages' own folders, and the name zoom-cli's folders had before.
115
+ */
111
116
  const WIRECAT_APPS = [
112
- { appName: "max-cli", prefix: "MAX" },
113
- { appName: "tg-cli", prefix: "TG" },
114
- { appName: "whatsapp-cli", prefix: "WA" },
115
- { appName: "cli-memo", prefix: "MEMO" },
116
- { appName: "drive-cli", prefix: "DRIVE" },
117
+ ...WIRECAT_TOOLS.map(({ appName, envPrefix }) => ({ appName, prefix: envPrefix })),
118
+ { appName: "amo-cli", prefix: "AMO" },
119
+ { appName: "beeline-cli", prefix: "BEELINE" },
117
120
  { appName: "zm", prefix: "ZM" },
118
121
  { appName: "cli-messaging", prefix: "MESSAGING" },
119
122
  { appName: "cli-common", prefix: "CLI_COMMON" },
120
123
  ];
124
+ /** Kernel and device files: `/proc/self/environ` holds the process's tokens, and a device is no file to send. */
125
+ const SYSTEM_ROOTS = ["/proc", "/sys", "/dev"];
126
+ const systemPlace = (path, platform) => platform !== "win32" && SYSTEM_ROOTS.some((root) => inside(path, root));
121
127
  /** Where `path` really is: its nearest existing ancestor's real path, as a write may create the rest under a symlink. */
122
128
  const realPathOf = (path) => {
123
129
  let ancestor = resolve(path);
@@ -152,7 +158,10 @@ export const refuseLockedOutput = (path, app, env, flag) => {
152
158
  ? `this process is read-only (${lock}) — ${flag} writes a file only inside a scheduled run's work folder`
153
159
  : `this process is read-only (${lock}) — ${flag} writes only inside its run's work folder, ${work}`, { reason: "read-only.output-outside", param: flag });
154
160
  };
155
- /** Protect known credential/state paths without refusing ordinary hidden developer folders. */
161
+ /**
162
+ * Protect known credential/state paths and the kernel's and devices' files, through any link, without refusing
163
+ * ordinary hidden developer folders.
164
+ */
156
165
  export const refusedPlace = (path, app, env, platform = process.platform) => {
157
166
  const own = [
158
167
  ...[{ appName: app.appName, prefix: app.envPrefix }, ...WIRECAT_APPS].flatMap((one) => Object.values(resolvePaths({ ...one, env, platform }))),
@@ -174,7 +183,8 @@ export const refusedPlace = (path, app, env, platform = process.platform) => {
174
183
  runs.some((run) => run.every((part, offset) => names[index + offset] === part)));
175
184
  };
176
185
  const same = (a, b) => fold(a) === fold(b);
177
- return [resolve(path), real].some((candidate) => named(candidate) ||
186
+ return [resolve(path), real].some((candidate) => systemPlace(candidate, platform) ||
187
+ named(candidate) ||
178
188
  own.some((dir) => inside(fold(candidate), fold(dir))) ||
179
189
  [store, `${store}-wal`, `${store}-shm`].some((file) => same(candidate, file)));
180
190
  };
@@ -193,6 +203,10 @@ export const readUpload = async (kind, path, { app, env = process.env, anyFile =
193
203
  if (kind === "voice" && !VOICE.has(extension)) {
194
204
  throw new CliError("validation_error", `a voice message is Ogg Opus: .ogg, .oga or .opus — send ${path} as a file`);
195
205
  }
206
+ // --allow-any-file is for the owner's own credential file; no one sends the kernel's view of this process.
207
+ if ([resolve(path), realPathOf(path)].some((candidate) => systemPlace(candidate, process.platform))) {
208
+ throw new CliError("validation_error", `cannot send ${path}: a file under /proc, /sys or /dev is never sent`);
209
+ }
196
210
  if (!anyFile && refusedPlace(path, app, env)) {
197
211
  throw new CliError("validation_error", `cannot send ${path}: known credential files, browser profiles, the WireCat apps' folders and the message ` +
198
212
  "store are not sent — the owner adds --allow-any-file to the command if this file is meant to go");
@@ -1,6 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { oneMoreFits } from "../../background/budget.js";
4
3
  import { inScope, within } from "../../documents/scope.js";
5
4
  // Without a query or pages the hash stays what it was, so a profile that never set them keeps its checkpoint. Turning
6
5
  // pages on changes it, so the next sync walks again and imports the pages an incremental one would never revisit.
@@ -186,15 +185,14 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
186
185
  }
187
186
  // One listing at least per call, so a folder with more children than the bound still moves on.
188
187
  // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
189
- // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first listing
190
- // goes ahead while one request still fits before the deadline itself.
188
+ // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first request
189
+ // goes ahead while one still fits before the deadline itself.
191
190
  const taken = options.signal?.aborted
192
191
  ? "cancelled"
193
192
  : listed > 0 && spent >= maxEntries
194
193
  ? "entries"
195
194
  : budget?.take();
196
- const first = taken === "deadline" && listed === 0 && oneMoreFits(options.deadline, now());
197
- stopped = first ? null : (taken ?? null);
195
+ stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
198
196
  if (stopped)
199
197
  break;
200
198
  const folder = step.folder ?? (await source.metadata(step.id));
@@ -21,6 +21,8 @@ export interface SyncOptions<M extends SourceFile> {
21
21
  /** Asked before each folder listing and each file read: a stop ends the call with its work saved. */
22
22
  budget?: {
23
23
  take(): "requests" | "deadline" | "cancelled" | null;
24
+ /** The call's first request, when `take()` said "deadline" and nothing has gone yet (`RunBudget.first`). */
25
+ first?(): boolean;
24
26
  readonly stopped?: string | null;
25
27
  };
26
28
  /** The run's hard limit: the word index at the end of a sync stops before it, less its margin. */
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError, isCliError } from "@wirecat/cli-base";
3
- import { deadlineMargin, oneMoreFits } from "../../background/budget.js";
3
+ import { deadlineMargin } from "../../background/budget.js";
4
4
  import { catalogFiles } from "../../documents/catalog.js";
5
5
  import { inScope } from "../../documents/scope.js";
6
6
  import { changedSince, planDocuments, scopeHash } from "./plan.js";
@@ -148,7 +148,6 @@ export const syncDocuments = async (options) => {
148
148
  flush?.();
149
149
  };
150
150
  const jobs = [...pending.jobs].slice(0, max);
151
- let read = 0;
152
151
  for (const job of jobs) {
153
152
  if (signal?.aborted)
154
153
  throw new CliError("cancelled", "sync was cancelled; pending operations are retained");
@@ -168,13 +167,12 @@ export const syncDocuments = async (options) => {
168
167
  if (!source)
169
168
  throw new CliError("configuration_error", "a pending save requires source sign-in");
170
169
  const taken = options.budget?.take();
171
- // The first read of a call goes ahead as the walk's first listing does, or a short run never saves one.
172
- const stop = taken === "deadline" && read === 0 && oneMoreFits(options.deadline, now()) ? null : taken;
170
+ // A call that has listed nothing reads one page, or a short run never saves one.
171
+ const stop = taken === "deadline" && options.budget?.first?.() ? null : taken;
173
172
  if (stop) {
174
173
  result.stopped = stop;
175
174
  break;
176
175
  }
177
- read++;
178
176
  const content = await source.content(job.id, limit);
179
177
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
180
178
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
@@ -1,5 +1,6 @@
1
1
  import { type KeyringStore } from "@wirecat/cli-base";
2
2
  import { type QueryNode } from "@wirecat/cli-base/query";
3
+ import { type Deadline } from "../background/budget.js";
3
4
  import { type Embedder, type WarmEmbedders } from "../embeddings/embed.js";
4
5
  import { type TextModel } from "../embeddings/models.js";
5
6
  import type { PictureEmbedder } from "../images/picture/embedder.js";
@@ -54,12 +55,19 @@ export interface NotesEmbedOptions {
54
55
  keyring?: KeyringStore;
55
56
  /** Tests give a fake model here; nothing in the suite reaches a provider. */
56
57
  enrichWith?: Pick<EnrichOptions, "adapters" | "fetch" | "key">;
58
+ /** The run's hard limit: the run stops between batches before it, less its margin, as a sync's last step does. */
59
+ deadline?: Deadline;
60
+ signal?: AbortSignal;
57
61
  }
58
62
  export interface NotesEmbedded {
59
63
  model: string;
60
64
  embedded: number;
61
65
  /** Chunks still without a vector, when `maxChunks` stopped the run, or records still to enrich. */
62
66
  left: boolean;
67
+ /** The run stopped early to end in time, or was cancelled; the next run goes on. */
68
+ stopped?: "deadline" | "cancelled";
69
+ /** After a stop: the chunks still without a vector, when the store can count them. */
70
+ remaining?: number;
63
71
  /** What the owner's enrichment did first; absent when it is off. */
64
72
  /** The run, or `failed` with no counts when enrichment threw before it could count. */
65
73
  enrichment?: Exclude<EnrichRun, {
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { dateRange, parseLucene, timezoneOf } from "@wirecat/cli-base/query";
3
+ import { deadlineMargin } from "../background/budget.js";
3
4
  import { INTERNAL_NOTES, isImportedProvider } from "../domain/providers.js";
4
5
  import { normalizeTag } from "../domain/tags.js";
5
6
  import { defaultThreads, isTextModelInstalled, openEmbedder, textModelsDirectory, } from "../embeddings/embed.js";
@@ -101,14 +102,31 @@ export const withLocal = async (model, directory, threads, work, shared) => {
101
102
  * as conversations, so a chunk whose text a conversation shares is embedded once. A missing model is
102
103
  * an error naming the download command; nothing is downloaded.
103
104
  */
104
- const embedChunks = async (store, source, { model: choice, maxChunks = Number.POSITIVE_INFINITY, env, threads, command, } = {}) => {
105
+ /** When a run with this deadline stops: its margin before the end, as the word index after a sync does. */
106
+ const stopsAt = (deadline) => deadline ? deadline.endsAt - deadlineMargin(deadline) : Number.POSITIVE_INFINITY;
107
+ const embedChunks = async (store, source, { model: choice, maxChunks = Number.POSITIVE_INFINITY, env, threads, command, deadline, signal, } = {}) => {
105
108
  const { model, directory, key } = localModel(choice, env, command);
106
109
  if ((await source.chunksToEmbed(key, { limit: 1 })).length === 0)
107
110
  return { model: model.id, embedded: 0, left: false };
111
+ const until = stopsAt(deadline);
112
+ const stopped = (slowest) => signal?.aborted ? "cancelled" : Date.now() + slowest >= until ? "deadline" : undefined;
113
+ const stop = async (embedded, why) => {
114
+ const remaining = await source.chunksLeft?.(key);
115
+ return { model: model.id, embedded, left: true, stopped: why, ...(remaining === undefined ? {} : { remaining }) };
116
+ };
117
+ // Loading the model alone takes seconds.
118
+ const early = stopped(0);
119
+ if (early)
120
+ return stop(0, early);
108
121
  return withLocal(model, directory, threads, async (embedder) => {
109
122
  let embedded = 0;
110
123
  let after;
124
+ let slowest = 0;
111
125
  while (embedded < maxChunks) {
126
+ const why = stopped(slowest);
127
+ if (why)
128
+ return stop(embedded, why);
129
+ const started = Date.now();
112
130
  const batch = await source.chunksToEmbed(key, {
113
131
  limit: Math.min(NOTE_BATCH, maxChunks - embedded),
114
132
  ...(after === undefined ? {} : { after }),
@@ -119,6 +137,7 @@ const embedChunks = async (store, source, { model: choice, maxChunks = Number.PO
119
137
  const vectors = await embedder.embed(batch.map(({ text }) => text), "passage");
120
138
  await store.vectors.saveVectors(key, model.dims, batch.map(({ hash }, index) => ({ hash, vector: vectors[index] })));
121
139
  embedded += batch.length;
140
+ slowest = Math.max(slowest, Date.now() - started);
122
141
  }
123
142
  const left = (await source.chunksToEmbed(key, { limit: 1, ...(after === undefined ? {} : { after }) })).length > 0;
124
143
  return { model: model.id, embedded, left };
@@ -130,6 +149,14 @@ const embedChunks = async (store, source, { model: choice, maxChunks = Number.PO
130
149
  */
131
150
  const enrichedFirst = async (store, types, options, embed) => {
132
151
  let enrichment;
152
+ const time = stopsAt(options.deadline) - Date.now();
153
+ // Out of time, the embed answers that it stopped; enrichment that runs into the deadline fails and is retried.
154
+ if (time <= 0 || options.signal?.aborted)
155
+ return embed();
156
+ const signals = [
157
+ ...(options.signal ? [options.signal] : []),
158
+ ...(Number.isFinite(time) ? [AbortSignal.timeout(time)] : []),
159
+ ];
133
160
  try {
134
161
  const run = await enrichRecords(store, {
135
162
  env: options.env ?? process.env,
@@ -137,6 +164,7 @@ const enrichedFirst = async (store, types, options, embed) => {
137
164
  ...(options.app ? { app: options.app } : {}),
138
165
  ...(options.keyring ? { keyring: options.keyring } : {}),
139
166
  ...options.enrichWith,
167
+ ...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
140
168
  });
141
169
  if (run.status !== "off")
142
170
  enrichment = run;
@@ -4,5 +4,7 @@ export interface SkillValidation {
4
4
  file?: string;
5
5
  version?: string;
6
6
  program?: Command;
7
+ /** The most SKILL.md may weigh, in bytes: an agent carries it in every later turn, the linked files only when read. */
8
+ maxBytes?: number;
7
9
  }
8
10
  export declare const validateSkill: (content: string, options?: SkillValidation) => string[];
@@ -1,5 +1,5 @@
1
- import { existsSync } from "node:fs";
2
- import { dirname, resolve } from "node:path";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
3
  import { parseDocument } from "yaml";
4
4
  // The Agent Skills specification asks for string values; OpenClaw and ClawHub read their install and requirement
5
5
  // declarations only from an object at `metadata.openclaw`, so that one key is a mapping.
@@ -44,14 +44,37 @@ export const validateSkill = (content, options = {}) => {
44
44
  problems.push("skill metadata must contain string values, and metadata.openclaw a mapping");
45
45
  if (options.version && fields.metadata?.version !== options.version)
46
46
  problems.push("emitted skill version must match the binary");
47
- const body = content.slice(match[0].length);
47
+ if (options.maxBytes !== undefined) {
48
+ const bytes = Buffer.byteLength(content);
49
+ if (bytes > options.maxBytes)
50
+ problems.push(`SKILL.md is ${bytes} bytes, over ${options.maxBytes}: move what only some tasks need into linked files`);
51
+ }
52
+ const seen = new Set(options.file ? [options.file] : []);
53
+ for (const problem of bodyProblems(content.slice(match[0].length), options, seen))
54
+ problems.push(problem);
55
+ return [...new Set(problems)];
56
+ };
57
+ /**
58
+ * Relative links that lead nowhere and command paths the program does not have, in a skill's body and, through its
59
+ * relative Markdown links, in every file beside it that it links: those are loaded in its place.
60
+ */
61
+ const bodyProblems = (body, options, seen) => {
62
+ const problems = [];
48
63
  if (options.file) {
49
64
  for (const link of body.matchAll(/\[[^\]]*\]\(([^\s)]+)\)/g)) {
50
65
  const target = (link[1] ?? "").split("#")[0] ?? "";
51
66
  if (!target || /^(?:[a-z]+:|\/)/i.test(target))
52
67
  continue;
53
- if (!existsSync(resolve(dirname(options.file), target)))
68
+ const path = resolve(dirname(options.file), target);
69
+ if (!existsSync(path)) {
54
70
  problems.push(`missing skill reference: ${target}`);
71
+ continue;
72
+ }
73
+ if (!path.endsWith(".md") || seen.has(path))
74
+ continue;
75
+ seen.add(path);
76
+ for (const problem of bodyProblems(readFileSync(path, "utf8"), { ...options, file: path }, seen))
77
+ problems.push(`${basename(path)}: ${problem}`);
55
78
  }
56
79
  }
57
80
  if (options.program) {
@@ -82,5 +105,5 @@ export const validateSkill = (content, options = {}) => {
82
105
  }
83
106
  }
84
107
  }
85
- return [...new Set(problems)];
108
+ return problems;
86
109
  };
@@ -5,7 +5,7 @@ import { IDENTITY_LINK_KIND, } from "../identity-links.js";
5
5
  import { rejectedEvidence, sidesOf } from "./identity-link-rows.js";
6
6
  import { openIdentityLink } from "./identity-proposals.js";
7
7
  import { isOwner, mergePerson, recordOf, required, survivorOf } from "./person-links.js";
8
- import { emailHolders, phoneHolders, phonePairJoins, sharedLine, } from "./person-match-scan.js";
8
+ import { emailHolders, oneHolderPerSource, phoneHolders, phonePairJoins, sharedLine, } from "./person-match-scan.js";
9
9
  import { mergeId, merges } from "./person-merges.js";
10
10
  import { resolvePersonLinks } from "./person-resolution.js";
11
11
  import { separated } from "./person-separation.js";
@@ -24,7 +24,7 @@ const weaknessOf = (context, kind, value, holders, sides, others) => {
24
24
  return "role-address";
25
25
  if (sharedLine(context, holders))
26
26
  return "company";
27
- if (others > 0)
27
+ if (others > 0 && !oneHolderPerSource(holders))
28
28
  return "shared";
29
29
  if (kind === "phone" && !isMobilePhone(value))
30
30
  return "landline";
@@ -53,6 +53,8 @@ export interface EventSearch {
53
53
  after?: string;
54
54
  limit: number;
55
55
  }): Promise<EventChunkToEmbed[]>;
56
+ /** How many live events' pieces have no vector of `model` yet: what `chunksToEmbed` would still give, at most. */
57
+ chunksLeft(model: string): Promise<number>;
56
58
  /** Whether any live event with a searchable copy in these accounts has a vector of `model`. */
57
59
  embedded(model: string, options?: {
58
60
  accountIds?: string[];
@@ -105,6 +105,16 @@ export const eventSearchOver = (context) => {
105
105
  });
106
106
  },
107
107
  eventIndexState: async () => corpusIndexState(database, CORPORA.event),
108
+ chunksLeft: async (model) => {
109
+ drain();
110
+ const scope = live(undefined);
111
+ const row = database
112
+ .prepare(`SELECT count(DISTINCT k.content_hash) AS left FROM chunks k
113
+ WHERE 1${scope.sql}
114
+ AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`)
115
+ .get(...scope.params, model);
116
+ return Number(row?.left ?? 0);
117
+ },
108
118
  chunksToEmbed: async (model, { after, limit }) => {
109
119
  drain();
110
120
  const scope = live(undefined);
@@ -126,6 +126,8 @@ export interface NoteSearch extends DocumentPictureStore {
126
126
  after?: string;
127
127
  limit: number;
128
128
  }): Promise<NoteChunkToEmbed[]>;
129
+ /** How many live chunks have no vector of `model` yet: what `chunksToEmbed` would still give, at most. */
130
+ chunksLeft(model: string): Promise<number>;
129
131
  /** Whether any live chunk in this scope has a vector of `model`: none means meaning search has nothing to rank. */
130
132
  embedded(model: string, options: {
131
133
  folderIds?: string[];
@@ -401,6 +401,16 @@ export const noteSearchOver = (context) => {
401
401
  await new Promise((resolve) => setImmediate(resolve));
402
402
  }
403
403
  },
404
+ chunksLeft: async (model) => {
405
+ drain();
406
+ const scope = live(undefined, undefined);
407
+ const row = database
408
+ .prepare(`SELECT count(DISTINCT k.content_hash) AS left FROM chunks k
409
+ WHERE 1${scope.sql}
410
+ AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`)
411
+ .get(...scope.params, model);
412
+ return Number(row?.left ?? 0);
413
+ },
404
414
  chunksToEmbed: async (model, { after, limit }) => {
405
415
  drain();
406
416
  const scope = live(undefined, undefined);
@@ -26,6 +26,11 @@ export declare const PROPOSAL_SCORE: {
26
26
  * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
27
27
  */
28
28
  export declare const phonePairJoins: (phone: string, holders: Holder[]) => boolean;
29
+ /**
30
+ * BUG-774: holders that each come from a different source are one human seen by each of them (their CRM card, their
31
+ * WhatsApp, their call), not people on one line, however many person rows they still are.
32
+ */
33
+ export declare const oneHolderPerSource: (holders: Holder[]) => boolean;
29
34
  export interface Holder {
30
35
  identity: number;
31
36
  provider: string;
@@ -19,7 +19,7 @@ export const RULE = { bot: "rule", kind: "rule" };
19
19
  const MOST_SHARING = 6;
20
20
  const CURSOR = "people.scan";
21
21
  /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
22
- const RULES = 5;
22
+ const RULES = 6;
23
23
  /**
24
24
  * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
25
25
  * The owner's word (2026-11-11): `hr@` is often one person's, so it starts below `info@`.
@@ -49,6 +49,11 @@ export const PROPOSAL_SCORE = {
49
49
  */
50
50
  export const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
51
51
  (holders.some(({ externalId }) => externalId === `phone:${phone}`) && isMobilePhone(phone));
52
+ /**
53
+ * BUG-774: holders that each come from a different source are one human seen by each of them (their CRM card, their
54
+ * WhatsApp, their call), not people on one line, however many person rows they still are.
55
+ */
56
+ export const oneHolderPerSource = (holders) => new Set(holders.map(({ list }) => list)).size === holders.length;
52
57
  /** NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. */
53
58
  const addressGroupJoins = (people) => people <= 2;
54
59
  /** A bot or a service account shares its number or address with whoever runs it; it is nobody's person. */
@@ -264,8 +269,9 @@ const tooMany = (pass, people, reason, signal) => {
264
269
  };
265
270
  const skipShared = (pass, people, signal) => pass.result.skipped.push({ persons: [...people.keys()].map(String), signal, reason: `identity.shared-${signal}` });
266
271
  /**
267
- * A number two people have joins them (NEED-2445); one that more share, or that once proposed, proposes. A company's
268
- * line does neither.
272
+ * A number two people have joins them (NEED-2445), and so does one each source has once (BUG-774); one that more
273
+ * share proposes. A company's line does neither. A proposal still open for the pair never keeps it from joining
274
+ * (BUG-775): the join settles it.
269
275
  */
270
276
  const samePhone = (pass, phone, holders) => {
271
277
  const people = peopleOf(pass.context, holders);
@@ -273,11 +279,12 @@ const samePhone = (pass, phone, holders) => {
273
279
  return;
274
280
  if (sharedLine(pass.context, holders))
275
281
  return skipShared(pass, people, "phone");
276
- const [into, from] = [...people.keys()].sort((a, b) => a - b);
277
- if (people.size === 2 && phonePairJoins(phone, holders) && !pass.index.known(from, into))
278
- join(pass, { from, into, identity: people.get(from), with: people.get(into) }, "phone");
279
- else
280
- proposeEachPair(pass, people, "phone");
282
+ if (!(people.size === 2 || oneHolderPerSource(holders)) || !phonePairJoins(phone, holders))
283
+ return proposeEachPair(pass, people, "phone");
284
+ const [first, ...rest] = [...people.keys()].sort((a, b) => a - b);
285
+ let into = first;
286
+ for (const from of rest)
287
+ into = join(pass, { from, into, identity: people.get(from), with: people.get(into) }, "phone");
281
288
  };
282
289
  const nameOf = ({ database }, person) => {
283
290
  const name = database.prepare("SELECT name FROM persons WHERE id = ?").get(person)?.name;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.679.0",
3
+ "version": "0.680.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",
@@ -300,7 +300,7 @@
300
300
  "@types/pngjs": "6.0.5",
301
301
  "@types/ssh2": "1.15.5",
302
302
  "@vitest/coverage-v8": "^5.0.5",
303
- "@wirecat/cli-base": "0.103.0",
303
+ "@wirecat/cli-base": "0.106.0",
304
304
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
305
305
  "ajv": "8.17.1",
306
306
  "commander": "15.0.0",
@@ -324,7 +324,7 @@
324
324
  },
325
325
  "peerDependencies": {
326
326
  "@napi-rs/canvas": ">=0.1.69 <2",
327
- "@wirecat/cli-base": ">=0.103.0 <1.0.0",
327
+ "@wirecat/cli-base": ">=0.106.0 <1.0.0",
328
328
  "commander": ">=15",
329
329
  "mysql2": "^3.24.6",
330
330
  "pg": "^8.23.1",