@things-factory/ai-assistant 10.1.304 → 10.1.316

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 (45) hide show
  1. package/dist-client/utils/entry-proposal.d.ts +4 -1
  2. package/dist-client/utils/entry-proposal.js +5 -2
  3. package/dist-client/utils/entry-workspace.js +3 -3
  4. package/dist-server/index.d.ts +1 -0
  5. package/dist-server/index.js +4 -0
  6. package/dist-server/service/chat-session/attachment-tools.js +2 -0
  7. package/dist-server/service/chat-session/chat-session.d.ts +6 -0
  8. package/dist-server/service/chat-session/chat-session.js +9 -1
  9. package/dist-server/service/data-entry/entry-apply.js +3 -4
  10. package/dist-server/service/data-entry/entry-target.d.ts +13 -0
  11. package/dist-server/service/data-entry/entry-target.js +31 -0
  12. package/dist-server/service/data-entry/entry-tools.d.ts +4 -3
  13. package/dist-server/service/data-entry/entry-tools.js +50 -11
  14. package/dist-server/service/data-entry/entry-update.d.ts +1 -0
  15. package/dist-server/service/data-entry/entry-update.js +2 -0
  16. package/dist-server/service/data-read/read-tools.js +11 -6
  17. package/dist-server/service/database-error.d.ts +5 -0
  18. package/dist-server/service/database-error.js +27 -0
  19. package/dist-server/service/index.d.ts +1 -0
  20. package/dist-server/service/index.js +4 -1
  21. package/dist-server/service/mcp/mcp-audit.d.ts +7 -0
  22. package/dist-server/service/mcp/mcp-audit.js +44 -0
  23. package/dist-server/service/mcp/mcp-call.d.ts +60 -0
  24. package/dist-server/service/mcp/mcp-call.js +134 -0
  25. package/dist-server/service/mcp/mcp-conversation.d.ts +30 -0
  26. package/dist-server/service/mcp/mcp-conversation.js +202 -0
  27. package/dist-server/service/mcp/mcp-route.d.ts +7 -0
  28. package/dist-server/service/mcp/mcp-route.js +49 -0
  29. package/dist-server/service/mcp/mcp-scope.d.ts +45 -0
  30. package/dist-server/service/mcp/mcp-scope.js +138 -0
  31. package/dist-server/service/mcp/mcp-server.d.ts +43 -0
  32. package/dist-server/service/mcp/mcp-server.js +153 -0
  33. package/dist-server/service/mcp/mcp-settings.d.ts +33 -0
  34. package/dist-server/service/mcp/mcp-settings.js +25 -0
  35. package/dist-server/service/people/invite-tools.js +3 -0
  36. package/dist-server/service/workspace/workspace-blocks.d.ts +2 -0
  37. package/dist-server/service/workspace/workspace-blocks.js +3 -1
  38. package/dist-server/service/workspace/workspace-tools.js +3 -1
  39. package/package.json +7 -7
  40. package/translations/en.json +8 -1
  41. package/translations/es.json +8 -1
  42. package/translations/ja.json +8 -1
  43. package/translations/ko.json +8 -1
  44. package/translations/ms.json +8 -1
  45. package/translations/zh.json +8 -1
@@ -89,7 +89,10 @@ export declare function entryProposalHandler(apply: (sessionId: string, proposal
89
89
  * cannot be entered (the server refuses it as `superseded`; the card says so before anyone presses).
90
90
  */
91
91
  export declare function latestEntryKeys(proposalsInOrder: any[][]): Map<string, string>;
92
- /** A 입력안 and a 수정안 of one record are counted apart - a newer one of the same kind replaces the older. */
92
+ /**
93
+ * Which work a card is - the server's rule (`workOfProposal`): the card says it (`work` - the records a 수정안 changes, the
94
+ * values of a target's identity fields); a card that says nothing is its target and kind of work, as before.
95
+ */
93
96
  export declare function entryGroupOf(proposal: any): string;
94
97
  /**
95
98
  * The card's title - the record's name from the target (`부서`, `거래처`) and the kind of card from here, so a
@@ -135,9 +135,12 @@ export function latestEntryKeys(proposalsInOrder) {
135
135
  latest.set(entryGroupOf(one), one.key);
136
136
  return latest;
137
137
  }
138
- /** A 입력안 and a 수정안 of one record are counted apart - a newer one of the same kind replaces the older. */
138
+ /**
139
+ * Which work a card is - the server's rule (`workOfProposal`): the card says it (`work` - the records a 수정안 changes, the
140
+ * values of a target's identity fields); a card that says nothing is its target and kind of work, as before.
141
+ */
139
142
  export function entryGroupOf(proposal) {
140
- return `${proposal?.target}:${proposal?.op ?? 'create'}`;
143
+ return typeof proposal?.work === 'string' && proposal.work ? proposal.work : `${proposal?.target}:${proposal?.op ?? 'create'}`;
141
144
  }
142
145
  /**
143
146
  * The card's title - the record's name from the target (`부서`, `거래처`) and the kind of card from here, so a
@@ -7,6 +7,7 @@
7
7
  * that changed in between is refused, and the person reviews it again.
8
8
  */
9
9
  import { entryProposalHash } from './entry-hash.js';
10
+ import { entryGroupOf } from './entry-proposal.js';
10
11
  /** A card wide or long enough not to be read in the dock. */
11
12
  export const WORKSPACE_ROWS = 20;
12
13
  export const WORKSPACE_COLUMNS = 6;
@@ -28,9 +29,8 @@ export function entryForReview(messages, key) {
28
29
  });
29
30
  if (!proposal)
30
31
  return { superseded: false };
31
- const superseded = messages
32
- .slice(at + 1)
33
- .some(message => (message.proposalsJson ?? []).some(one => one?.kind === 'entry' && one?.target === proposal.target && (one?.op ?? 'create') === (proposal.op ?? 'create')));
32
+ const work = entryGroupOf(proposal);
33
+ const superseded = messages.slice(at + 1).some(message => (message.proposalsJson ?? []).some(one => one?.kind === 'entry' && entryGroupOf(one) === work));
34
34
  return { proposal, createdAt, superseded };
35
35
  }
36
36
  const STORE = 'ai-assistant.entry-reviewed:';
@@ -28,3 +28,4 @@
28
28
  export * from './service/index.js';
29
29
  import './tool-registry-boot-report.js';
30
30
  import './service/assistant-mode/fallback-subjects.js';
31
+ export { initMiddlewares } from './service/mcp/mcp-route.js';
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initMiddlewares = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  /**
5
6
  * `@things-factory/ai-assistant` — **AI 대화의 집.**
@@ -32,6 +33,9 @@ tslib_1.__exportStar(require("./service/index.js"), exports);
32
33
  require("./tool-registry-boot-report.js");
33
34
  /* The site, an application's home and a board are named without an application's help (design/ai/screen-pattern.md §2-1). */
34
35
  require("./service/assistant-mode/fallback-subjects.js");
36
+ /* The tools opened to an agent outside the application, read-only, as the person who connects it (ADR-0237). */
37
+ var mcp_route_js_1 = require("./service/mcp/mcp-route.js");
38
+ Object.defineProperty(exports, "initMiddlewares", { enumerable: true, get: function () { return mcp_route_js_1.initMiddlewares; } });
35
39
  const auth_base_1 = require("@things-factory/auth-base");
36
40
  const role_tasks_js_1 = require("./role-tasks.js");
37
41
  for (const task of role_tasks_js_1.ROLE_TASKS)
@@ -26,6 +26,8 @@ const readChatAttachment = {
26
26
  kind: 'read',
27
27
  name: 'readChatAttachment',
28
28
  doors: ['Query.chatMessages'],
29
+ /* The id it takes is written only in the conversation's history. */
30
+ needs: ['conversation'],
29
31
  description: 'Open a file that was sent earlier in this conversation. History names such files as "[attachment <id>: <name> ...]"; ' +
30
32
  'pass that id. An image comes back as the picture itself, a text file as its text (cut when long - the answer says so).',
31
33
  schema: {
@@ -79,6 +79,12 @@ export declare class ChatSession {
79
79
  * 함께 옮겨 적고, 목록도 같은 관문을 지난다.
80
80
  */
81
81
  lastMessageDoors?: string[];
82
+ /**
83
+ * The outside connection this conversation keeps the proposals of (ADR-0237 decision 11) - an authorization grant
84
+ * of the person, for one client. An agent outside the application hands 입력안 in through it; they wait here, in the
85
+ * person's own conversation, until the person presses them. One conversation per connection. The server's value.
86
+ */
87
+ connectionId?: string;
82
88
  lastSummary?: string;
83
89
  /**
84
90
  * `lastSummary` 가 **어디까지 덮는지** — 이 메시지까지 요약에 반영됐다.
@@ -123,6 +123,11 @@ tslib_1.__decorate([
123
123
  (0, type_graphql_1.Field)(() => [String], { nullable: true, description: 'Doors of the message the preview came from — the session list passes the same gate as the conversation.' }),
124
124
  tslib_1.__metadata("design:type", Array)
125
125
  ], ChatSession.prototype, "lastMessageDoors", void 0);
126
+ tslib_1.__decorate([
127
+ (0, typeorm_1.Column)({ nullable: true, length: 64 }),
128
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The outside connection (an authorization grant) whose handed-in proposals this conversation keeps. Written by the server.' }),
129
+ tslib_1.__metadata("design:type", String)
130
+ ], ChatSession.prototype, "connectionId", void 0);
126
131
  tslib_1.__decorate([
127
132
  (0, typeorm_1.Column)({
128
133
  nullable: true,
@@ -181,7 +186,10 @@ exports.ChatSession = ChatSession = tslib_1.__decorate([
181
186
  (0, typeorm_1.Index)('ix_chat_session_1', (session) => [session.domain, session.boardId])
182
187
  // 앵커 조회용 — chatSessionsByAnchor 가 [domain, anchorType, anchorId] 로 질의.
183
188
  ,
184
- (0, typeorm_1.Index)('ix_chat_session_2', (session) => [session.domain, session.anchorType, session.anchorId]),
189
+ (0, typeorm_1.Index)('ix_chat_session_2', (session) => [session.domain, session.anchorType, session.anchorId])
190
+ /* One conversation per outside connection (ADR-0237 decision 11) - two first calls at once make one, not two. */
191
+ ,
192
+ (0, typeorm_1.Index)('ix_chat_session_3', (session) => [session.domain, session.connectionId], { unique: true, where: '"connection_id" IS NOT NULL AND "deleted_at" IS NULL' }),
185
193
  (0, type_graphql_1.ObjectType)({
186
194
  description: 'One AI conversation, anchored to what it is about. An anchor may have several — threads, one per person, one per context.'
187
195
  })
@@ -47,10 +47,9 @@ function findEntryProposal(messages, key) {
47
47
  });
48
48
  if (!proposal)
49
49
  return { superseded: false };
50
- /* A later card of the same record and the same work replaces this one - pressing both would do the corrected work twice. */
51
- const superseded = messages
52
- .slice(at + 1)
53
- .some(message => (message.proposals ?? []).some(one => one?.kind === 'entry' && one?.target === proposal.target && (one?.op ?? 'create') === (proposal.op ?? 'create')));
50
+ /* A later card of the same work replaces this one - pressing both would do the corrected work twice (workOfProposal). */
51
+ const work = (0, entry_target_js_1.workOfProposal)(proposal);
52
+ const superseded = messages.slice(at + 1).some(message => (message.proposals ?? []).some(one => one?.kind === 'entry' && (0, entry_target_js_1.workOfProposal)(one) === work));
54
53
  return { proposal, superseded };
55
54
  }
56
55
  async function applyEntryProposal(key, deps, targetOf = entry_target_js_1.entryTargetOf) {
@@ -154,6 +154,13 @@ export interface EntryTarget {
154
154
  screen?: string;
155
155
  /** At most this many rows in one proposal. Default 200. */
156
156
  maxRows?: number;
157
+ /**
158
+ * The fields whose values make two 입력안 of this target the same work - a reply's inquiry, for example. A newer card
159
+ * of the same values replaces an older one; a card of other values stands beside it (ADR-0237: an agent hands in a
160
+ * reply to one inquiry, then to another, into one conversation). Absent: every 입력안 of the target is one work, and
161
+ * the newest replaces the rest - as a conversation corrects its one table of rows.
162
+ */
163
+ identity?: string[];
157
164
  /**
158
165
  * Read-only checks the application owns - a duplicate of what is already entered, a code that does not
159
166
  * exist. Asked when the rows are proposed and again when they are entered: the records may have moved.
@@ -323,3 +330,9 @@ export declare function offsetAt(timeZone: string | undefined, wall: string): st
323
330
  export declare function zonedDateTimes<T extends {
324
331
  values: Record<string, unknown>;
325
332
  }>(fields: EntryField[], rows: T[], timeZone: string | undefined): T[];
333
+ export declare function entryWorkOf(target: EntryTarget, op: 'create' | 'update', rows: {
334
+ id?: string;
335
+ values?: Record<string, unknown>;
336
+ }[]): string | undefined;
337
+ /** The work a stored card is, by the rule above. */
338
+ export declare function workOfProposal(proposal: any): string;
@@ -26,6 +26,8 @@ exports.resolveReferences = resolveReferences;
26
26
  exports.entryGroups = entryGroups;
27
27
  exports.offsetAt = offsetAt;
28
28
  exports.zonedDateTimes = zonedDateTimes;
29
+ exports.entryWorkOf = entryWorkOf;
30
+ exports.workOfProposal = workOfProposal;
29
31
  /*
30
32
  * Data entry from material - what an application declares so the assistant can enter its records
31
33
  * (operato-application/design/ai/data-entry.md).
@@ -100,6 +102,9 @@ function declareEntryTarget(target) {
100
102
  }
101
103
  if (typeof target.variables !== 'function' && typeof target.group?.variables !== 'function')
102
104
  throw new Error(`[ai-assistant] entry target '${target.key}' has no variables (per row, or per group).`);
105
+ for (const name of target.identity ?? [])
106
+ if (!target.fields.some(field => field.name === name))
107
+ throw new Error(`[ai-assistant] entry target '${target.key}': identity field '${name}' is not declared.`);
103
108
  if (target.group && !target.fields.some(field => field.name === target.group.by))
104
109
  throw new Error(`[ai-assistant] entry target '${target.key}': group by '${target.group.by}' is not a declared field.`);
105
110
  if (target.update) {
@@ -593,4 +598,30 @@ function zonedDateTimes(fields, rows, timeZone) {
593
598
  }
594
599
  return rows;
595
600
  }
601
+ /*
602
+ * Which work a card is - the one rule of replacing, read by the server when a card is pressed and by the screen when it
603
+ * draws one. A newer card of the same work replaces an older one; cards of other work stand side by side.
604
+ *
605
+ * a 수정안 the records it changes (`update:<ids>`)
606
+ * a 입력안 the values of the fields the target names as its identity (`create:<values>`)
607
+ * a 입력안 of a target that names none, and a card from before the rule, carry no work: the target and the kind of
608
+ * work make it, as they always did.
609
+ */
610
+ function entryWorkOf(target, op, rows) {
611
+ if (op === 'update')
612
+ return `${target.key}:update:${JSON.stringify([...new Set(rows.map(row => String(row.id ?? '')))].sort())}`;
613
+ if (!target.identity?.length)
614
+ return undefined;
615
+ const fields = target.identity.map(name => target.fields.find(field => field.name === name));
616
+ const valueOf = (field, value) => (field.axis && typeof value === 'string' ? recordIdOfKey(field.axis, value) ?? value : value) ?? null;
617
+ /* One field: its values; several: each row's values together. Sorted, so the same rows in another order are the same work. */
618
+ const keyOf = (row) => (fields.length === 1 ? valueOf(fields[0], row.values?.[fields[0].name]) : fields.map(field => valueOf(field, row.values?.[field.name])));
619
+ const distinct = new Map(rows.map(row => [JSON.stringify(keyOf(row)), keyOf(row)]));
620
+ const values = [...distinct.keys()].sort().map(key => distinct.get(key));
621
+ return `${target.key}:create:${JSON.stringify(values)}`;
622
+ }
623
+ /** The work a stored card is, by the rule above. */
624
+ function workOfProposal(proposal) {
625
+ return typeof proposal?.work === 'string' && proposal.work ? proposal.work : `${proposal?.target}:${proposal?.op ?? 'create'}`;
626
+ }
596
627
  //# sourceMappingURL=entry-target.js.map
@@ -15,9 +15,6 @@ export declare function proposeEntries(target: EntryTarget, args: any, context:
15
15
  screen?: string;
16
16
  screenLists?: true;
17
17
  groupBy?: string;
18
- proposed: boolean;
19
- kind: string;
20
- target: string;
21
18
  labelKey: string;
22
19
  label: string;
23
20
  icon: string;
@@ -48,6 +45,10 @@ export declare function proposeEntries(target: EntryTarget, args: any, context:
48
45
  verified: number;
49
46
  unmatched: number;
50
47
  };
48
+ work?: string;
49
+ proposed: boolean;
50
+ kind: string;
51
+ target: string;
51
52
  rejected?: undefined;
52
53
  error?: undefined;
53
54
  }>;
@@ -47,6 +47,7 @@ exports.registerEntryTarget = registerEntryTarget;
47
47
  * field's type, asks the target's own checks, and hands back a proposal - the card.
48
48
  */
49
49
  const ai_client_base_1 = require("@things-factory/ai-client-base");
50
+ const database_error_js_1 = require("../database-error.js");
50
51
  const entry_update_js_1 = require("./entry-update.js");
51
52
  const entry_screen_js_1 = require("./entry-screen.js");
52
53
  const entry_target_js_1 = require("./entry-target.js");
@@ -88,6 +89,19 @@ async function proposeEntries(target, args, context, loadTexts = readSources, ru
88
89
  await told({ rows: 0, ok: false, error: 'no-rows', detail: args });
89
90
  return { rejected: true, error: 'no-rows', message: 'no rows were given. Read the material and pass every record as a row.' };
90
91
  }
92
+ /*
93
+ * From an agent outside the application (ADR-0237 decision 11) there is no file of a conversation and no word the
94
+ * person said in one: a citation of either would stand for something nobody can check. Where in the agent's own
95
+ * material a value is from goes in `where`.
96
+ */
97
+ if (context?.outside && (normalized.some(row => row.sources.some(source => source.attachmentId || source.person)) || args?.declaredTotal?.attachmentId)) {
98
+ await told({ rows: normalized.length, ok: false, error: 'source-not-here', detail: args });
99
+ return {
100
+ rejected: true,
101
+ error: 'source-not-here',
102
+ message: 'this connection has no files of a conversation and no words of the person in one. Say where in your own material each value is from as sources: [{ where }], and call again.'
103
+ };
104
+ }
91
105
  /* The server looks in the cited files itself - the model's citation is not proof (design/ai/data-entry.md §4-1). */
92
106
  const declared = args?.declaredTotal && typeof args.declaredTotal === 'object' ? args.declaredTotal : undefined;
93
107
  const cited = [...normalized.flatMap(row => row.sources.map(source => source.attachmentId)), declared?.attachmentId].filter((id) => typeof id === 'string' && !!id);
@@ -117,6 +131,8 @@ async function proposeEntries(target, args, context, loadTexts = readSources, ru
117
131
  proposed: true,
118
132
  kind: 'entry',
119
133
  target: target.key,
134
+ /* Which work it is - a newer card of the same work replaces it (entryWorkOf). */
135
+ ...((0, entry_target_js_1.entryWorkOf)(target, 'create', rows) ? { work: (0, entry_target_js_1.entryWorkOf)(target, 'create', rows) } : {}),
120
136
  labelKey: target.labelKey,
121
137
  label: `${rows.length} ${target.key} rows`,
122
138
  icon: 'playlist_add',
@@ -147,7 +163,12 @@ const runAsCaller = (context) => async (document, variables) => {
147
163
  const result = operation === 'mutate'
148
164
  ? await GraphqlLocalClient.client.mutate({ mutation: gql(document), variables, context: { state, t: context?.t } })
149
165
  : await GraphqlLocalClient.client.query({ query: gql(document), variables, context: { state, t: context?.t }, fetchPolicy: 'no-cache' });
150
- return { data: result.data, errors: result.errors };
166
+ /* The local client does not pass the GraphQL door's plugin - its rule for a database error is kept here (ADR-0237). */
167
+ const errors = result.errors?.map((error) => {
168
+ const said = (0, database_error_js_1.databaseErrorUnspoken)(error, context?.t);
169
+ return said ? { message: said, ...(error?.path ? { path: error.path } : {}) } : error;
170
+ });
171
+ return { data: result.data, errors };
151
172
  };
152
173
  exports.runAsCaller = runAsCaller;
153
174
  /** The two tools of changing records - finding candidates, and the 수정안 (design/ai/data-entry.md §5-1). */
@@ -160,6 +181,9 @@ function changeSpecs(target, run) {
160
181
  {
161
182
  kind: 'read',
162
183
  name: (0, entry_target_js_1.changeToolName)(target.key),
184
+ /* A 수정안 card - nothing changes until the person presses it; it waits in the conversation until then. */
185
+ proposes: true,
186
+ keepsProposal: true,
163
187
  /* The person must be able to read the records and change them by hand. */
164
188
  doors: [...new Set([(0, entry_target_js_1.rootFieldOf)(update.mutation, 'mutation'), readDoor, ...(0, entry_target_js_1.referenceDoorsOf)((0, entry_update_js_1.changeableFields)(target))])],
165
189
  description: `Propose changes to existing records: ${target.description} ` +
@@ -203,6 +227,9 @@ function entryCategoryOf(target, run = exports.runAsCaller) {
203
227
  const spec = {
204
228
  kind: 'read',
205
229
  name,
230
+ /* An 입력안 card - nothing is written until the person presses it; it waits in the conversation until then. */
231
+ proposes: true,
232
+ keepsProposal: true,
206
233
  /* The person must be able to enter these records themselves - the tool is not a second way in. */
207
234
  doors: [(0, entry_target_js_1.entryDoorOf)(target.mutation), ...(0, entry_target_js_1.referenceDoorsOf)(target.fields)],
208
235
  description: `Propose records to enter: ${target.description} ` +
@@ -256,21 +283,33 @@ function entryCategoryOf(target, run = exports.runAsCaller) {
256
283
  return {
257
284
  name: (0, entry_target_js_1.entryCategoryName)(target.key),
258
285
  description: `data entry: ${target.key}`,
286
+ /*
287
+ * Every rule here is about the 입력안 or the 수정안 card - said where those tools are open, never to a door that has
288
+ * only the find (ADR-0237). The attachment reader is named in the first line, which still goes in a conversation
289
+ * that takes no files: it is a rule of entering, said there today. Its files and the screen's "current" and
290
+ * "selected" are a person's conversation's (`needs`) - an outside agent is not told of them.
291
+ */
259
292
  guidance: [
260
- `- When the person gives material to enter as records (files, photos, pasted text), read all of it first - call readChatAttachment for a file sent in an earlier turn - then call ${name} once with every record as a row.`,
261
- '- Never invent a value. Leave a field out when the material does not say it; the card marks it, and you ask the person for it.',
262
- '- A row kept out because a name was not found, or matches several records, is settled in the conversation: say which name, list the candidates the card names, and ask; then propose again with the name the person chose. The card has no picker - never tell the person to choose on it.',
263
- '- Give each row its sources: which attachment and where in it, written in the person\'s language. A value the person gave or corrected in the conversation adds the source { person: true }. The server looks for each row\'s numbers and dates in the cited file and marks what it does not find.',
264
- '- When the material prints a total, always pass it as declaredTotal exactly as printed - do not add it up yourself. The server also reads a total line of a text file itself.',
265
- `- ${name} only proposes. Nothing is entered until the person presses the button on the card - never say the records were entered.`,
266
- `- When the person corrects or drops rows, call ${name} again with the whole corrected set. The newest card replaces the earlier ones; an earlier card can no longer be entered.`,
293
+ { text: `- When the person gives material to enter as records (files, photos, pasted text), read all of it first - call readChatAttachment for a file sent in an earlier turn - then call ${name} once with every record as a row.`, tools: [name], needs: ['conversation'] },
294
+ { text: '- Never invent a value. Leave a field out when the material does not say it; the card marks it, and you ask the person for it.', tools: [name] },
295
+ { text: '- A row kept out because a name was not found, or matches several records, is settled in the conversation: say which name, list the candidates the card names, and ask; then propose again with the name the person chose. The card has no picker - never tell the person to choose on it.', tools: [name] },
296
+ { text: '- Give each row its sources: which attachment and where in it, written in the person\'s language. A value the person gave or corrected in the conversation adds the source { person: true }. The server looks for each row\'s numbers and dates in the cited file and marks what it does not find.', tools: [name], needs: ['conversation'] },
297
+ { text: '- When the material prints a total, always pass it as declaredTotal exactly as printed - do not add it up yourself. The server also reads a total line of a text file itself.', tools: [name] },
298
+ { text: `- ${name} only proposes. Nothing is entered until the person presses the button on the card - never say the records were entered.`, tools: [name] },
299
+ { text: `- When the person corrects or drops rows, call ${name} again with the whole corrected set. The newest card replaces the earlier ones; an earlier card can no longer be entered.`, tools: [name] },
267
300
  ...(target.update
268
301
  ? [
269
- `- To change records that exist, call ${(0, entry_target_js_1.changeToolName)(target.key)}. Use ref "current" for the record on screen and "selected" for the rows selected there.${target.update.find ? ` Otherwise call ${(0, entry_target_js_1.findToolName)(target.key)} first with what the person said; if more than one record matches, list them and ask which - never pick one yourself.` : ' Otherwise ask the person to open or select the record.'}`,
270
- `- ${(0, entry_target_js_1.changeToolName)(target.key)} only proposes; the card shows each record's value now and after. Never say a record was changed.`
302
+ { text: `- To change records that exist, call ${(0, entry_target_js_1.changeToolName)(target.key)}. Use ref "current" for the record on screen and "selected" for the rows selected there.${target.update.find ? ` Otherwise call ${(0, entry_target_js_1.findToolName)(target.key)} first with what the person said; if more than one record matches, list them and ask which - never pick one yourself.` : ' Otherwise ask the person to open or select the record.'}`, tools: [(0, entry_target_js_1.changeToolName)(target.key)], needs: ['screen'] },
303
+ /* The same rule without a screen to point at - records are named by their ids (an outside agent, ADR-0237). */
304
+ {
305
+ text: `- To change records that exist, call ${(0, entry_target_js_1.changeToolName)(target.key)} naming each record by its id or key.${target.update.find ? ` Call ${(0, entry_target_js_1.findToolName)(target.key)} first with what is known; if more than one record matches, list them and ask which - never pick one yourself.` : ' Ask which record when it is not known.'}`,
306
+ tools: [(0, entry_target_js_1.changeToolName)(target.key)],
307
+ without: ['screen']
308
+ },
309
+ { text: `- ${(0, entry_target_js_1.changeToolName)(target.key)} only proposes; the card shows each record's value now and after. Never say a record was changed.`, tools: [(0, entry_target_js_1.changeToolName)(target.key)] }
271
310
  ]
272
311
  : [])
273
- ].join('\n'),
312
+ ],
274
313
  specs: [spec, ...changeSpecs(target, run)]
275
314
  };
276
315
  }
@@ -57,6 +57,7 @@ export declare function proposeChanges(target: EntryTarget, args: any, context:
57
57
  kind: string;
58
58
  op: string;
59
59
  target: string;
60
+ work: string;
60
61
  labelKey: string;
61
62
  label: string;
62
63
  icon: string;
@@ -151,6 +151,8 @@ async function proposeChanges(target, args, context, run) {
151
151
  kind: 'entry',
152
152
  op: 'update',
153
153
  target: target.key,
154
+ /* The records it changes - a newer 수정안 of the same records replaces it (entryWorkOf). */
155
+ work: (0, entry_target_js_1.entryWorkOf)(target, 'update', rows),
154
156
  labelKey: target.labelKey,
155
157
  label: `${rows.length} ${target.key} changes`,
156
158
  icon: 'edit_note',
@@ -180,6 +180,8 @@ function readCategoryOf(target, run = entry_tools_js_1.runAsCaller) {
180
180
  name: { type: 'string', description: 'The workspace key; the same key again makes a new version.' }
181
181
  }
182
182
  },
183
+ /* `show`, `title` and `name` shape the AI 작업 패널 - a door with no panel leaves them out (ADR-0237 decision 3). */
184
+ screenArgs: ['show', 'title', 'name'],
183
185
  builder: (args, context) => queryRecords(target, args, context, run(context))
184
186
  },
185
187
  ...(target.screen
@@ -190,6 +192,8 @@ function readCategoryOf(target, run = entry_tools_js_1.runAsCaller) {
190
192
  doors: [door],
191
193
  description: `Offer the person the screen that lists ${target.description} with these conditions. Reads nothing. The screen takes: ${target.screen.takes.join(', ')}.`,
192
194
  schema: { type: 'object', properties: conditions },
195
+ /* A card that opens the screen - it reads nothing. */
196
+ proposes: true,
193
197
  builder: (args, context) => openScreen(target, args, context)
194
198
  }
195
199
  ]
@@ -198,15 +202,16 @@ function readCategoryOf(target, run = entry_tools_js_1.runAsCaller) {
198
202
  return {
199
203
  name: (0, read_target_js_1.readCategoryName)(target.key),
200
204
  description: `data read: ${target.key}`,
205
+ /* Each rule names the tools it speaks of - a door without the panel or the screen card is not told of them (ADR-0237). */
201
206
  guidance: [
202
- `- To answer from ${target.key} records - a list, or one record found by its name, code or id - call ${(0, read_target_js_1.queryToolName)(target.key)} with the conditions the question names. Every number you say comes from its result - never add up rows yourself; use its sums and groups.`,
203
- `- A list, a summary by item or month, or a comparison: call it with groupBy, and let a long result go on the AI 작업 패널 - then answer in one or two lines.`,
204
- `- When the result says complete: false, say how many of how many were read and ask to narrow - never call partial sums the total.`,
207
+ { text: `- To answer from ${target.key} records - a list, or one record found by its name, code or id - call ${(0, read_target_js_1.queryToolName)(target.key)} with the conditions the question names. Every number you say comes from its result - never add up rows yourself; use its sums and groups.`, tools: [(0, read_target_js_1.queryToolName)(target.key)] },
208
+ { text: `- A list, a summary by item or month, or a comparison: call it with groupBy, and let a long result go on the AI 작업 패널 - then answer in one or two lines.`, tools: [(0, read_target_js_1.queryToolName)(target.key), workspace_blocks_js_1.WORKSPACE_TOOL] },
209
+ { text: `- When the result says complete: false, say how many of how many were read and ask to narrow - never call partial sums the total.`, tools: [(0, read_target_js_1.queryToolName)(target.key)] },
205
210
  ...(target.columns.some(one => one.currency)
206
- ? [`- Sums of ${target.columns.filter(one => one.currency).map(one => one.name).join(', ')} come per currency. Say each currency's sum; never add two currencies into one number. A comparison across currencies uses a rate you read, and says the rate and its date.`]
211
+ ? [{ text: `- Sums of ${target.columns.filter(one => one.currency).map(one => one.name).join(', ')} come per currency. Say each currency's sum; never add two currencies into one number. A comparison across currencies uses a rate you read, and says the rate and its date.`, tools: [(0, read_target_js_1.queryToolName)(target.key)] }]
207
212
  : []),
208
- ...(target.screen ? [`- When the person wants to work on the records themselves (edit, sort, export), call ${(0, read_target_js_1.screenToolName)(target.key)}; say which conditions the screen does not take.`] : [])
209
- ].join('\n'),
213
+ ...(target.screen ? [{ text: `- When the person wants to work on the records themselves (edit, sort, export), call ${(0, read_target_js_1.screenToolName)(target.key)}; say which conditions the screen does not take.`, tools: [(0, read_target_js_1.screenToolName)(target.key)] }] : [])
214
+ ],
210
215
  specs
211
216
  };
212
217
  }
@@ -0,0 +1,5 @@
1
+ /** The same key and words the GraphQL door uses. */
2
+ export declare const DATABASE_FAILED = "error.database-failed";
3
+ export declare const DATABASE_FAILED_SAID = "The server could not process this. Tell your administrator.";
4
+ /** The sentence to say instead when `error` is the database's, logging what it said; undefined for any other error. */
5
+ export declare function databaseErrorUnspoken(error: unknown, t?: (key: string, params?: Record<string, any>) => string): string | undefined;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DATABASE_FAILED_SAID = exports.DATABASE_FAILED = void 0;
4
+ exports.databaseErrorUnspoken = databaseErrorUnspoken;
5
+ /*
6
+ * A database error does not reach a reader as the database said it - the rule the GraphQL door keeps for the screens
7
+ * (shell `databaseErrorsUnspoken`), for the roads that do not pass through that door: the application's API run as
8
+ * the person (`runAsCaller`) and the tools an outside agent calls (`/mcp`).
9
+ *
10
+ * `column "salary_amount" of relation "payroll_lines" does not exist` names tables and columns and helps no reader.
11
+ * The reader gets one sentence in the request's language; the server log keeps the database's own words. A refusal is
12
+ * not touched - it was meant, and says why.
13
+ */
14
+ const typeorm_1 = require("typeorm");
15
+ const env_1 = require("@things-factory/env");
16
+ /** The same key and words the GraphQL door uses. */
17
+ exports.DATABASE_FAILED = 'error.database-failed';
18
+ exports.DATABASE_FAILED_SAID = 'The server could not process this. Tell your administrator.';
19
+ /** The sentence to say instead when `error` is the database's, logging what it said; undefined for any other error. */
20
+ function databaseErrorUnspoken(error, t) {
21
+ const original = error?.originalError ?? error;
22
+ if (!(original instanceof typeorm_1.QueryFailedError))
23
+ return undefined;
24
+ env_1.logger.error(original);
25
+ return typeof t === 'function' ? t(exports.DATABASE_FAILED, { defaultValue: exports.DATABASE_FAILED_SAID }) : exports.DATABASE_FAILED_SAID;
26
+ }
27
+ //# sourceMappingURL=database-error.js.map
@@ -56,3 +56,4 @@ export declare const entities: (typeof import("./chat-message/chat-message.js").
56
56
  export declare const schema: {
57
57
  resolverClasses: (typeof ChatSessionResolver | typeof AssistantProgressSubscription | typeof AssistantChatResolver | typeof AssistantModeResolver | typeof AssistantCapabilityResolver | typeof AiAgentResolver | typeof MySessionActivitySubscription | typeof ChatMessageSubscription | typeof ChatTypingSubscription | typeof EntryProposalResolver)[];
58
58
  };
59
+ export { registerAssistantHome, type AssistantHome } from './mcp/mcp-conversation.js';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.schema = exports.entities = exports.assertMayWriteSession = exports.PROPOSAL_OUTCOME_PREFIX = exports.runDetail = exports.detailCategoryOf = exports.registerDetailRead = exports.readCategoryOf = exports.registerReadTarget = exports.MAX_CHANGES = exports.proposeChanges = exports.runAsCaller = exports.entryCategoryOf = exports.registerEntryTarget = exports.requestTranslator = void 0;
3
+ exports.registerAssistantHome = exports.schema = exports.entities = exports.assertMayWriteSession = exports.PROPOSAL_OUTCOME_PREFIX = exports.runDetail = exports.detailCategoryOf = exports.registerDetailRead = exports.readCategoryOf = exports.registerReadTarget = exports.MAX_CHANGES = exports.proposeChanges = exports.runAsCaller = exports.entryCategoryOf = exports.registerEntryTarget = exports.requestTranslator = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const chat_session_resolver_js_1 = require("./chat-session-resolver.js");
6
6
  const assistant_chat_resolver_js_1 = require("./assistant-chat-resolver.js");
@@ -113,4 +113,7 @@ exports.schema = {
113
113
  entry_resolver_js_1.EntryProposalResolver
114
114
  ]
115
115
  };
116
+ /* An app names the anchor its assistant opens at home - where a conversation the server makes for a person is listed. */
117
+ var mcp_conversation_js_1 = require("./mcp/mcp-conversation.js");
118
+ Object.defineProperty(exports, "registerAssistantHome", { enumerable: true, get: function () { return mcp_conversation_js_1.registerAssistantHome; } });
116
119
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ import type { ToolCallContext, ToolCallRecord } from '@things-factory/ai-client-base';
2
+ import type { McpRefusal } from './mcp-scope.js';
3
+ export declare const MCP_AUDIT_KIND = "mcp.tool-call";
4
+ /** A recorder for the registry's runner - the calls whose road is `mcp`, and no other. */
5
+ export declare function auditMcpCall(record: ToolCallRecord, context: ToolCallContext): Promise<void>;
6
+ /** A call refused before it ran. */
7
+ export declare function auditMcpRefusal(state: any, refusal: McpRefusal): Promise<void>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MCP_AUDIT_KIND = void 0;
4
+ exports.auditMcpCall = auditMcpCall;
5
+ exports.auditMcpRefusal = auditMcpRefusal;
6
+ /*
7
+ * Every call from outside the application, in the framework's audit (ADR-0237 decision 4) - whatever app serves it and
8
+ * whoever registered the tool. An application's own AI audit (Office's) still writes what it writes; this is the floor
9
+ * every app has: who, in which domain, which tool of which category, from which client, how it ended, and when.
10
+ *
11
+ * A call refused before it ran - a name nobody registered, a tool that does not go out, a door the person lacks - is
12
+ * written too, as refused, with why. The client is told only that the tool is unknown; the audit says which it was.
13
+ *
14
+ * The row is auth-base's (`AuditAction`, ADR-0141): no arguments and no result are kept, only the ids the arguments
15
+ * name, how many rows came back and the error's code.
16
+ */
17
+ const auth_base_1 = require("@things-factory/auth-base");
18
+ exports.MCP_AUDIT_KIND = 'mcp.tool-call';
19
+ (0, auth_base_1.registerAuditKind)(exports.MCP_AUDIT_KIND, ['tool', 'category', 'client', 'durationMs']);
20
+ const whoOf = (state) => ({ actorId: state?.user?.id ?? null, domainId: state?.domain?.id ?? null });
21
+ /** A recorder for the registry's runner - the calls whose road is `mcp`, and no other. */
22
+ async function auditMcpCall(record, context) {
23
+ if (record.path !== 'mcp')
24
+ return;
25
+ await (0, auth_base_1.recordAuditAction)({
26
+ kind: exports.MCP_AUDIT_KIND,
27
+ decision: 'granted',
28
+ outcome: record.ok ? 'ok' : 'error',
29
+ ...(record.errorCode ? { code: record.errorCode } : {}),
30
+ ...(record.resultCount !== undefined ? { returned: record.resultCount } : {}),
31
+ ...(record.targetIds.length ? { targetIds: record.targetIds } : {}),
32
+ detail: { tool: record.tool, category: record.category, client: record.client ?? null, durationMs: record.durationMs }
33
+ }, whoOf(context?.state));
34
+ }
35
+ /** A call refused before it ran. */
36
+ async function auditMcpRefusal(state, refusal) {
37
+ await (0, auth_base_1.recordAuditAction)({
38
+ kind: exports.MCP_AUDIT_KIND,
39
+ decision: 'denied',
40
+ code: refusal.code,
41
+ detail: { tool: refusal.tool, category: refusal.category ?? null, client: state?.oauth?.clientId ?? null }
42
+ }, whoOf(state));
43
+ }
44
+ //# sourceMappingURL=mcp-audit.js.map
@@ -0,0 +1,60 @@
1
+ import { type ToolAccessCheck, type ToolSpec, type ToolTranslate } from '@things-factory/ai-client-base';
2
+ /** What MCP's `tools/call` answers. */
3
+ export interface McpToolResult {
4
+ content: ({
5
+ type: 'text';
6
+ text: string;
7
+ } | {
8
+ type: 'image';
9
+ data: string;
10
+ mimeType: string;
11
+ })[];
12
+ isError?: boolean;
13
+ }
14
+ /** A proposal handed in from outside, as its card - kept in the person's conversation for the connection. */
15
+ export interface McpKept {
16
+ /** This server's origin as the client reached it - the address handed back is a full one. */
17
+ origin?: string;
18
+ sessionId: string;
19
+ tool: string;
20
+ category: string;
21
+ doors: string[];
22
+ card: Record<string, any>;
23
+ state: any;
24
+ t: ToolTranslate;
25
+ }
26
+ /** Where a proposal handed in from outside goes (ADR-0237 decision 11). */
27
+ export interface McpOutside {
28
+ /** The person's conversation for this connection - made the first time, the same one after. */
29
+ conversationOf(state: any, t: ToolTranslate): Promise<{
30
+ id: string;
31
+ name: string;
32
+ }>;
33
+ /** Keeps the card as a message of that conversation and tells the person; where they find it, and the earlier cards of the same work it replaced. */
34
+ keep(kept: McpKept): Promise<{
35
+ address: string;
36
+ replaced: string[];
37
+ }>;
38
+ }
39
+ export interface McpCall {
40
+ spec: ToolSpec;
41
+ category: string;
42
+ args: unknown;
43
+ state: any;
44
+ t: ToolTranslate;
45
+ access: ToolAccessCheck;
46
+ /** The client the person connected - written on the record. */
47
+ client?: string;
48
+ /** Where a kept proposal goes; a tool that keeps one is not offered without it. */
49
+ outside?: McpOutside;
50
+ origin?: string;
51
+ }
52
+ /**
53
+ * A proposal that could not be kept - the conversation or its message could not be written. The call is recorded as a
54
+ * failure and the client gets a JSON-RPC error: it is never told a card was handed in that is not there.
55
+ */
56
+ export declare class McpKeepFailed extends Error {
57
+ readonly code = "mcp-keep-failed";
58
+ constructor();
59
+ }
60
+ export declare function callMcpTool({ spec, category, args, state, t, access, client, outside, origin }: McpCall): Promise<McpToolResult>;