@wirecat/cli-core 0.663.0 → 0.664.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 (97) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/chat-sending-command.d.ts +14 -0
  4. package/dist/cli/chat-sending-command.js +64 -0
  5. package/dist/cli/context.d.ts +7 -0
  6. package/dist/cli/context.js +12 -4
  7. package/dist/cli/index.d.ts +2 -0
  8. package/dist/cli/index.js +2 -0
  9. package/dist/cli/meeting-meaning-command.d.ts +47 -0
  10. package/dist/cli/meeting-meaning-command.js +136 -0
  11. package/dist/cli/meeting-preparation-answer.d.ts +6 -0
  12. package/dist/cli/meeting-preparation-projects.d.ts +6 -0
  13. package/dist/cli/meeting-preparation-read.d.ts +6 -0
  14. package/dist/cli/meeting-tags-command.d.ts +18 -0
  15. package/dist/cli/meeting-tags-command.js +74 -0
  16. package/dist/cli/messenger/conversation-answers.d.ts +1 -1
  17. package/dist/cli/messenger/conversation-answers.js +1 -0
  18. package/dist/cli/messenger/conversations-command.js +38 -12
  19. package/dist/cli/messenger/models-command.js +7 -0
  20. package/dist/cli/messenger/records-command.d.ts +4 -1
  21. package/dist/cli/messenger/records-command.js +6 -1
  22. package/dist/cli/model-catalogue-command.js +2 -0
  23. package/dist/cli/profile-token.d.ts +15 -1
  24. package/dist/cli/profile-token.js +103 -7
  25. package/dist/cli/program.js +2 -2
  26. package/dist/domain/links.d.ts +11 -0
  27. package/dist/domain/links.js +4 -0
  28. package/dist/entities/chat-sending.d.ts +10 -0
  29. package/dist/entities/chat-sending.js +11 -0
  30. package/dist/entities/index.d.ts +43 -1
  31. package/dist/entities/index.js +6 -2
  32. package/dist/entities/meeting-preparation.d.ts +6 -0
  33. package/dist/entities/meeting.d.ts +1 -1
  34. package/dist/entities/meeting.js +1 -1
  35. package/dist/errors/reasons.js +25 -1
  36. package/dist/mcp/meeting-preparation.d.ts +6 -0
  37. package/dist/meetings/answers.d.ts +7 -0
  38. package/dist/meetings/answers.js +4 -0
  39. package/dist/meetings/index.d.ts +1 -0
  40. package/dist/meetings/index.js +1 -0
  41. package/dist/meetings/mcp/search.d.ts +6 -0
  42. package/dist/meetings/project-evidence-answer.d.ts +6 -0
  43. package/dist/meetings/tag-answers.d.ts +43 -0
  44. package/dist/meetings/tag-answers.js +41 -0
  45. package/dist/models/chat-sending.d.ts +24 -0
  46. package/dist/models/chat-sending.js +40 -0
  47. package/dist/runs/events.d.ts +1 -1
  48. package/dist/search/question-plan.d.ts +2 -0
  49. package/dist/search/question-plan.js +2 -0
  50. package/dist/search/task-similarity.d.ts +1 -0
  51. package/dist/search/task-similarity.js +1 -1
  52. package/dist/services/embeddings-search.js +19 -5
  53. package/dist/services/embeddings.d.ts +4 -0
  54. package/dist/services/index.d.ts +2 -0
  55. package/dist/services/index.js +2 -0
  56. package/dist/services/meeting-meaning.d.ts +47 -0
  57. package/dist/services/meeting-meaning.js +158 -0
  58. package/dist/services/meeting-tags.d.ts +27 -0
  59. package/dist/services/meeting-tags.js +81 -0
  60. package/dist/services/messages-discovery.js +2 -2
  61. package/dist/sftp/index.d.ts +1 -1
  62. package/dist/sftp/index.js +1 -1
  63. package/dist/sftp/session.d.ts +30 -4
  64. package/dist/sftp/session.js +195 -11
  65. package/dist/sftp/ssh2.d.ts +19 -4
  66. package/dist/sftp/ssh2.js +144 -17
  67. package/dist/speech/cloud.d.ts +47 -0
  68. package/dist/speech/cloud.js +73 -0
  69. package/dist/speech/decode.d.ts +36 -9
  70. package/dist/speech/decode.js +208 -61
  71. package/dist/speech/index.d.ts +2 -1
  72. package/dist/speech/index.js +2 -1
  73. package/dist/speech/openai.d.ts +4 -0
  74. package/dist/speech/openai.js +13 -12
  75. package/dist/sql/index.d.ts +1 -0
  76. package/dist/sql/index.js +1 -0
  77. package/dist/sql/reader.d.ts +95 -0
  78. package/dist/sql/reader.js +214 -0
  79. package/dist/store/sqlite/drizzle/bun.js +4 -4
  80. package/dist/store/sqlite/drizzle/bun.js.map +1 -1
  81. package/dist/store/sqlite/drizzle/core.js +5 -5
  82. package/dist/store/sqlite/drizzle/core.js.map +1 -1
  83. package/dist/store/sqlite/drizzle/node.js +4 -4
  84. package/dist/store/sqlite/drizzle/node.js.map +1 -1
  85. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js → shared-5XR7K42U.js} +58 -58
  86. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js.map → shared-5XR7K42U.js.map} +1 -1
  87. package/dist/store/sqlite/knowledge.d.ts +1 -1
  88. package/dist/store/sqlite/knowledge.js +8 -4
  89. package/dist/store/sqlite/labelled.d.ts +5 -0
  90. package/dist/store/sqlite/labelled.js +6 -0
  91. package/dist/store/sqlite/link-row.d.ts +1 -0
  92. package/dist/store/sqlite/link-row.js +2 -0
  93. package/dist/store/sqlite/notes.d.ts +1 -1
  94. package/dist/store/sqlite/notes.js +1 -1
  95. package/package.json +18 -3
  96. package/parity.json +20 -1
  97. package/skills/link-conversations/SKILL.md +1 -1
@@ -0,0 +1,158 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ const bounded = (value, maximum) => value === undefined || (Number.isSafeInteger(value) && value > 0 && value <= maximum);
3
+ export const validateMeetingModel = (options) => {
4
+ if (typeof options.model !== "string" || !options.model.trim() || options.model.length > 1000)
5
+ throw new CliError("validation_error", "select an explicit embedding model");
6
+ if (options.baseUrl === undefined) {
7
+ if (options.dims !== undefined)
8
+ throw new CliError("validation_error", "dimensions require an explicit remote base URL");
9
+ return;
10
+ }
11
+ let url;
12
+ try {
13
+ url = new URL(options.baseUrl);
14
+ }
15
+ catch {
16
+ throw new CliError("validation_error", "embedding base URL must be an HTTP or HTTPS URL");
17
+ }
18
+ if (!["http:", "https:"].includes(url.protocol) ||
19
+ url.username ||
20
+ url.password ||
21
+ url.search ||
22
+ url.hash ||
23
+ !/^[\w./:-]{1,200}$/.test(options.model) ||
24
+ options.dims === undefined ||
25
+ !bounded(options.dims, 8192))
26
+ throw new CliError("validation_error", "remote embeddings require an HTTP base URL without credentials and explicit dimensions");
27
+ };
28
+ export const validateMeetingMeaningSearch = (query, options) => {
29
+ validateMeetingModel(options);
30
+ if (typeof query !== "string" ||
31
+ !query.trim() ||
32
+ Buffer.byteLength(query, "utf8") > 65536 ||
33
+ !bounded(options.limit, 1000) ||
34
+ !bounded(options.maxChunks, 100000) ||
35
+ !bounded(options.maxRows, 100000) ||
36
+ !bounded(options.maxTextBytes, 64 * 1024 * 1024))
37
+ throw new CliError("validation_error", "meeting semantic search requires a nonempty bounded query and positive limits");
38
+ };
39
+ export const validateMeetingEmbeddings = (options) => {
40
+ validateMeetingModel(options);
41
+ if (!bounded(options.limit, 1000) ||
42
+ !bounded(options.maxRows, 100000) ||
43
+ !bounded(options.maxTextBytes, 64 * 1024 * 1024))
44
+ throw new CliError("validation_error", "meeting embedding generation requires valid bounded limits");
45
+ };
46
+ // The embedding runtime is heavy; a command that never asks for meaning never loads it.
47
+ const loadApi = async () => {
48
+ const [model, combined, semantic] = await Promise.all([
49
+ import("./meeting-model.js"),
50
+ import("./meeting-combined.js"),
51
+ import("./meeting-semantic.js"),
52
+ ]);
53
+ return { ...model, ...combined, ...semantic };
54
+ };
55
+ const checkCancelled = (signal) => {
56
+ if (!signal?.aborted)
57
+ return;
58
+ if (signal.reason instanceof CliError)
59
+ throw signal.reason;
60
+ const timedOut = signal.reason instanceof Error && signal.reason.name === "TimeoutError";
61
+ throw new CliError(timedOut ? "timeout" : "cancelled", timedOut ? "command timed out" : "command cancelled");
62
+ };
63
+ /**
64
+ * Search by meaning and the vectors it reads, over one account's stored meetings. A local model keeps the
65
+ * transcripts on this computer; `baseUrl` sends passages to that service and is only ever chosen by the caller.
66
+ */
67
+ export const meetingMeaning = (store, accountId, options = {}) => {
68
+ if (!Number.isSafeInteger(accountId) || accountId < 1)
69
+ throw new CliError("validation_error", "meeting vectors require a selected positive account ID");
70
+ const load = options.load ?? loadApi;
71
+ const choice = (api, input) => input.baseUrl === undefined
72
+ ? input.model
73
+ : { remote: api.createMeetingRemoteModel({ model: input.model, baseUrl: input.baseUrl, dims: input.dims }) };
74
+ const budget = (input) => ({
75
+ maxRows: input.maxRows,
76
+ maxTextBytes: input.maxTextBytes,
77
+ signal: input.signal,
78
+ });
79
+ // rebuild has no "new transcripts only" mode, so every pass splits every current transcript again; only
80
+ // passages without a vector for this model reach the embedder.
81
+ const splitAll = async (input) => {
82
+ let afterTranscriptId;
83
+ let pages = 0;
84
+ for (;;) {
85
+ checkCancelled(input.signal);
86
+ const page = await store.meetingVectors.rebuild({ accountId, limit: 1000, afterTranscriptId, ...budget(input) });
87
+ pages += 1;
88
+ if (!page.hasMore || page.nextTranscriptId === undefined)
89
+ return { pages };
90
+ afterTranscriptId = page.nextTranscriptId;
91
+ }
92
+ };
93
+ const buildMissing = async (api, embedder, input) => {
94
+ await splitAll(input);
95
+ let afterHash;
96
+ for (;;) {
97
+ checkCancelled(input.signal);
98
+ const batch = await api.applyMeetingEmbedding(store.meetingVectors, accountId, embedder, {
99
+ afterHash,
100
+ ...budget(input),
101
+ });
102
+ if (!batch.hasMore || batch.nextHash === undefined)
103
+ return;
104
+ afterHash = batch.nextHash;
105
+ }
106
+ };
107
+ return {
108
+ search: async (query, input) => {
109
+ validateMeetingMeaningSearch(query, input);
110
+ checkCancelled(input.signal);
111
+ const api = await load();
112
+ checkCancelled(input.signal);
113
+ const embedder = await api.openMeetingEmbedder(choice(api, input), { env: options.env, signal: input.signal });
114
+ try {
115
+ if (input.buildMissing)
116
+ await buildMissing(api, embedder, input);
117
+ return await api.searchMeetingsCombined(store, embedder, query, {
118
+ ...input.selection,
119
+ accountId,
120
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
121
+ ...(input.after === undefined ? {} : { after: input.after }),
122
+ ...(input.maxChunks === undefined ? {} : { maxChunks: input.maxChunks }),
123
+ ...(input.maxRows === undefined ? {} : { maxRows: input.maxRows }),
124
+ ...(input.maxTextBytes === undefined ? {} : { maxTextBytes: input.maxTextBytes }),
125
+ ...(input.signal ? { signal: input.signal } : {}),
126
+ });
127
+ }
128
+ finally {
129
+ await embedder.close();
130
+ }
131
+ },
132
+ generate: async (input) => {
133
+ validateMeetingEmbeddings(input);
134
+ checkCancelled(input.signal);
135
+ const api = await load();
136
+ checkCancelled(input.signal);
137
+ const selected = choice(api, input);
138
+ const descriptor = api.meetingEmbeddingModel(selected, options.env);
139
+ if (input.yes !== true)
140
+ return api.proposeMeetingEmbedding(store.meetingVectors, accountId, descriptor, { signal: input.signal });
141
+ const embedder = await api.openMeetingEmbedder(selected, { env: options.env, signal: input.signal });
142
+ try {
143
+ checkCancelled(input.signal);
144
+ // Passages that already have a vector are never offered again, so the next run takes the next batch.
145
+ const rebuild = await splitAll(input);
146
+ checkCancelled(input.signal);
147
+ const result = await api.applyMeetingEmbedding(store.meetingVectors, accountId, embedder, {
148
+ maxChunks: input.limit,
149
+ ...budget(input),
150
+ });
151
+ return { ...result, applied: true, model: descriptor, rebuild };
152
+ }
153
+ finally {
154
+ await embedder.close();
155
+ }
156
+ },
157
+ };
158
+ };
@@ -0,0 +1,27 @@
1
+ import type { MeetingTagChange, MeetingTagged } from "../meetings/index.js";
2
+ import type { MessageStore } from "../store/store.js";
3
+ /** The meetings a tag change acts on: these store ids, or every meeting with a hit of a `search meetings` query. */
4
+ export type MeetingTagTarget = {
5
+ meetings: number[];
6
+ } | {
7
+ matching: string;
8
+ };
9
+ export interface MeetingTags {
10
+ add(target: MeetingTagTarget, tags: string[], signal?: AbortSignal): Promise<MeetingTagChange>;
11
+ remove(target: MeetingTagTarget, tags: string[], signal?: AbortSignal): Promise<MeetingTagChange>;
12
+ list(request: {
13
+ tag?: string;
14
+ limit: number;
15
+ offset: number;
16
+ }): Promise<{
17
+ items: MeetingTagged[];
18
+ hasMore: boolean;
19
+ }>;
20
+ }
21
+ type Store = Pick<MessageStore, "meetings" | "knowledge">;
22
+ /**
23
+ * The owner's labels on one account's meetings, kept in the store's taggings like every other tag, so `--tag` and
24
+ * `tag:` in `search meetings` select them. A mark stays when a new transcript no longer says the words.
25
+ */
26
+ export declare const meetingTags: (store: Store, accountId: number) => MeetingTags;
27
+ export {};
@@ -0,0 +1,81 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { normalizeTag } from "../domain/tags.js";
3
+ import { searchMeetingHits } from "./meeting-hit-search.js";
4
+ const keyOf = async (store, accountId) => {
5
+ const owner = await store.meetings.account(accountId);
6
+ if (!owner)
7
+ throw new CliError("not_found", `meeting account ${accountId} is not in the store`);
8
+ return { provider: owner.provider, account: owner.account };
9
+ };
10
+ const tagsOf = (given) => {
11
+ if (given.length === 0)
12
+ throw new CliError("validation_error", "name at least one tag");
13
+ return [...new Set(given.map(normalizeTag))];
14
+ };
15
+ /** Every page of the search, so a word said in a thousand calls marks all of them; hits come one per line. */
16
+ const matchedMeetings = async (store, accountId, query, signal) => {
17
+ const found = new Set();
18
+ let after;
19
+ for (;;) {
20
+ const page = await searchMeetingHits(store, query, {
21
+ accountId,
22
+ limit: 1000,
23
+ ...(after === undefined ? {} : { after }),
24
+ ...(signal ? { signal } : {}),
25
+ });
26
+ for (const hit of page.items)
27
+ found.add(hit.meetingId);
28
+ if (!page.hasMore || page.nextCursor === null)
29
+ return [...found];
30
+ after = page.nextCursor;
31
+ }
32
+ };
33
+ const meetingsOf = async (store, accountId, target, signal) => {
34
+ if ("matching" in target)
35
+ return matchedMeetings(store, accountId, target.matching, signal);
36
+ const ids = [...new Set(target.meetings)];
37
+ // A meeting of another account is not found, as if it were not stored.
38
+ for (const meetingId of ids)
39
+ await store.meetings.meetingMetadata({ accountId, meetingId, ...(signal ? { signal } : {}) });
40
+ return ids;
41
+ };
42
+ /**
43
+ * The owner's labels on one account's meetings, kept in the store's taggings like every other tag, so `--tag` and
44
+ * `tag:` in `search meetings` select them. A mark stays when a new transcript no longer says the words.
45
+ */
46
+ export const meetingTags = (store, accountId) => {
47
+ const change = (operation) => async (target, given, signal) => {
48
+ const tags = tagsOf(given);
49
+ const key = await keyOf(store, accountId);
50
+ const meetings = await meetingsOf(store, accountId, target, signal);
51
+ const changed = [];
52
+ for (const meetingId of meetings) {
53
+ signal?.throwIfAborted();
54
+ const done = await store.knowledge[operation](key, { type: "meeting", id: String(meetingId) }, tags);
55
+ if (done.length > 0)
56
+ changed.push({ meetingId, tags: done });
57
+ }
58
+ return { accountId, tags, matched: meetings.length, changed };
59
+ };
60
+ return {
61
+ add: change("addTags"),
62
+ remove: change("removeTags"),
63
+ list: async ({ tag, limit, offset }) => {
64
+ const key = await keyOf(store, accountId);
65
+ const found = await store.knowledge.labelled(key, {
66
+ type: "meeting",
67
+ ...(tag === undefined ? {} : { tag: normalizeTag(tag) }),
68
+ limit,
69
+ offset,
70
+ });
71
+ const items = [];
72
+ for (const { target, tags } of found.items) {
73
+ if (target.type !== "meeting")
74
+ continue;
75
+ const meeting = await store.meetings.meetingMetadata({ accountId, meetingId: Number(target.id) });
76
+ items.push({ accountId, meetingId: meeting.id, title: meeting.title, startedAt: meeting.startedAt, tags });
77
+ }
78
+ return { items, hasMore: found.hasMore };
79
+ },
80
+ };
81
+ };
@@ -4,7 +4,7 @@ import { parseLocator } from "../domain/locator.js";
4
4
  import { fieldsOfQuery, meaningWords } from "../search/lucene/meaning-parts.js";
5
5
  import { validateFields } from "../search/lucene/registry.js";
6
6
  import { exhausted, MESSAGE_PARSING, outOfTime, QUERY_LIMITS } from "../search/lucene/types.js";
7
- import { anyOfTerms, lookupTerms, planQuestion, questionText, words } from "../search/question-plan.js";
7
+ import { anyOfTerms, joinedHyphens, lookupTerms, planQuestion, questionText, words } from "../search/question-plan.js";
8
8
  import { searchCombined } from "./messages-combined.js";
9
9
  import { prepareLucene, searchLucene } from "./messages-search.js";
10
10
  /** How many of the messages nearest in meaning join the fusion: the benchmark's pool (performance/search/evidence-pipeline). */
@@ -71,7 +71,7 @@ export const searchDiscovery = async (store, account, asked, messenger = {}, mea
71
71
  const question = root === undefined ? text : meaningWords(root);
72
72
  if (!question)
73
73
  return searchLucene(store, account, request, messenger);
74
- const terms = root === undefined ? lookupTerms(plan) : [...new Set(words(question))];
74
+ const terms = [...new Set([...(root === undefined ? lookupTerms(plan) : words(question)), ...joinedHyphens(text)])];
75
75
  if (!terms.length)
76
76
  return searchLucene(store, account, request, messenger);
77
77
  if (terms.length > 64)
@@ -1 +1 @@
1
- export { type HostKey, openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, type SftpAuth, type SftpClient, type SftpEntry, type SftpKind, type SftpOptions, type SftpReadOptions, type SftpTarget, sftpHostKey, } from "./session.js";
1
+ export { type HostKey, openSftp, openSshTunnel, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, type SftpAuth, type SftpClient, type SftpEntry, type SftpKind, type SftpOptions, type SftpReadOptions, type SftpStreamOptions, type SftpTarget, type SshTunnel, type SshTunnelOptions, sftpHostKey, } from "./session.js";
@@ -1 +1 @@
1
- export { openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, sftpHostKey, } from "./session.js";
1
+ export { openSftp, openSshTunnel, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, sftpHostKey, } from "./session.js";
@@ -36,11 +36,21 @@ export interface SftpReadOptions {
36
36
  /** A larger file is refused before its first byte is read, and a file that grows past it while read is too. */
37
37
  maxBytes: number;
38
38
  }
39
+ export interface SftpStreamOptions {
40
+ /** A larger file is refused before its first byte is read, and one that grows past it while read is too. */
41
+ maxBytes?: number;
42
+ }
39
43
  export interface SftpClient {
40
44
  /** The entries of a folder, without `.` and `..`. */
41
45
  list(path: string): Promise<SftpEntry[]>;
42
46
  stat(path: string): Promise<SftpEntry>;
43
47
  readFile(path: string, options: SftpReadOptions): Promise<Uint8Array>;
48
+ /**
49
+ * The file in order, piece by piece, with about a megabyte read ahead: a file of gigabytes is never held whole.
50
+ * A connection that breaks halfway is opened again and the read goes on where it stopped, once the bytes just
51
+ * before that point are the same; a file replaced meanwhile is refused (`sftp.file-changed`).
52
+ */
53
+ readStream(path: string, options?: SftpStreamOptions): AsyncIterable<Uint8Array>;
44
54
  close(): Promise<void>;
45
55
  }
46
56
  export type { HostKey, SftpEntry, SftpKind } from "./ssh2.js";
@@ -53,9 +63,25 @@ export declare const SFTP_RETRY: RetryConfig;
53
63
  * the key exchange and sends no credential.
54
64
  */
55
65
  export declare const sftpHostKey: (target: SftpTarget) => Promise<HostKey>;
66
+ export declare const openSftp: (input: SftpOptions) => Promise<SftpClient>;
67
+ export interface SshTunnelOptions extends SftpTarget {
68
+ username: string;
69
+ auth: SftpAuth;
70
+ /** The SSH server's fingerprint the owner confirmed, as for SFTP: `sftpHostKey` shows it. */
71
+ hostKey: string;
72
+ }
73
+ export interface SshTunnel {
74
+ /**
75
+ * A new connection to `host:port` as the SSH server sees it (`127.0.0.1:3306` is the server's own MySQL), shaped
76
+ * as a socket: hand it to a database driver's `stream` option, or to `openSqlReader`'s `socket`.
77
+ */
78
+ connect(host: string, port: number): Promise<Duplex>;
79
+ close(): Promise<void>;
80
+ }
56
81
  /**
57
- * A read-only SFTP connection: list, stat and read, nothing that writes. The host key must match the pinned
58
- * fingerprint before a credential is sent. Each operation is a request in the run's events (host and operation,
59
- * never a path or file content) and is tried again on a transient failure over a fresh connection.
82
+ * An SSH connection that only forwards, for a database that listens only on its own server (a FreePBX CDR database):
83
+ * `ssh -L` without a port on this computer, so no other program here can reach the database through it. The host key
84
+ * must match the pinned fingerprint before a credential is sent. Each forward is a request in the run's events (host
85
+ * only, never the address forwarded to) and is tried again on a transient failure over a fresh connection.
60
86
  */
61
- export declare const openSftp: (input: SftpOptions) => Promise<SftpClient>;
87
+ export declare const openSshTunnel: (input: SshTunnelOptions) => Promise<SshTunnel>;
@@ -1,6 +1,6 @@
1
1
  import { backoffMs, CliError, isCliError, realSleep, } from "@wirecat/cli-base";
2
2
  import { providerEvent, providerRequest } from "../cli/command-runs.js";
3
- import { openWire, probeHostKey } from "./ssh2.js";
3
+ import { openForwarder, openWire, probeHostKey, } from "./ssh2.js";
4
4
  export const SFTP_CONNECT_TIMEOUT_MS = 20_000;
5
5
  export const SFTP_OPERATION_TIMEOUT_MS = 30_000;
6
6
  /** Every operation only reads, so a transient failure is tried again: three attempts in all. */
@@ -62,7 +62,7 @@ const retrying = async (target, job) => {
62
62
  if (stop)
63
63
  throw stop;
64
64
  const answered = providerRequest(job.operation, events, {
65
- transport: "sftp",
65
+ transport: job.transport ?? "sftp",
66
66
  attempt,
67
67
  ...(waitMs === undefined ? {} : { waitMs }),
68
68
  });
@@ -130,12 +130,12 @@ export const sftpHostKey = async (target) => {
130
130
  });
131
131
  };
132
132
  const closedError = () => new CliError("validation_error", "the SFTP connection is closed", { reason: "sftp.closed" });
133
- const refuseOptions = (options) => {
133
+ const refuseOptions = (options, server = "SFTP") => {
134
134
  if (!options.hostKey?.trim())
135
- throw new CliError("configuration_error", "no host key is pinned for this SFTP server: show the owner its fingerprint (sftpHostKey) and pin the one confirmed", { reason: "sftp.host-key-missing" });
135
+ throw new CliError("configuration_error", `no host key is pinned for this ${server} server: show the owner its fingerprint (sftpHostKey) and pin the one confirmed`, { reason: "sftp.host-key-missing" });
136
136
  const auth = options.auth;
137
137
  if (!auth?.password && !auth?.privateKey)
138
- throw new CliError("configuration_error", "an SFTP connection needs a password or a private key", {
138
+ throw new CliError("configuration_error", `an ${server} connection needs a password or a private key`, {
139
139
  reason: "sftp.auth-missing",
140
140
  });
141
141
  };
@@ -144,17 +144,27 @@ const refuseOptions = (options) => {
144
144
  * fingerprint before a credential is sent. Each operation is a request in the run's events (host and operation,
145
145
  * never a path or file content) and is tried again on a transient failure over a fresh connection.
146
146
  */
147
+ const credentialsOf = (options) => ({
148
+ username: options.username,
149
+ ...("password" in options.auth
150
+ ? { password: options.auth.password }
151
+ : { privateKey: options.auth.privateKey, passphrase: options.auth.passphrase }),
152
+ });
153
+ const STREAM_CHUNK = 64 * 1024;
154
+ const STREAM_AHEAD = 16;
155
+ const fileChanged = () => new CliError("validation_error", "the file changed on the SFTP server while it was read; read it again", {
156
+ reason: "sftp.file-changed",
157
+ });
158
+ const tooLarge = (maxBytes) => new CliError("validation_error", `the file is larger than the read's limit of ${maxBytes} bytes`, {
159
+ reason: "sftp.too-large",
160
+ max_bytes: maxBytes,
161
+ });
147
162
  export const openSftp = async (input) => {
148
163
  refuseOptions(input);
149
164
  const options = seams(input);
150
165
  const pinned = normalized(options.hostKey);
151
166
  const operationMs = options.operationTimeoutMs ?? SFTP_OPERATION_TIMEOUT_MS;
152
- const credentials = {
153
- username: options.username,
154
- ...("password" in options.auth
155
- ? { password: options.auth.password }
156
- : { privateKey: options.auth.privateKey, passphrase: options.auth.passphrase }),
157
- };
167
+ const credentials = credentialsOf(options);
158
168
  let wire;
159
169
  let connecting;
160
170
  let closed = false;
@@ -204,6 +214,94 @@ export const openSftp = async (input) => {
204
214
  },
205
215
  ...(answer ? { answer } : {}),
206
216
  });
217
+ const timed = (current, work) => deadline(operationMs, options.sleep, () => current.close(), () => work());
218
+ async function* readStream(path, maxBytes) {
219
+ const retry = options.retry ?? SFTP_RETRY;
220
+ const events = options.events ?? providerEvent;
221
+ let position = 0;
222
+ let tail = Buffer.alloc(0);
223
+ let waitMs;
224
+ for (let attempt = 1;; attempt++) {
225
+ const stop = stoppedBy(options.signal);
226
+ if (stop)
227
+ throw stop;
228
+ const answered = providerRequest("sftp.stream", events, {
229
+ transport: "sftp",
230
+ attempt,
231
+ ...(waitMs === undefined ? {} : { waitMs }),
232
+ });
233
+ const from = position;
234
+ let current;
235
+ let file;
236
+ let finished = false;
237
+ try {
238
+ current = await connected();
239
+ const wire = current;
240
+ file = await timed(wire, () => wire.open(path));
241
+ const opened = file;
242
+ if (opened.size > maxBytes)
243
+ throw tooLarge(maxBytes);
244
+ if (position > 0) {
245
+ const again = await timed(wire, () => opened.read(position - tail.length, tail.length));
246
+ if (!again.equals(tail))
247
+ throw fileChanged();
248
+ }
249
+ const ahead = [];
250
+ let next = position;
251
+ const ask = () => {
252
+ const at = next;
253
+ const piece = timed(wire, () => opened.read(at, STREAM_CHUNK));
254
+ piece.catch(() => { });
255
+ ahead.push(piece);
256
+ next += STREAM_CHUNK;
257
+ };
258
+ while (ahead.length < STREAM_AHEAD)
259
+ ask();
260
+ for (;;) {
261
+ const piece = await ahead.shift();
262
+ if (piece.length > 0) {
263
+ position += piece.length;
264
+ if (position > maxBytes)
265
+ throw tooLarge(maxBytes);
266
+ tail = piece;
267
+ yield new Uint8Array(piece.buffer, piece.byteOffset, piece.length);
268
+ }
269
+ if (piece.length < STREAM_CHUNK) {
270
+ finished = true;
271
+ answered({ ids: { host: options.host }, bytes: position - from });
272
+ return;
273
+ }
274
+ ask();
275
+ }
276
+ }
277
+ catch (caught) {
278
+ const error = stoppedBy(options.signal) ?? (caught instanceof Expired ? timedOut("request", operationMs) : caught);
279
+ answered({ ids: { host: options.host }, error, ...(isCliError(error) ? { errorCode: error.code } : {}) });
280
+ finished = true;
281
+ const retryable = isCliError(error) && error.details.retryable === true;
282
+ if (retryable || caught instanceof Expired)
283
+ drop(current);
284
+ if (!retryable || options.signal?.aborted || attempt > retry.retries) {
285
+ if (retryable)
286
+ throw new CliError(error.code, error.message, { ...error.details, attempts: attempt });
287
+ throw error;
288
+ }
289
+ waitMs = backoffMs(attempt, retry, options.random);
290
+ try {
291
+ await options.sleep(waitMs, options.signal, "retry");
292
+ }
293
+ catch {
294
+ throw stoppedBy(options.signal) ?? error;
295
+ }
296
+ }
297
+ finally {
298
+ file?.close();
299
+ // The reader stopped early: what it took is this attempt's answer.
300
+ if (!finished)
301
+ answered({ ids: { host: options.host }, bytes: position - from });
302
+ }
303
+ }
304
+ }
207
305
  try {
208
306
  await retrying(options, { operation: "sftp.connect", run: () => connected() });
209
307
  }
@@ -221,6 +319,92 @@ export const openSftp = async (input) => {
221
319
  }));
222
320
  return operation("sftp.read", (current, touch) => current.read(path, maxBytes, touch), (bytes) => ({ bytes: bytes.length }));
223
321
  },
322
+ readStream: (path, { maxBytes = Number.POSITIVE_INFINITY } = {}) => {
323
+ if (maxBytes !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxBytes) || maxBytes < 0))
324
+ throw new CliError("validation_error", "maxBytes must be a whole number of bytes, 0 or more", {
325
+ reason: "input.invalid",
326
+ });
327
+ return readStream(path, maxBytes);
328
+ },
329
+ close: async () => {
330
+ closed = true;
331
+ options.signal?.removeEventListener("abort", abort);
332
+ drop();
333
+ },
334
+ };
335
+ };
336
+ /**
337
+ * An SSH connection that only forwards, for a database that listens only on its own server (a FreePBX CDR database):
338
+ * `ssh -L` without a port on this computer, so no other program here can reach the database through it. The host key
339
+ * must match the pinned fingerprint before a credential is sent. Each forward is a request in the run's events (host
340
+ * only, never the address forwarded to) and is tried again on a transient failure over a fresh connection.
341
+ */
342
+ export const openSshTunnel = async (input) => {
343
+ refuseOptions(input, "SSH");
344
+ const options = seams(input);
345
+ const pinned = normalized(options.hostKey);
346
+ const credentials = credentialsOf(options);
347
+ const target = { ...options, events: options.events ?? providerEvent };
348
+ let ssh;
349
+ let connecting;
350
+ let closed = false;
351
+ const drop = (failed = ssh) => {
352
+ if (ssh === failed)
353
+ ssh = undefined;
354
+ failed?.close();
355
+ };
356
+ const abort = () => drop();
357
+ options.signal?.addEventListener("abort", abort, { once: true });
358
+ const open = async () => {
359
+ const opened = await connectOnce(options, (signal) => openForwarder(wireOptions(options, credentials), (key) => normalized(key.fingerprint) === pinned, signal));
360
+ if (options.signal?.aborted || closed) {
361
+ opened.close();
362
+ throw stoppedBy(options.signal) ?? closedError();
363
+ }
364
+ ssh = opened;
365
+ return opened;
366
+ };
367
+ const connected = async () => {
368
+ if (closed)
369
+ throw closedError();
370
+ if (ssh && !ssh.closed)
371
+ return ssh;
372
+ connecting ??= open().finally(() => {
373
+ connecting = undefined;
374
+ });
375
+ return connecting;
376
+ };
377
+ try {
378
+ await retrying(target, { operation: "ssh.connect", transport: "ssh", run: () => connected() });
379
+ }
380
+ catch (error) {
381
+ options.signal?.removeEventListener("abort", abort);
382
+ throw error;
383
+ }
384
+ const operationMs = SFTP_CONNECT_TIMEOUT_MS;
385
+ return {
386
+ connect: (host, port) => retrying(target, {
387
+ operation: "ssh.forward",
388
+ transport: "ssh",
389
+ run: async () => {
390
+ const current = await connected();
391
+ try {
392
+ return await deadline(options.connectTimeoutMs ?? operationMs, options.sleep, () => current.close(), () => current.forward(host, port));
393
+ }
394
+ catch (error) {
395
+ if (error instanceof Expired) {
396
+ drop(current);
397
+ throw new CliError("timeout", "the SSH server did not open the forwarded connection in time", {
398
+ reason: "sftp.timeout",
399
+ retryable: true,
400
+ });
401
+ }
402
+ if (isCliError(error) && error.details.retryable === true && error.details.reason !== "ssh.forward-failed")
403
+ drop(current);
404
+ throw error;
405
+ }
406
+ },
407
+ }),
224
408
  close: async () => {
225
409
  closed = true;
226
410
  options.signal?.removeEventListener("abort", abort);
@@ -22,17 +22,32 @@ export interface WireOptions {
22
22
  /** Opens a stream already connected to the server, instead of a TCP connection to `host`. */
23
23
  socket?: (() => Duplex | Promise<Duplex>) | undefined;
24
24
  }
25
+ /** An open file, read by position: a stream reads it piece by piece and never holds it whole. */
26
+ export interface OpenFile {
27
+ size: number;
28
+ /** Whole seconds since 1970, to tell a file replaced between two connections. */
29
+ mtime: number;
30
+ /** Up to `length` bytes from `position`, fewer only at the end of the file. */
31
+ read(position: number, length: number): Promise<Buffer>;
32
+ close(): void;
33
+ }
25
34
  export interface Wire {
26
35
  list(path: string): Promise<SftpEntry[]>;
27
36
  stat(path: string): Promise<SftpEntry>;
28
37
  read(path: string, maxBytes: number, progress: () => void): Promise<Uint8Array>;
38
+ open(path: string): Promise<OpenFile>;
39
+ close(): void;
40
+ }
41
+ /** An SSH connection that only forwards: each `forward` is one TCP connection the server opens on the owner's behalf. */
42
+ export interface Forwarder {
43
+ forward(host: string, port: number): Promise<Duplex>;
29
44
  close(): void;
45
+ readonly closed: boolean;
30
46
  }
31
47
  export declare const hostKeyOf: (blob: Buffer) => HostKey;
32
- /**
33
- * Connects, checks the host key with `accept` before any credential is sent, and opens the SFTP channel. `signal`
34
- * ends the attempt and destroys the connection.
35
- */
48
+ /** Signs in as `connectClient` does and opens the SFTP channel. */
36
49
  export declare const openWire: (options: WireOptions, accept: (key: HostKey) => boolean, signal: AbortSignal) => Promise<Wire>;
50
+ /** Signs in as `connectClient` does, for forwarding only: no shell, no command, no SFTP. */
51
+ export declare const openForwarder: (options: WireOptions, accept: (key: HostKey) => boolean, signal: AbortSignal) => Promise<Forwarder>;
37
52
  /** Connects only as far as the server's host key, and returns it; no credential is sent. */
38
53
  export declare const probeHostKey: (options: WireOptions, signal: AbortSignal) => Promise<HostKey>;