@wirecat/cli-core 0.653.0 → 0.655.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 (49) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/cli/bot/mcp.js +2 -1
  3. package/dist/cli/command-availability.d.ts +3 -1
  4. package/dist/cli/command-availability.js +6 -4
  5. package/dist/cli/early-refusal.d.ts +5 -5
  6. package/dist/cli/early-refusal.js +7 -7
  7. package/dist/cli/messenger/search-answers.js +1 -0
  8. package/dist/cli/preview.js +8 -4
  9. package/dist/cli/program.js +3 -7
  10. package/dist/cli/setup-answers.d.ts +3 -2
  11. package/dist/cli/setup-answers.js +5 -6
  12. package/dist/domain/providers.js +2 -0
  13. package/dist/entities/hit.d.ts +2 -0
  14. package/dist/entities/hit.js +2 -0
  15. package/dist/entities/index.d.ts +7 -0
  16. package/dist/google/errors.d.ts +18 -0
  17. package/dist/google/errors.js +71 -0
  18. package/dist/google/index.d.ts +2 -0
  19. package/dist/google/index.js +2 -0
  20. package/dist/google/pages.d.ts +11 -0
  21. package/dist/google/pages.js +23 -0
  22. package/dist/kit/index.d.ts +1 -0
  23. package/dist/kit/index.js +1 -0
  24. package/dist/kit/sync-after-install.d.ts +26 -0
  25. package/dist/kit/sync-after-install.js +72 -0
  26. package/dist/mcp/agent.d.ts +3 -0
  27. package/dist/mcp/agent.js +5 -4
  28. package/dist/mcp/app-server.js +4 -1
  29. package/dist/mcp/bot/server.d.ts +2 -0
  30. package/dist/mcp/bot/server.js +2 -0
  31. package/dist/mcp/server.js +4 -1
  32. package/dist/meetings/answers.d.ts +11 -1
  33. package/dist/meetings/answers.js +17 -0
  34. package/dist/meetings/index.d.ts +3 -3
  35. package/dist/meetings/index.js +1 -1
  36. package/dist/meetings/pull.js +3 -0
  37. package/dist/meetings/source.d.ts +3 -1
  38. package/dist/meetings/store.d.ts +24 -0
  39. package/dist/meetings/store.js +1 -0
  40. package/dist/meetings/transcript-store.d.ts +9 -1
  41. package/dist/oauth/requests.js +22 -4
  42. package/dist/services/search-all.d.ts +2 -0
  43. package/dist/services/search-all.js +30 -11
  44. package/dist/store/sqlite/meeting-documents.d.ts +13 -0
  45. package/dist/store/sqlite/meeting-documents.js +110 -0
  46. package/dist/store/sqlite/meetings.js +5 -2
  47. package/package.json +5 -1
  48. package/dist/store/sqlite/meeting-transcript-documents.d.ts +0 -10
  49. package/dist/store/sqlite/meeting-transcript-documents.js +0 -52
package/dist/mcp/agent.js CHANGED
@@ -148,7 +148,7 @@ const keywordsOf = (examples) => [
148
148
  ...new Set(examples.flatMap((example) => example.split(/\s+/u).filter((word) => word !== "" && !word.startsWith("-")))),
149
149
  ];
150
150
  export const toolsFromCommands = (commands, options = {}) => {
151
- const { root = [], exclude = [], levels, keyOf, authority, readOnly = false, permissions } = options;
151
+ const { root = [], exclude = [], levels, keyOf, authority, readOnly = false, permissions, fetches } = options;
152
152
  return flatten(commands)
153
153
  .filter((info) =>
154
154
  // A group is offered only when it runs on its own; without an action it only prints its help.
@@ -162,9 +162,10 @@ export const toolsFromCommands = (commands, options = {}) => {
162
162
  (!(readOnly && (changesMessenger(info) || authority?.(info.path))) &&
163
163
  (levels === undefined && !(readOnly && permissions)
164
164
  ? true
165
- : commandAvailability(info, levels ?? {}, keyOf, authority, readOnly, true, permissions).available))))
165
+ : commandAvailability(info, levels ?? {}, keyOf, authority, readOnly, true, permissions, fetches)
166
+ .available))))
166
167
  .map((info) => ({
167
- availability: () => commandAvailability(info, options.currentLevels?.() ?? levels ?? {}, keyOf, authority, readOnly, true, permissions),
168
+ availability: () => commandAvailability(info, options.currentLevels?.() ?? levels ?? {}, keyOf, authority, readOnly, true, permissions, fetches),
168
169
  command: info.path.slice(root.length).join(" "),
169
170
  path: info.path,
170
171
  title: info.summary ?? info.description,
@@ -217,7 +218,7 @@ export const runCommandForAgent = async (program, path, input, ctx) => {
217
218
  throw new CliError("validation_error", `"${path.join(" ")}" runs until it is stopped; an agent call must return`);
218
219
  const levels = ctx.levels?.();
219
220
  const availability = (levels || ctx.readOnly || ctx.permissions) &&
220
- commandAvailability(info, levels ?? {}, ctx.keyOf, ctx.authority, ctx.readOnly, true, ctx.permissions);
221
+ commandAvailability(info, levels ?? {}, ctx.keyOf, ctx.authority, ctx.readOnly, true, ctx.permissions, ctx.fetches);
221
222
  if (availability && !availability.available)
222
223
  throw new CliError("permission_error", `${path.join(" ")}: ${availability.reason}`, {
223
224
  sent: false,
@@ -4,7 +4,7 @@ import { CliError, mcpErrorResult } from "@wirecat/cli-base";
4
4
  import { describeProgram } from "@wirecat/cli-base/commands";
5
5
  import { skillResource } from "@wirecat/cli-base/skill";
6
6
  import { environmentOf } from "../cli/context.js";
7
- import { changesAuthorityAt, judgedTargets, readsOverMcpAt } from "../cli/effects.js";
7
+ import { changesAuthorityAt, fetchesOnlyAt, judgedTargets, readsOverMcpAt } from "../cli/effects.js";
8
8
  import { DEFAULT_OUTPUT_BYTES } from "../cli/execution.js";
9
9
  import { rootOf } from "../cli/steps.js";
10
10
  import { mcpUrlOf } from "../http/public-url.js";
@@ -45,6 +45,7 @@ export const createAppServer = (command, context, options) => {
45
45
  const levels = () => options.resolveSettings(flags, { env: context.env }).permissions;
46
46
  const readOnly = () => readOnlyLockOf(app, context.env) !== undefined;
47
47
  const authority = changesAuthorityAt(root);
48
+ const fetches = fetchesOnlyAt(root);
48
49
  const targets = judgedTargets(root);
49
50
  const passed = Object.fromEntries(Object.entries(environment).filter(([key]) => !PER_RUN.has(key)));
50
51
  const tools = toolsFromCommands(program.commands, {
@@ -55,6 +56,7 @@ export const createAppServer = (command, context, options) => {
55
56
  readOnly: readOnly(),
56
57
  authority,
57
58
  fetchOnly: readsOverMcpAt(root),
59
+ fetches,
58
60
  permissions: options.permissions,
59
61
  });
60
62
  const availability = (one) => () => {
@@ -88,6 +90,7 @@ export const createAppServer = (command, context, options) => {
88
90
  levels,
89
91
  overrides,
90
92
  authority,
93
+ fetches,
91
94
  permissions: options.permissions,
92
95
  environment: passed,
93
96
  });
@@ -18,6 +18,8 @@ export interface BotServerOptions {
18
18
  authority?: (path: readonly string[]) => boolean;
19
19
  /** Whether a command only fetches into this machine (`fetchesOnlyAt`): offered through the read tool. */
20
20
  fetchOnly?: (path: readonly string[]) => boolean;
21
+ /** Whether a command only fetches into the store (`fetchesOnlyAt`): setup's "read only" answer lets it run. */
22
+ fetches?: (path: readonly string[]) => boolean;
21
23
  env: NodeJS.ProcessEnv;
22
24
  skill?: URL;
23
25
  }
@@ -34,6 +34,7 @@ export const createBotServer = (options) => {
34
34
  ...(options.keyOf ? { keyOf: options.keyOf } : {}),
35
35
  authority,
36
36
  ...(options.fetchOnly ? { fetchOnly: options.fetchOnly } : {}),
37
+ ...(options.fetches ? { fetches: options.fetches } : {}),
37
38
  offline: true,
38
39
  // Another bot's copy is this bot's to read only where `read_other_bots` says so.
39
40
  ...(settings.readOtherBots ? {} : { omit: ["all_bots", "bots"] }),
@@ -59,6 +60,7 @@ export const createBotServer = (options) => {
59
60
  levels,
60
61
  ...(options.keyOf ? { keyOf: options.keyOf } : {}),
61
62
  authority,
63
+ ...(options.fetches ? { fetches: options.fetches } : {}),
62
64
  ...(caller ? { caller } : {}),
63
65
  }));
64
66
  queue = next.catch(() => undefined);
@@ -8,7 +8,7 @@ import * as v from "valibot";
8
8
  import { findCommand } from "../cli/command-contract.js";
9
9
  import { environmentOf } from "../cli/context.js";
10
10
  import { refuseWriteBeforeConnecting } from "../cli/early-refusal.js";
11
- import { changesAuthorityAt, judgedTargets, readsOverMcpAt } from "../cli/effects.js";
11
+ import { changesAuthorityAt, fetchesOnlyAt, judgedTargets, readsOverMcpAt } from "../cli/effects.js";
12
12
  import { itemOf } from "../cli/envelope.js";
13
13
  import { DEFAULT_OUTPUT_BYTES } from "../cli/execution.js";
14
14
  import { recalledAccount } from "../cli/messenger/accounts.js";
@@ -104,6 +104,7 @@ export const createServer = (command, context, messenger, sessionOptions) => {
104
104
  }
105
105
  };
106
106
  const authority = changesAuthorityAt(root);
107
+ const fetches = fetchesOnlyAt(root);
107
108
  const stdin = (path) => {
108
109
  try {
109
110
  return stdinFieldOf(findCommand(root, path));
@@ -128,6 +129,7 @@ export const createServer = (command, context, messenger, sessionOptions) => {
128
129
  keyOf,
129
130
  authority,
130
131
  fetchOnly: readsOverMcpAt(root),
132
+ fetches,
131
133
  offline: true,
132
134
  stdin,
133
135
  }).map((one) => "sync_first" in one.input.entries && !syncAllowed(one.path)
@@ -219,6 +221,7 @@ export const createServer = (command, context, messenger, sessionOptions) => {
219
221
  overrides,
220
222
  keyOf,
221
223
  authority,
224
+ fetches,
222
225
  stdin,
223
226
  connection,
224
227
  environment: agentEnvironment,
@@ -3,7 +3,7 @@ import * as v from "valibot";
3
3
  import { type MeetingOwner } from "./item.js";
4
4
  import type { Summary, Transcript, TranscriptRow } from "./model.js";
5
5
  import type { MeetingSearchPage } from "./search-store.js";
6
- import type { MeetingDetails, SearchHit } from "./store.js";
6
+ import { type MeetingDetails, type SearchHit } from "./store.js";
7
7
  /** A passage `search meetings` found: a transcript cue, a chat line or a summary. */
8
8
  export declare const meetingHit: v.StrictObjectSchema<{
9
9
  /** The cue for a transcript passage, else the meeting. */
@@ -140,6 +140,16 @@ export declare const meetingDetails: v.StrictObjectSchema<{
140
140
  readonly size: v.NullableSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
141
141
  readonly url: v.NullableSchema<v.StringSchema<undefined>, undefined>;
142
142
  }, undefined>, undefined>;
143
+ /**
144
+ * The Drive files the meeting service saved for it, by role. `document` is the stored document (`document:<id>`) once
145
+ * a Drive profile has imported the file, else `null`: then `drive` can fetch it by `file_id`.
146
+ */
147
+ readonly documents: v.ArraySchema<v.StrictObjectSchema<{
148
+ readonly file_id: v.StringSchema<undefined>;
149
+ readonly role: v.PicklistSchema<readonly ["transcript", "recording", "notes"], undefined>;
150
+ readonly title: v.NullableSchema<v.StringSchema<undefined>, undefined>;
151
+ readonly document: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
152
+ }, undefined>, undefined>;
143
153
  }, undefined>;
144
154
  export type MeetingHitItem = v.InferOutput<typeof meetingHit>;
145
155
  export type MeetingTranscriptItem = v.InferOutput<typeof meetingTranscript>;
@@ -2,6 +2,7 @@ import { defineSteps, isoTime, reference, STEPS, stepOf, } from "@wirecat/cli-ba
2
2
  import * as v from "valibot";
3
3
  import { meeting, meetingItem } from "./item.js";
4
4
  import { formatMeetingReference, parseMeetingReference } from "./reference.js";
5
+ import { MEETING_DOCUMENT_ROLES } from "./store.js";
5
6
  const text = v.string();
6
7
  const count = v.pipe(v.number(), v.integer(), v.minValue(0));
7
8
  const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
@@ -93,6 +94,16 @@ export const meetingDetails = v.strictObject({
93
94
  size: v.nullable(count),
94
95
  url: v.nullable(text),
95
96
  })),
97
+ /**
98
+ * The Drive files the meeting service saved for it, by role. `document` is the stored document (`document:<id>`) once
99
+ * a Drive profile has imported the file, else `null`: then `drive` can fetch it by `file_id`.
100
+ */
101
+ documents: v.array(v.strictObject({
102
+ file_id: text,
103
+ role: v.picklist(MEETING_DOCUMENT_ROLES),
104
+ title: v.nullable(text),
105
+ document: v.nullable(reference),
106
+ })),
96
107
  });
97
108
  const meetingRef = (accountId, meetingId) => formatMeetingReference({ type: "meeting", accountId, meetingId });
98
109
  export const meetingTranscriptItem = (accountId, transcript, rows) => ({
@@ -172,6 +183,12 @@ export const meetingDetailsItem = (details, owner) => {
172
183
  size: one.size,
173
184
  url: one.url,
174
185
  })),
186
+ documents: (details.documents ?? []).map((one) => ({
187
+ file_id: one.fileId,
188
+ role: one.role,
189
+ title: one.title,
190
+ document: one.documentId === null ? null : `document:${one.documentId}`,
191
+ })),
175
192
  };
176
193
  };
177
194
  /** A list read whole: every item on one page. */
@@ -52,10 +52,10 @@ export type { MeetingSeriesCandidate, MeetingSeriesInventoryPage, MeetingSeriesI
52
52
  export { validateMeetingSeriesInventoryCursor } from "./series-inventory-validation.js";
53
53
  export type { MeetingSource, SourceParticipant } from "./source.js";
54
54
  export { aggregateMeetingCounts, aggregateMeetingStats, MEETING_COUNTS_GROUPINGS, type MeetingCounts, type MeetingCountsGrouping, type MeetingCountsInput, type MeetingCountsMeeting, type MeetingCountsRow, type MeetingSpeakerStats, type MeetingStats, type MeetingStatsInput, type MeetingStatsRow, type MeetingStatsSelection, type MeetingStatsStore, type MeetingWeekStats, NO_SERIES, } from "./stats.js";
55
- export type { ChatInput, ContractCase, EventCandidateFilter, IdentityInput, MeetingDetails, MeetingFilter, MeetingHitSource, MeetingInput, MeetingParticipant, MeetingSave, MeetingStore, NewRecord, ParticipantInput, SearchHit, TranscriptInput, TranscriptLanguageFill, TranscriptRowInput, } from "./store.js";
56
- export { READ_BUDGET_EXCEEDED } from "./store.js";
55
+ export type { ChatInput, ContractCase, EventCandidateFilter, IdentityInput, MeetingDetails, MeetingDocument, MeetingDocumentInput, MeetingDocumentRole, MeetingFilter, MeetingHitSource, MeetingInput, MeetingParticipant, MeetingSave, MeetingStore, NewRecord, ParticipantInput, SearchHit, TranscriptInput, TranscriptLanguageFill, TranscriptRowInput, } from "./store.js";
56
+ export { MEETING_DOCUMENT_ROLES, READ_BUDGET_EXCEEDED } from "./store.js";
57
57
  export { meetingTimestamp } from "./timestamp.js";
58
- export type { MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, TranscriptAppend, TranscriptAppendReceipt, UnlinkedTranscriptInput, } from "./transcript-store.js";
58
+ export type { DocumentMeeting, MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, TranscriptAppend, TranscriptAppendReceipt, UnlinkedTranscriptInput, } from "./transcript-store.js";
59
59
  export { parseTranscriptText, TranscriptTextError, type TranscriptTextHeader } from "./transcript-text.js";
60
60
  export { type MeetingMediaDescriptor, type MeetingRecognitionSegment, type MeetingTranscriptionContext, type MeetingTranscriptionOptions, type MeetingTranscriptionReceipt, type MeetingTranscriptionSource, transcribeMeeting, } from "./transcription.js";
61
61
  export { createUpcomingMeetingReader } from "./upcoming.js";
@@ -39,7 +39,7 @@ export { validateMeetingSeriesHistory, } from "./series-history.js";
39
39
  export { createMeetingSeriesInventoryReader } from "./series-inventory.js";
40
40
  export { validateMeetingSeriesInventoryCursor } from "./series-inventory-validation.js";
41
41
  export { aggregateMeetingCounts, aggregateMeetingStats, MEETING_COUNTS_GROUPINGS, NO_SERIES, } from "./stats.js";
42
- export { READ_BUDGET_EXCEEDED } from "./store.js";
42
+ export { MEETING_DOCUMENT_ROLES, READ_BUDGET_EXCEEDED } from "./store.js";
43
43
  export { meetingTimestamp } from "./timestamp.js";
44
44
  export { parseTranscriptText, TranscriptTextError } from "./transcript-text.js";
45
45
  export { transcribeMeeting, } from "./transcription.js";
@@ -98,6 +98,8 @@ export const pull = async (source, store, options) => {
98
98
  const chat = await read("chat", () => source.chat(id));
99
99
  const summary = await read("summary", () => source.summary(id));
100
100
  const attachments = await read("files", () => source.files(id));
101
+ const listDocuments = source.documents?.bind(source);
102
+ const documents = listDocuments ? await read("documents", () => listDocuments(id)) : undefined;
101
103
  const startedAt = timestamp(m.occurrence.startedAt);
102
104
  const endedAt = m.occurrence.endedAt === null ? null : timestamp(m.occurrence.endedAt);
103
105
  if (endedAt !== null && endedAt < startedAt)
@@ -161,6 +163,7 @@ export const pull = async (source, store, options) => {
161
163
  ]
162
164
  : undefined,
163
165
  attachments: attachments ?? undefined,
166
+ documents: documents ?? undefined,
164
167
  now,
165
168
  });
166
169
  // Without participants the rows cannot be linked: they are saved only when the meeting has no current
@@ -1,5 +1,5 @@
1
1
  import type { Metadata, SourceChatLine, SourceMeeting, SummaryContent, TranscriptLine } from "./model.js";
2
- import type { MeetingSave } from "./store.js";
2
+ import type { MeetingDocumentInput, MeetingSave } from "./store.js";
3
3
  export interface SourceParticipant {
4
4
  identityExternalId: string | null;
5
5
  email: string | null;
@@ -38,4 +38,6 @@ export interface MeetingSource {
38
38
  chat(occurrenceId: string): Promise<SourceChatLine[] | null>;
39
39
  summary(occurrenceId: string): Promise<SummaryContent | null>;
40
40
  files(occurrenceId: string): Promise<NonNullable<MeetingSave["attachments"]> | null>;
41
+ /** The Drive files the service saved for the occurrence: its transcript, recording and notes documents. */
42
+ documents?(occurrenceId: string): Promise<MeetingDocumentInput[] | null>;
41
43
  }
@@ -28,6 +28,26 @@ export interface TranscriptInput extends Omit<NewRecord<Transcript>, "meetingId"
28
28
  */
29
29
  driveFileId?: string;
30
30
  }
31
+ export declare const MEETING_DOCUMENT_ROLES: readonly ["transcript", "recording", "notes"];
32
+ export type MeetingDocumentRole = (typeof MEETING_DOCUMENT_ROLES)[number];
33
+ /**
34
+ * A Drive file the meeting service saved for the meeting: its transcript, its recording or its notes (Meet's
35
+ * `docsDestination.document`, `driveDestination.file`, Gemini's notes). Keyed by the Drive file id alone, so the Drive
36
+ * profile that imports the file may differ from the meeting's.
37
+ */
38
+ export interface MeetingDocumentInput {
39
+ fileId: string;
40
+ role: MeetingDocumentRole;
41
+ title?: string | null;
42
+ }
43
+ /** A meeting's Drive file, and the document it is once a Drive account has stored it. */
44
+ export interface MeetingDocument {
45
+ fileId: string;
46
+ role: MeetingDocumentRole;
47
+ title: string | null;
48
+ /** `null` while no Drive account holds the file, while two do (CORE-54), or while its document is deleted. */
49
+ documentId: number | null;
50
+ }
31
51
  export interface ChatInput extends Omit<NewRecord<ChatLine>, "meetingId" | "senderParticipantId"> {
32
52
  senderParticipantPosition: number | null;
33
53
  }
@@ -43,6 +63,8 @@ export interface MeetingSave {
43
63
  chat?: ChatInput[];
44
64
  summaries?: Omit<NewRecord<Summary>, "meetingId">[];
45
65
  attachments?: Omit<NewRecord<Attachment>, "attachableType" | "attachableId">[];
66
+ /** Adds to the documents held and retitles them; one left out stays linked, since the service forgets its files. */
67
+ documents?: MeetingDocumentInput[];
46
68
  now: number;
47
69
  /**
48
70
  * A copy of the occurrence read from a file, not from the provider. It joins the provider's record of the same
@@ -69,6 +91,8 @@ export interface MeetingDetails {
69
91
  chat: ChatLine[];
70
92
  summaries: Summary[];
71
93
  attachments: Attachment[];
94
+ /** Left out by a store that keeps no Drive links. */
95
+ documents?: MeetingDocument[];
72
96
  }
73
97
  export interface MeetingFilter {
74
98
  accountId?: number;
@@ -1,2 +1,3 @@
1
+ export const MEETING_DOCUMENT_ROLES = ["transcript", "recording", "notes"];
1
2
  /** `searchHits`' refusal of a page whose stored text passes `maxReadBytes`; a reader may ask for fewer rows. */
2
3
  export const READ_BUDGET_EXCEEDED = "Meeting search exceeds its stored text byte budget";
@@ -1,4 +1,4 @@
1
- import type { MeetingDetails, TranscriptInput, TranscriptRowInput } from "./store.js";
1
+ import type { MeetingDetails, MeetingDocumentRole, TranscriptInput, TranscriptRowInput } from "./store.js";
2
2
  export type UnlinkedTranscriptInput = Omit<TranscriptInput, "rows" | "contentHash"> & {
3
3
  contentHash: string;
4
4
  rows: Omit<TranscriptRowInput, "speakerParticipantPosition">[];
@@ -35,7 +35,15 @@ export interface TranscriptAppendReceipt {
35
35
  export interface MeetingTranscriptReceiptStore {
36
36
  appendTranscriptsWithReceipt(input: TranscriptAppend): Promise<TranscriptAppendReceipt>;
37
37
  }
38
+ /** The meeting a Drive document belongs to, and as what. */
39
+ export interface DocumentMeeting {
40
+ meetingId: number;
41
+ accountId: number;
42
+ role: MeetingDocumentRole;
43
+ }
38
44
  /** The meeting whose transcript a Drive document is, by the `driveFileId` the meeting's transcript named. */
39
45
  export interface MeetingTranscriptDocumentStore {
40
46
  transcriptMeetings(documentIds: readonly number[]): Promise<Map<number, number>>;
47
+ /** The meeting each document is a transcript, recording or notes of; a document of two meetings names the first. */
48
+ documentMeetings(documentIds: readonly number[]): Promise<Map<number, DocumentMeeting>>;
41
49
  }
@@ -108,6 +108,20 @@ const exchangeTokens = async (provider, params, context, deadline) => {
108
108
  ...(tokenType ? { tokenType } : {}),
109
109
  };
110
110
  };
111
+ /**
112
+ * Google answers 400 `invalid_token` for a grant the owner or Google already took back: nothing is left to revoke.
113
+ * RFC 7009 §2.2 has such a token answered 200; this is the same outcome said another way.
114
+ */
115
+ const alreadyRevoked = async (response) => {
116
+ if (response.status !== 400)
117
+ return false;
118
+ try {
119
+ return object(JSON.parse(await response.text())).error === "invalid_token";
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ };
111
125
  /** Revokes the refresh token at `revokeUrl`. A provider without one, or with another method, declares `revoke`. */
112
126
  export const revokeToken = async (provider, tokens, context) => {
113
127
  if (provider.revoke)
@@ -116,16 +130,20 @@ export const revokeToken = async (provider, tokens, context) => {
116
130
  throw new CliError("validation_error", `${provider.name} declares no way to revoke a sign-in`);
117
131
  const { revokeUrl } = provider;
118
132
  const form = new URLSearchParams({ token: tokens.refreshToken, ...clientFields(context) });
119
- const response = await withTimeLimit(REQUEST_LIMIT_MS, (deadline) => post(revokeUrl, form, context, deadline));
120
- context.log?.[response?.ok ? "info" : "warn"]({
133
+ const { response, gone } = await withTimeLimit(REQUEST_LIMIT_MS, async (deadline) => {
134
+ const response = await post(revokeUrl, form, context, deadline);
135
+ return { response, gone: response ? await alreadyRevoked(response) : false };
136
+ });
137
+ const done = response?.ok || gone;
138
+ context.log?.[done ? "info" : "warn"]({
121
139
  event: TOKEN_LOG_EVENT,
122
140
  provider: provider.id,
123
141
  operation: "revoke",
124
142
  pid: process.pid,
125
- outcome: response?.ok ? "revoked" : response ? "rejected" : "no_response",
143
+ outcome: response?.ok ? "revoked" : gone ? "already_revoked" : response ? "rejected" : "no_response",
126
144
  ...(response ? { status: response.status } : {}),
127
145
  });
128
- if (!response?.ok)
146
+ if (!done)
129
147
  throw new CliError("outcome_unknown", `${provider.name} did not confirm the revoke`, {
130
148
  reason: "oauth.revoke-failed",
131
149
  ...(response ? { status: response.status } : {}),
@@ -51,6 +51,8 @@ export interface SearchAllRecordItem {
51
51
  review?: "proposed" | "confirmed";
52
52
  /** A business hit's source record, when an import made it. */
53
53
  sourceRecord?: BusinessSource;
54
+ /** A document's: the meeting it is the transcript, recording or notes of (`meeting:<account>/<meeting>`). */
55
+ meeting?: string;
54
56
  }
55
57
  /** One account a search read, by the kind it was read for: the shape memo's `search all` answers too. */
56
58
  export interface SearchedAccount {
@@ -6,6 +6,7 @@ import { senderIsMe } from "../domain/models.js";
6
6
  import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
7
7
  import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { chosenTextModel } from "../embeddings/models.js";
9
+ import { formatMeetingReference } from "../meetings/index.js";
9
10
  import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
10
11
  import { plainQuery } from "../search/lucene/plain.js";
11
12
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
@@ -143,6 +144,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
143
144
  /** Each hit found by meaning, by its cosine: one model for every source, so these compare across them. */
144
145
  const cosines = new Map();
145
146
  let coverage;
147
+ const meetingAccountsRead = new Set();
146
148
  let meetings;
147
149
  const messagesOf = async (kind) => {
148
150
  const given = scope?.[kind];
@@ -382,6 +384,8 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
382
384
  continue;
383
385
  hasMore ||= found.hasMore;
384
386
  meetings = found.coverage;
387
+ for (const { id } of found.read)
388
+ meetingAccountsRead.add(id);
385
389
  lists.push(found.items);
386
390
  for (const { provider, account } of found.read)
387
391
  accounts.push({ resource, provider, account });
@@ -400,7 +404,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
400
404
  finally {
401
405
  await embedders.close();
402
406
  }
403
- let ordered = insidePeriodFirst(oneList(await withoutTranscriptCopies(store, lists), cosines), period);
407
+ let ordered = insidePeriodFirst(oneList(await withMeetingDocuments(store, lists, meetingAccountsRead), cosines), period);
404
408
  let harder;
405
409
  if (request.harder) {
406
410
  const asking = {
@@ -443,22 +447,37 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
443
447
  };
444
448
  };
445
449
  /**
446
- * A meeting's transcript that Drive also imported as a document is one thing: when the meeting is among the hits, its
447
- * document's hit is dropped. Alone, the document stays, so nothing found is lost.
450
+ * A document that is a meeting's transcript, recording or notes names that meeting, when this search read the
451
+ * meeting's account: a search that may not read meetings, or not that account, never learns of it. A transcript that Drive also
452
+ * imported as a document is one thing with its meeting: when the meeting is among the hits, the document's hit is
453
+ * dropped. Alone, the document stays, so nothing found is lost.
448
454
  */
449
- const withoutTranscriptCopies = async (store, lists) => {
450
- const meetings = new Set(lists.flat().flatMap((item) => (item.kind === "meeting" ? [item.meetingId] : [])));
451
- if (!meetings.size)
455
+ const withMeetingDocuments = async (store, lists, read) => {
456
+ if (!read.size)
452
457
  return lists;
453
458
  const documentOf = (item) => item.kind === "document" && /^document:\d+$/.test(item.ref) ? Number(item.ref.slice("document:".length)) : undefined;
454
459
  const documents = lists.flat().flatMap((item) => documentOf(item) ?? []);
455
- const transcripts = await store.meetings.transcriptMeetings(documents);
456
- if (!transcripts.size)
460
+ if (!documents.length)
461
+ return lists;
462
+ const owners = await store.meetings.documentMeetings(documents);
463
+ if (!owners.size)
457
464
  return lists;
458
- return lists.map((list) => list.filter((item) => {
465
+ const meetings = new Set(lists.flat().flatMap((item) => (item.kind === "meeting" ? [item.meetingId] : [])));
466
+ return lists.map((list) => list.flatMap((item) => {
459
467
  const document = documentOf(item);
460
- const meeting = document === undefined ? undefined : transcripts.get(document);
461
- return meeting === undefined || !meetings.has(meeting);
468
+ const owner = document === undefined ? undefined : owners.get(document);
469
+ if (owner === undefined || item.kind === "meeting")
470
+ return [item];
471
+ if (owner.role === "transcript" && meetings.has(owner.meetingId))
472
+ return [];
473
+ if (!read.has(owner.accountId))
474
+ return [item];
475
+ return [
476
+ {
477
+ ...item,
478
+ meeting: formatMeetingReference({ type: "meeting", accountId: owner.accountId, meetingId: owner.meetingId }),
479
+ },
480
+ ];
462
481
  }));
463
482
  };
464
483
  /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
@@ -0,0 +1,13 @@
1
+ import { type MeetingDocument, type MeetingDocumentInput, type MeetingTranscriptDocumentStore } from "../../meetings/index.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ /** A file the meeting's source listed. Listed links only grow: a file left out of a later list stays linked. */
5
+ export declare const attachListedDocument: (database: CacheDatabase, meetingId: number, { fileId, role, title }: MeetingDocumentInput, now: number) => void;
6
+ /**
7
+ * The file one transcript source saved its transcript as. A new version (`replaces`) drops the links an earlier
8
+ * version of the same source named, never a listed link or another source's; a replay of an old version keeps them.
9
+ */
10
+ export declare const attachTranscriptFile: (database: CacheDatabase, meetingId: number, fileId: string, source: string, now: number, replaces: boolean) => void;
11
+ /** The meeting's Drive files, in the order they were first named. */
12
+ export declare const meetingDocumentsOf: (database: CacheDatabase, meetingId: number) => MeetingDocument[];
13
+ export declare const meetingTranscriptDocumentsOver: ({ database }: StoreContext) => MeetingTranscriptDocumentStore;
@@ -0,0 +1,110 @@
1
+ import { MEETING_DOCUMENT_ROLES, } from "../../meetings/index.js";
2
+ import { fromJson, int, str } from "./events.js";
3
+ import { driveDocumentOf, driveFileTarget } from "./files.js";
4
+ import { read } from "./transaction.js";
5
+ const TRANSCRIPT_ROLE = "transcript";
6
+ const roleOf = (value) => MEETING_DOCUMENT_ROLES.find((role) => role === value);
7
+ /**
8
+ * The meeting's Drive file as an `attached` link to the file's document, waiting by its Drive id when Drive has not
9
+ * stored it yet. Drive's later import resolves it (`linkAttached`), so either order ends in one link.
10
+ *
11
+ * Metadata tells who named the file: `{ listed: true, title? }` the source's list (`MeetingSave.documents`), or
12
+ * `{ source }` a transcript version (`TranscriptInput.driveFileId`). A listing wins: it sets the role and title, and a
13
+ * transcript version never changes a listed link.
14
+ */
15
+ const attach = (database, meetingId, fileId, role, metadata, listed, now) => {
16
+ const target = driveFileTarget(fileId);
17
+ const held = database
18
+ .prepare("SELECT id, to_id, role, metadata FROM links WHERE from_type = 'meeting' AND from_id = ? AND kind = 'attached' " +
19
+ "AND target_text = ?")
20
+ .get(meetingId, target);
21
+ if (!held) {
22
+ database
23
+ .prepare(`INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, target_text, role, metadata, confirmed,
24
+ author, created_at, updated_at) VALUES ('meeting', ?, 'document', ?, 'attached', 'meeting', ?, ?, ?, 1, 'rule',
25
+ ?, ?)`)
26
+ .run(meetingId, driveDocumentOf(database, fileId), target, role, metadata, now, now);
27
+ return;
28
+ }
29
+ const document = held.to_id == null ? driveDocumentOf(database, fileId) : int(held.to_id);
30
+ const nextRole = listed ? role : str(held.role);
31
+ const nextMetadata = listed ? metadata : str(held.metadata);
32
+ database
33
+ .prepare("UPDATE links SET to_id = ?, role = ?, metadata = ?, updated_at = ? WHERE id = ? " +
34
+ "AND (to_id IS NOT ? OR role IS NOT ? OR metadata IS NOT ?)")
35
+ .run(document, nextRole, nextMetadata, now, Number(held.id), document, nextRole, nextMetadata);
36
+ };
37
+ /** A file the meeting's source listed. Listed links only grow: a file left out of a later list stays linked. */
38
+ export const attachListedDocument = (database, meetingId, { fileId, role, title }, now) => {
39
+ const file = fileId.trim();
40
+ if (file)
41
+ attach(database, meetingId, file, role, JSON.stringify({ listed: true, ...(title ? { title } : {}) }), true, now);
42
+ };
43
+ /**
44
+ * The file one transcript source saved its transcript as. A new version (`replaces`) drops the links an earlier
45
+ * version of the same source named, never a listed link or another source's; a replay of an old version keeps them.
46
+ */
47
+ export const attachTranscriptFile = (database, meetingId, fileId, source, now, replaces) => {
48
+ const file = fileId.trim();
49
+ if (!file)
50
+ return;
51
+ if (replaces)
52
+ database
53
+ .prepare("DELETE FROM links WHERE from_type = 'meeting' AND from_id = ? AND kind = 'attached' AND role = ? " +
54
+ "AND target_text <> ? AND json_extract(metadata, '$.source') = ? AND json_extract(metadata, '$.listed') IS NULL")
55
+ .run(meetingId, TRANSCRIPT_ROLE, driveFileTarget(file), source);
56
+ attach(database, meetingId, file, TRANSCRIPT_ROLE, JSON.stringify({ source }), false, now);
57
+ };
58
+ /** The meeting's Drive files, in the order they were first named. */
59
+ export const meetingDocumentsOf = (database, meetingId) => database
60
+ .prepare("SELECT l.target_text, l.role, l.metadata, CASE WHEN d.deleted_at IS NULL THEN l.to_id END AS to_id " +
61
+ "FROM links l LEFT JOIN documents d ON d.id = l.to_id WHERE l.from_type = 'meeting' AND l.from_id = ? " +
62
+ "AND l.kind = 'attached' AND l.to_type = 'document' ORDER BY l.id")
63
+ .all(meetingId)
64
+ .flatMap((row) => {
65
+ const role = roleOf(row.role);
66
+ return role === undefined
67
+ ? []
68
+ : [
69
+ {
70
+ fileId: String(row.target_text).slice(driveFileTarget("").length),
71
+ role,
72
+ title: str(fromJson(row.metadata)?.title),
73
+ documentId: int(row.to_id),
74
+ },
75
+ ];
76
+ });
77
+ export const meetingTranscriptDocumentsOver = ({ database }) => {
78
+ const meetingsOf = (documentIds, roles) => read(database, () => {
79
+ const rows = database
80
+ .prepare(`SELECT l.to_id AS document_id, l.from_id AS meeting_id, m.account_id, l.role FROM links l
81
+ JOIN meetings m ON m.id = l.from_id
82
+ WHERE l.kind = 'attached' AND l.from_type = 'meeting' AND l.to_type = 'document'
83
+ AND l.role IN (SELECT value FROM json_each(?)) AND m.deleted_at IS NULL
84
+ AND l.to_id IN (SELECT value FROM json_each(?))
85
+ ORDER BY l.role = ? DESC, l.id`)
86
+ .all(JSON.stringify(roles), JSON.stringify(documentIds), TRANSCRIPT_ROLE);
87
+ const found = new Map();
88
+ for (const row of rows) {
89
+ const role = roleOf(row.role);
90
+ if (role !== undefined && !found.has(Number(row.document_id)))
91
+ found.set(Number(row.document_id), {
92
+ meetingId: Number(row.meeting_id),
93
+ accountId: Number(row.account_id),
94
+ role,
95
+ });
96
+ }
97
+ return found;
98
+ });
99
+ return {
100
+ async transcriptMeetings(documentIds) {
101
+ if (!documentIds.length)
102
+ return new Map();
103
+ const found = await meetingsOf(documentIds, [TRANSCRIPT_ROLE]);
104
+ return new Map([...found].map(([document, { meetingId }]) => [document, meetingId]));
105
+ },
106
+ async documentMeetings(documentIds) {
107
+ return documentIds.length ? meetingsOf(documentIds, MEETING_DOCUMENT_ROLES) : new Map();
108
+ },
109
+ };
110
+ };
@@ -8,6 +8,7 @@ import { meetingIdentityPk } from "./identities.js";
8
8
  import { reviewLink } from "./link-reviews.js";
9
9
  import { meetingChatLinesOver } from "./meeting-chat-lines.js";
10
10
  import { meetingContextLinksOver } from "./meeting-context-links.js";
11
+ import { attachListedDocument, attachTranscriptFile, meetingDocumentsOf, meetingTranscriptDocumentsOver, } from "./meeting-documents.js";
11
12
  import { meetingHitIndexOver } from "./meeting-hit-index.js";
12
13
  import { meetingHitSearchOver } from "./meeting-hit-search.js";
13
14
  import { INDEX_CODES, indexedText, meetingRowid, summaryOf } from "./meeting-index-values.js";
@@ -22,7 +23,6 @@ import { meetingReviewOver } from "./meeting-review.js";
22
23
  import { meetingSeriesHistoryOver } from "./meeting-series-history.js";
23
24
  import { meetingStatsOver } from "./meeting-stats.js";
24
25
  import { invalidateMeetingStems } from "./meeting-stem-state.js";
25
- import { attachTranscriptDocument, meetingTranscriptDocumentsOver } from "./meeting-transcript-documents.js";
26
26
  import { meetingOf, transcriptOf, transcriptRowOf } from "./meeting-values.js";
27
27
  import { linkPhones } from "./person-match-scan.js";
28
28
  import { queryFilter } from "./query-filter.js";
@@ -134,6 +134,7 @@ const details = (database, id) => {
134
134
  .prepare("SELECT * FROM attachments WHERE attachable_type = 'meeting' AND attachable_id = ? ORDER BY position")
135
135
  .all(id)
136
136
  .map(attachmentOf),
137
+ documents: meetingDocumentsOf(database, id),
137
138
  };
138
139
  };
139
140
  /** Inserts or updates the row the key finds; `values` are the columns besides the key and the times. */
@@ -332,6 +333,8 @@ const save = (context, input) => {
332
333
  }, now);
333
334
  for (const a of input.attachments ?? [])
334
335
  saveAttachment(database, "meeting", meetingId, a, now);
336
+ for (const document of input.documents ?? [])
337
+ attachListedDocument(database, meetingId, document, now);
335
338
  return meetingId;
336
339
  };
337
340
  const saveTranscripts = (database, meetingId, transcripts, participantId, now) => {
@@ -346,7 +349,7 @@ const saveTranscripts = (database, meetingId, transcripts, participantId, now) =
346
349
  for (const { rows, driveFileId, ...t } of transcripts) {
347
350
  const replayed = t.contentHash !== null && Boolean(sameContent.get(meetingId, t.source, t.contentHash));
348
351
  if (driveFileId !== undefined)
349
- attachTranscriptDocument(database, meetingId, driveFileId, now, !replayed);
352
+ attachTranscriptFile(database, meetingId, driveFileId, t.source, now, !replayed);
350
353
  if (replayed) {
351
354
  counts.replayedTranscripts++;
352
355
  continue;