@startsimpli/integrations 0.2.53 → 0.2.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/corpus/ask.ts CHANGED
@@ -241,7 +241,10 @@ async function loadCandidates(
241
241
 
242
242
  const [documents, money] = await Promise.all([
243
243
  corpus.listDocuments(documentQuery),
244
- corpus.listMoneyEvents
244
+ // A money event cannot be filed under a project (`about_focus` is
245
+ // source_document -> focus), so a project-scoped question has none to offer.
246
+ // Asking anyway would put workspace-wide payments into a "this project" answer.
247
+ corpus.listMoneyEvents && !request.filters?.focus
245
248
  ? corpus
246
249
  .listMoneyEvents({
247
250
  ...(searchTerm ? { search: searchTerm } : {}),
@@ -262,6 +265,23 @@ async function loadCandidates(
262
265
  };
263
266
  }
264
267
 
268
+ /**
269
+ * The filters an Ask route may accept from a request body: only the ones Ask
270
+ * understands, as non-empty strings. A route passes `body.filters` through this
271
+ * so a crafted POST cannot smuggle an arbitrary query parameter into retrieval.
272
+ * `undefined` when nothing usable remains.
273
+ */
274
+ export function sanitizeAskFilters(raw: unknown): AskRequest['filters'] | undefined {
275
+ if (!raw || typeof raw !== 'object') return undefined;
276
+ const source = raw as Record<string, unknown>;
277
+ const out: Record<string, string> = {};
278
+ for (const key of ['source', 'partyId', 'focus', 'occurredAfter', 'occurredBefore']) {
279
+ const value = source[key];
280
+ if (typeof value === 'string' && value.trim()) out[key] = value.trim();
281
+ }
282
+ return Object.keys(out).length ? (out as AskRequest['filters']) : undefined;
283
+ }
284
+
265
285
  /**
266
286
  * How many records this workspace holds AT ALL — asked only when the answer is
267
287
  * going to be "nothing matched", and only to decide WHICH "nothing".
@@ -49,6 +49,7 @@ import {
49
49
  import type {
50
50
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
51
51
  } from './entities';
52
+ import { ABOUT_FOCUS, createFilingApi } from './filing';
52
53
  import {
53
54
  FOCUS_TYPE,
54
55
  IN_FOCUS,
@@ -285,6 +286,7 @@ const DOCUMENT_FILTER_PARAMS: Array<[keyof DocumentQuery, string[]]> = [
285
286
  ['search', ['search']],
286
287
  ['source', ['source', 'attr.source']],
287
288
  ['partyId', ['party', 'related_to']],
289
+ ['focus', ['related_to']],
288
290
  ['occurredAfter', ['occurred_after', 'attr.occurred_at__gte']],
289
291
  ['occurredBefore', ['occurred_before', 'attr.occurred_at__lte']],
290
292
  ['folder', ['attr.path']],
@@ -368,6 +370,14 @@ function params(query: DocumentQuery, type: string) {
368
370
  if (query.order && (query.order !== 'relevance' || query.search)) out.order = query.order;
369
371
  if (query.source) out.source = query.source;
370
372
  if (query.partyId) out.party = query.partyId;
373
+ if (query.focus) {
374
+ // Filing is an edge, so "the documents in this project" is an edge walk. A
375
+ // document is the SOURCE of its own `about_focus` edge: `out` returns
376
+ // documents, `in` returns an empty page (see `commitmentParams`).
377
+ out.related_to = query.focus;
378
+ out.related_via = ABOUT_FOCUS;
379
+ out.related_direction = 'out';
380
+ }
371
381
  if (query.occurredAfter) out.occurred_after = query.occurredAfter;
372
382
  if (query.occurredBefore) out.occurred_before = query.occurredBefore;
373
383
  // THE FOLDER BOUNDS, and only ever one of them. `attr.path` is the shelf and
@@ -684,6 +694,8 @@ export function createCorpusApi(
684
694
  }
685
695
 
686
696
  return {
697
+ ...createFilingApi(http, { entities, relationships }),
698
+
687
699
  async listDocuments(query) {
688
700
  const documents = await page<TenantEntity>(types.document, query, (entity) => entity);
689
701
  // Skip the edge read entirely for an empty page: an empty corpus should
@@ -0,0 +1,122 @@
1
+ /**
2
+ * FILING A DOCUMENT UNDER A PROJECT (bd startsim-vkymg).
3
+ *
4
+ * Any `source_document` — a voice note, a Fathom meeting, a PDF — is filed under
5
+ * a project (a `focus`) by ONE `about_focus` edge, source_document -> focus. This
6
+ * is the single implementation of that edge's lifecycle; the voice page, the
7
+ * Library and anything later call it rather than re-writing replace-the-edge.
8
+ *
9
+ * `about_focus` is not `in_focus`. `in_focus` is commitment -> focus only and is
10
+ * what Planning's 'N of M done' counts; a document must never enter that number,
11
+ * which is why the two edges have different names and nothing here touches
12
+ * `in_focus`.
13
+ */
14
+ import type { CorpusHttp } from './client';
15
+ import type { TenantEntity, TenantRelationship } from './entities';
16
+ import { FOCUS_TYPE } from './planning';
17
+
18
+ /** A document is ABOUT a focus — its own edge, never `in_focus`. */
19
+ export const ABOUT_FOCUS = 'about_focus';
20
+
21
+ export interface FocusChoice {
22
+ id: string;
23
+ title: string;
24
+ detail?: string;
25
+ }
26
+
27
+ /** What a document is filed under. */
28
+ export interface DocumentFiling {
29
+ id: string;
30
+ title: string;
31
+ }
32
+
33
+ type Page<T> = { results?: T[] };
34
+
35
+ function text(value: unknown): string {
36
+ return typeof value === 'string' ? value : '';
37
+ }
38
+
39
+ export interface FilingPaths {
40
+ entities?: string;
41
+ relationships?: string;
42
+ }
43
+
44
+ /**
45
+ * Replace, never add: a document lives in one project. Existing `about_focus`
46
+ * edges from the document are deleted, then the new one is written (none for
47
+ * `null`, which unfiles).
48
+ */
49
+ export async function fileDocument(
50
+ http: CorpusHttp,
51
+ documentId: string,
52
+ focusId: string | null,
53
+ paths: FilingPaths = {},
54
+ ): Promise<void> {
55
+ const relationships = paths.relationships ?? 'api/v1/relationships';
56
+ if (!http.post) throw new Error('This client is read-only.');
57
+ const existing = await http.get<Page<TenantRelationship>>(relationships, {
58
+ params: { rel_type: ABOUT_FOCUS, source: documentId },
59
+ });
60
+ if (existing.results?.length) {
61
+ if (!http.delete) throw new Error('This client cannot move a note — no delete method was supplied.');
62
+ for (const edge of existing.results) await http.delete(`${relationships}/${edge.id}`);
63
+ }
64
+ if (focusId) {
65
+ await http.post(relationships, { rel_type: ABOUT_FOCUS, source: documentId, target: focusId });
66
+ }
67
+ }
68
+
69
+ /** The projects a document can be filed under, by title. */
70
+ export async function listFocusChoices(
71
+ http: CorpusHttp,
72
+ paths: FilingPaths = {},
73
+ ): Promise<FocusChoice[]> {
74
+ const entities = paths.entities ?? 'api/v1/entities';
75
+ const page = await http.get<Page<TenantEntity>>(entities, {
76
+ params: { type: FOCUS_TYPE, order: 'attr.title', page_size: 200 },
77
+ });
78
+ return (page.results ?? []).map((row) => ({
79
+ id: String(row.id),
80
+ title: text(((row.data ?? {}) as Record<string, unknown>).title) || row.name || 'Untitled',
81
+ }));
82
+ }
83
+
84
+ /** The project a document is filed under, or null when it is not filed. */
85
+ export async function getDocumentFiling(
86
+ http: CorpusHttp,
87
+ documentId: string,
88
+ paths: FilingPaths = {},
89
+ ): Promise<DocumentFiling | null> {
90
+ const entities = paths.entities ?? 'api/v1/entities';
91
+ const relationships = paths.relationships ?? 'api/v1/relationships';
92
+ const edges = await http.get<Page<TenantRelationship>>(relationships, {
93
+ params: { rel_type: ABOUT_FOCUS, source: documentId },
94
+ });
95
+ const edge = edges.results?.[0];
96
+ if (!edge) return null;
97
+ const id = String(edge.target);
98
+ try {
99
+ const row = await http.get<TenantEntity>(`${entities}/${encodeURIComponent(id)}`);
100
+ const title = text(((row.data ?? {}) as Record<string, unknown>).title) || row.name;
101
+ return { id, title: title || 'Untitled' };
102
+ } catch {
103
+ // The edge is real even when the project row is not readable by this
104
+ // principal; say it is filed rather than that it is not.
105
+ return { id, title: 'A project you cannot open' };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * The filing operations bound to one client — what `createCorpusApi` exposes.
111
+ * `fileDocument` is present only when the client can write: a control that
112
+ * appears to work and throws "read-only" is worse than none.
113
+ */
114
+ export function createFilingApi(http: CorpusHttp, paths: FilingPaths = {}) {
115
+ return {
116
+ ...(http.post
117
+ ? { fileDocument: (documentId: string, focusId: string | null) => fileDocument(http, documentId, focusId, paths) }
118
+ : {}),
119
+ getDocumentFiling: (documentId: string) => getDocumentFiling(http, documentId, paths),
120
+ listFocusChoices: () => listFocusChoices(http, paths),
121
+ };
122
+ }
@@ -101,6 +101,7 @@ export type { QuestionTerms, RetrieveOptions, ScopeFilterResult } from './retrie
101
101
  export {
102
102
  answerSystemPrompt,
103
103
  askCorpus,
104
+ sanitizeAskFilters,
104
105
  buildAnswerRequest,
105
106
  documentText,
106
107
  renderAnswerPrompt,
@@ -197,6 +198,15 @@ export {
197
198
  } from './fixtures';
198
199
  export type { FixtureCorpusOptions } from './fixtures';
199
200
 
201
+ export {
202
+ ABOUT_FOCUS,
203
+ createFilingApi,
204
+ fileDocument,
205
+ getDocumentFiling,
206
+ listFocusChoices,
207
+ } from './filing';
208
+ export type { DocumentFiling } from './filing';
209
+
200
210
  export {
201
211
  VOICE_SOURCE,
202
212
  VOICE_SOURCE_LABEL,
@@ -296,6 +296,13 @@ export interface DocumentQuery {
296
296
  order?: 'relevance' | 'recent' | 'oldest';
297
297
  source?: SourceKey;
298
298
  partyId?: string;
299
+ /**
300
+ * THE DOCUMENTS FILED UNDER ONE PROJECT (a focus), via the `about_focus` edge.
301
+ * Goes out as `related_to` / `related_via=about_focus` / `related_direction=out`
302
+ * — a document is the SOURCE of its own edge, and `in` returns an empty page
303
+ * rather than an error.
304
+ */
305
+ focus?: string;
299
306
  /** ISO instants, filtering on `occurredAt`. */
300
307
  occurredAfter?: string;
301
308
  occurredBefore?: string;
@@ -396,6 +403,16 @@ export interface CorpusApi {
396
403
  * list it rendered before. Never a half-drawn tree.
397
404
  */
398
405
  listFolders?(query: FolderQuery): Promise<CorpusPage<CorpusFolder>>;
406
+ /**
407
+ * FILING (bd startsim-vkymg) — the project a document sits under. All three
408
+ * optional: a client that cannot read them shows no 'Filed under'; one that
409
+ * cannot write shows the chip without the change control.
410
+ */
411
+ getDocumentFiling?(documentId: string): Promise<{ id: string; title: string } | null>;
412
+ /** Move to another project, or `null` to unfile. Replaces the edge: exactly one exists. */
413
+ fileDocument?(documentId: string, focusId: string | null): Promise<void>;
414
+ /** The projects a document can be filed under. */
415
+ listFocusChoices?(): Promise<Array<{ id: string; title: string }>>;
399
416
  /**
400
417
  * Optional because a tenant with no payment connector has no money events, and
401
418
  * a corpus surface that requires one would fail the Dropbox-only test.
@@ -449,7 +466,7 @@ export interface AskRequest {
449
466
  /** Extra instructions for GENERATE — tone, format, the kind of document. */
450
467
  instructions?: string;
451
468
  /** Narrow the corpus before retrieval, exactly like the Library's filters. */
452
- filters?: Pick<DocumentQuery, 'source' | 'partyId' | 'occurredAfter' | 'occurredBefore'>;
469
+ filters?: Pick<DocumentQuery, 'source' | 'partyId' | 'focus' | 'occurredAfter' | 'occurredBefore'>;
453
470
  }
454
471
 
455
472
  /**
@@ -1298,6 +1315,10 @@ export interface FocusStanding {
1298
1315
  * reading their items would be a folder tree with nothing in it.
1299
1316
  */
1300
1317
  export interface PlanningApi extends CommitmentApi {
1318
+ /** The documents filed under a focus (`DocumentQuery.focus`), server-paginated. */
1319
+ listDocuments?(query: DocumentQuery): Promise<CorpusPage<SourceDocument>>;
1320
+ /** Move a document to another project, or `null` to unfile. */
1321
+ fileDocument?(documentId: string, focusId: string | null): Promise<void>;
1301
1322
  listFocuses(query?: FocusQuery): Promise<CorpusPage<Focus>>;
1302
1323
  createFocus?(draft: FocusDraft): Promise<Focus>;
1303
1324
  /** Takes the row for the same reason `updateCommitment` does. */
@@ -24,26 +24,16 @@
24
24
  import type { CorpusHttp } from './client';
25
25
  import type { TenantEntity, TenantRelationship } from './entities';
26
26
  import type { CorpusScope } from './types';
27
+ import { ABOUT_FOCUS, fileDocument, listFocusChoices } from './filing';
28
+ import type { FocusChoice } from './filing';
27
29
 
28
- /**
29
- * A document is ABOUT a focus — its own edge, not `in_focus`. `in_focus` is
30
- * declared commitment -> focus only (a relationship definition has one source
31
- * type), and the Planning counts walk it expecting items. Reusing it for
32
- * documents would have been rejected by the tenant (400 "source must be a
33
- * 'commitment'"); widening it would let documents leak into item counts.
34
- */
35
- export const ABOUT_FOCUS = 'about_focus';
30
+ export { ABOUT_FOCUS };
31
+ export type { FocusChoice };
36
32
 
37
33
  export const VOICE_SOURCE = 'voice';
38
34
  export const VOICE_SOURCE_LABEL = 'Voice note';
39
35
  export type VoiceStatus = 'processing' | 'ready' | 'failed';
40
36
 
41
- export interface FocusChoice {
42
- id: string;
43
- title: string;
44
- detail?: string;
45
- }
46
-
47
37
  export interface VoiceAnalysis {
48
38
  title: string;
49
39
  summary: string;
@@ -326,29 +316,9 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
326
316
  .map((r) => toVoiceNote(r, focusOf.get(String(r.id)) ?? null));
327
317
  },
328
318
 
329
- async listFocuses() {
330
- const page = await http.get<Page<TenantEntity>>('api/v1/entities', {
331
- params: { type: 'focus', order: 'attr.title', page_size: 200 },
332
- });
333
- return (page.results ?? []).map((r) => ({
334
- id: String(r.id),
335
- title: text(((r.data ?? {}) as Record<string, unknown>).title) || r.name || 'Untitled',
336
- }));
337
- },
319
+ listFocuses: () => listFocusChoices(http),
338
320
 
339
- async file(noteId, focusId) {
340
- if (!http.post) throw new Error('This client is read-only.');
341
- // Replace, never add: a note lives in one project.
342
- const existing = await http.get<Page<TenantRelationship>>('api/v1/relationships', {
343
- params: { rel_type: ABOUT_FOCUS, source: noteId },
344
- });
345
- if (existing.results?.length) {
346
- if (!http.delete) throw new Error('This client cannot move a note — no delete method was supplied.');
347
- for (const edge of existing.results) await http.delete(`api/v1/relationships/${edge.id}`);
348
- }
349
- if (focusId) {
350
- await http.post('api/v1/relationships', { rel_type: ABOUT_FOCUS, source: noteId, target: focusId });
351
- }
352
- },
321
+ // Replace, never add: a note lives in one project (see ./filing).
322
+ file: (noteId, focusId) => fileDocument(http, noteId, focusId),
353
323
  };
354
324
  }