@things-factory/ai-assistant 10.1.88 → 10.1.90

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 (64) hide show
  1. package/client/components/assistant-chat.ts +19 -5
  2. package/client/components/assistant-dock.ts +21 -1
  3. package/client/components/entry-review.ts +246 -0
  4. package/client/utils/assistant-proposals.ts +11 -1
  5. package/client/utils/entry-proposal.ts +103 -0
  6. package/dist-client/components/assistant-chat.d.ts +1 -0
  7. package/dist-client/components/assistant-chat.js +19 -5
  8. package/dist-client/components/assistant-chat.js.map +1 -1
  9. package/dist-client/components/assistant-dock.js +16 -1
  10. package/dist-client/components/assistant-dock.js.map +1 -1
  11. package/dist-client/components/entry-review.d.ts +9 -0
  12. package/dist-client/components/entry-review.js +247 -0
  13. package/dist-client/components/entry-review.js.map +1 -0
  14. package/dist-client/tsconfig.tsbuildinfo +1 -1
  15. package/dist-client/utils/assistant-proposals.d.ts +1 -0
  16. package/dist-client/utils/assistant-proposals.js +9 -1
  17. package/dist-client/utils/assistant-proposals.js.map +1 -1
  18. package/dist-client/utils/entry-proposal.d.ts +55 -0
  19. package/dist-client/utils/entry-proposal.js +52 -0
  20. package/dist-client/utils/entry-proposal.js.map +1 -0
  21. package/dist-server/service/assistant-mode/registry.js +13 -0
  22. package/dist-server/service/assistant-mode/registry.js.map +1 -1
  23. package/dist-server/service/assistant-mode/resolve.d.ts +11 -0
  24. package/dist-server/service/assistant-mode/resolve.js +13 -3
  25. package/dist-server/service/assistant-mode/resolve.js.map +1 -1
  26. package/dist-server/service/assistant-mode/types.d.ts +7 -1
  27. package/dist-server/service/assistant-mode/types.js.map +1 -1
  28. package/dist-server/service/data-entry/entry-apply.d.ts +46 -0
  29. package/dist-server/service/data-entry/entry-apply.js +102 -0
  30. package/dist-server/service/data-entry/entry-apply.js.map +1 -0
  31. package/dist-server/service/data-entry/entry-resolver.d.ts +4 -0
  32. package/dist-server/service/data-entry/entry-resolver.js +80 -0
  33. package/dist-server/service/data-entry/entry-resolver.js.map +1 -0
  34. package/dist-server/service/data-entry/entry-sources.d.ts +1 -0
  35. package/dist-server/service/data-entry/entry-sources.js +41 -0
  36. package/dist-server/service/data-entry/entry-sources.js.map +1 -0
  37. package/dist-server/service/data-entry/entry-target.d.ts +157 -0
  38. package/dist-server/service/data-entry/entry-target.js +343 -0
  39. package/dist-server/service/data-entry/entry-target.js.map +1 -0
  40. package/dist-server/service/data-entry/entry-tools.d.ts +43 -0
  41. package/dist-server/service/data-entry/entry-tools.js +185 -0
  42. package/dist-server/service/data-entry/entry-tools.js.map +1 -0
  43. package/dist-server/service/index.d.ts +4 -1
  44. package/dist-server/service/index.js +10 -2
  45. package/dist-server/service/index.js.map +1 -1
  46. package/dist-server/tsconfig.tsbuildinfo +1 -1
  47. package/package.json +2 -2
  48. package/server/service/assistant-mode/registry.ts +13 -0
  49. package/server/service/assistant-mode/resolve.ts +13 -3
  50. package/server/service/assistant-mode/types.ts +7 -1
  51. package/server/service/data-entry/data-entry.test.ts +311 -0
  52. package/server/service/data-entry/entry-apply.ts +134 -0
  53. package/server/service/data-entry/entry-resolver.ts +74 -0
  54. package/server/service/data-entry/entry-sources.ts +35 -0
  55. package/server/service/data-entry/entry-target.ts +442 -0
  56. package/server/service/data-entry/entry-tools.ts +174 -0
  57. package/server/service/index.ts +7 -1
  58. package/test/entry-proposal.test.ts +67 -0
  59. package/test/open-doors.test.ts +2 -1
  60. package/translations/en.json +36 -1
  61. package/translations/ja.json +36 -1
  62. package/translations/ko.json +36 -1
  63. package/translations/ms.json +36 -1
  64. package/translations/zh.json +36 -1
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EntryProposalResolver = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const type_graphql_1 = require("type-graphql");
6
+ const graphql_scalars_1 = require("graphql-scalars");
7
+ const typeorm_1 = require("typeorm");
8
+ const env_1 = require("@things-factory/env");
9
+ const graphql_tag_1 = tslib_1.__importDefault(require("graphql-tag"));
10
+ const shell_1 = require("@things-factory/shell");
11
+ const chat_session_js_1 = require("../chat-session/chat-session.js");
12
+ const chat_message_js_1 = require("../chat-message/chat-message.js");
13
+ const session_write_gate_js_1 = require("../chat-session/session-write-gate.js");
14
+ const participant_lookup_js_1 = require("../chat-session-participant/participant-lookup.js");
15
+ const proposal_outcome_js_1 = require("../chat-message/proposal-outcome.js");
16
+ const tool_access_js_1 = require("../tool-access.js");
17
+ const entry_apply_js_1 = require("./entry-apply.js");
18
+ let EntryProposalResolver = class EntryProposalResolver {
19
+ /*
20
+ * Not `@transaction`: each row is its own call of the application's mutation (entry-apply.ts), so one
21
+ * refused row keeps the others. The dock reports the outcome afterwards through `reportProposalOutcome`.
22
+ */
23
+ async applyEntryProposal(sessionId, proposalKey, context) {
24
+ const { domain, user } = context.state;
25
+ const session = await (0, shell_1.getRepository)(chat_session_js_1.ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } });
26
+ if (!session)
27
+ throw new Error(`ChatSession ${sessionId} not found`);
28
+ await (0, session_write_gate_js_1.assertMayWriteSession)({
29
+ session,
30
+ userId: user?.id,
31
+ isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, session.id, user?.id),
32
+ t: (key, options) => (context.t ? context.t(key, options) : String(options?.defaultValue ?? key))
33
+ });
34
+ const key = (proposalKey ?? '').trim();
35
+ const carrying = await (0, shell_1.getRepository)(chat_message_js_1.ChatMessage).find({
36
+ select: ['id', 'proposals', 'createdAt'],
37
+ where: { session: { id: session.id }, proposals: (0, typeorm_1.Not)((0, typeorm_1.IsNull)()) },
38
+ order: { createdAt: 'ASC' }
39
+ });
40
+ const lines = await (0, shell_1.getRepository)(chat_message_js_1.ChatMessage).find({
41
+ select: ['content'],
42
+ where: { session: { id: session.id }, role: 'system', content: (0, typeorm_1.Like)(`${proposal_outcome_js_1.PROPOSAL_OUTCOME_PREFIX}${key}:%`) }
43
+ });
44
+ const passes = (0, tool_access_js_1.toolAccessFor)(context);
45
+ return await (0, entry_apply_js_1.applyEntryProposal)(key, {
46
+ messages: carrying.map((message) => ({ id: message.id, proposals: message.proposalsJson ?? [] })),
47
+ answered: (0, entry_apply_js_1.entryProposalAnswered)(key, lines.map((line) => line.content)),
48
+ passesDoor: door => passes(door),
49
+ state: context.state,
50
+ /*
51
+ * The application's API, as the person - the same request state the door would have seen had they typed
52
+ * the row in: domain, user, and what their address and prohibitions say. No `tx` is handed on, so the
53
+ * door opens its own transaction per row.
54
+ */
55
+ execute: async (mutation, variables) => {
56
+ const { tx: _tx, afterCommit: _after, ...state } = context.state;
57
+ const result = await shell_1.GraphqlLocalClient.client.mutate({ mutation: (0, graphql_tag_1.default)(mutation), variables, context: { state, t: context.t } });
58
+ return { data: result.data, errors: result.errors };
59
+ },
60
+ report: (message, error) => env_1.logger.error(message, error)
61
+ });
62
+ }
63
+ };
64
+ exports.EntryProposalResolver = EntryProposalResolver;
65
+ tslib_1.__decorate([
66
+ (0, type_graphql_1.Mutation)(() => graphql_scalars_1.GraphQLJSON, {
67
+ description: 'Enter the rows of a data entry proposal the person pressed. The rows are the stored proposal\'s; the door, a newer proposal and the target\'s checks are asked again, and each row is written in its own transaction.'
68
+ }),
69
+ (0, type_graphql_1.Directive)('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)'),
70
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('sessionId')),
71
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('proposalKey')),
72
+ tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
73
+ tslib_1.__metadata("design:type", Function),
74
+ tslib_1.__metadata("design:paramtypes", [String, String, Object]),
75
+ tslib_1.__metadata("design:returntype", Promise)
76
+ ], EntryProposalResolver.prototype, "applyEntryProposal", null);
77
+ exports.EntryProposalResolver = EntryProposalResolver = tslib_1.__decorate([
78
+ (0, type_graphql_1.Resolver)()
79
+ ], EntryProposalResolver);
80
+ //# sourceMappingURL=entry-resolver.js.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CAAC,IAAI,CAAC;YAChC,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB;;;;eAIG;YACH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE;gBACrC,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC,KAAY,CAAA;gBACvE,MAAM,MAAM,GAAQ,MAAM,0BAAkB,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAA,qBAAG,EAAC,QAAQ,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;gBACpI,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAA;YACrD,CAAC;YACD,MAAM,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,YAAM,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC;SACzD,CAAC,CAAA;IACJ,CAAC;CACF,CAAA;AAvDY,sDAAqB;AAU1B;IALL,IAAA,uBAAQ,EAAC,GAAG,EAAE,CAAC,6BAAW,EAAE;QAC3B,WAAW,EACT,uNAAuN;KAC1N,CAAC;IACD,IAAA,wBAAS,EAAC,uFAAuF,CAAC;IAEhG,mBAAA,IAAA,kBAAG,EAAC,WAAW,CAAC,CAAA;IAChB,mBAAA,IAAA,kBAAG,EAAC,aAAa,CAAC,CAAA;IAClB,mBAAA,IAAA,kBAAG,GAAE,CAAA;;;;+DAyCP;gCAtDU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CAuDjC","sourcesContent":["import { Resolver, Mutation, Arg, Ctx, Directive } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\nimport { Like, Not, IsNull } from 'typeorm'\n\nimport { logger } from '@things-factory/env'\nimport gql from 'graphql-tag'\n\nimport { getRepository, GraphqlLocalClient } from '@things-factory/shell'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\nimport { ChatMessage } from '../chat-message/chat-message.js'\nimport { assertMayWriteSession } from '../chat-session/session-write-gate.js'\nimport { isSessionParticipant } from '../chat-session-participant/participant-lookup.js'\nimport { PROPOSAL_OUTCOME_PREFIX } from '../chat-message/proposal-outcome.js'\nimport { toolAccessFor } from '../tool-access.js'\nimport { applyEntryProposal, entryProposalAnswered, type EntryApplyOutcome } from './entry-apply.js'\n\n@Resolver()\nexport class EntryProposalResolver {\n /*\n * Not `@transaction`: each row is its own call of the application's mutation (entry-apply.ts), so one\n * refused row keeps the others. The dock reports the outcome afterwards through `reportProposalOutcome`.\n */\n @Mutation(() => GraphQLJSON, {\n description:\n 'Enter the rows of a data entry proposal the person pressed. The rows are the stored proposal\\'s; the door, a newer proposal and the target\\'s checks are asked again, and each row is written in its own transaction.'\n })\n @Directive('@privilege(category: \"ai-assistant\", privilege: \"mutation\", domainOwnerGranted: true)')\n async applyEntryProposal(\n @Arg('sessionId') sessionId: string,\n @Arg('proposalKey') proposalKey: string,\n @Ctx() context: ResolverContext\n ): Promise<EntryApplyOutcome> {\n const { domain, user } = context.state\n const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } } as any)\n if (!session) throw new Error(`ChatSession ${sessionId} not found`)\n await assertMayWriteSession({\n session,\n userId: user?.id,\n isParticipant: () => isSessionParticipant(domain.id, session.id, user?.id),\n t: (key, options) => (context.t ? context.t(key, options) : String(options?.defaultValue ?? key))\n })\n\n const key = (proposalKey ?? '').trim()\n const carrying = await getRepository(ChatMessage).find({\n select: ['id', 'proposals', 'createdAt'] as any,\n where: { session: { id: session.id } as any, proposals: Not(IsNull()) } as any,\n order: { createdAt: 'ASC' } as any\n })\n const lines = await getRepository(ChatMessage).find({\n select: ['content'] as any,\n where: { session: { id: session.id } as any, role: 'system', content: Like(`${PROPOSAL_OUTCOME_PREFIX}${key}:%`) } as any\n })\n\n const passes = toolAccessFor(context)\n return await applyEntryProposal(key, {\n messages: carrying.map((message: any) => ({ id: message.id, proposals: message.proposalsJson ?? [] })),\n answered: entryProposalAnswered(key, lines.map((line: any) => line.content)),\n passesDoor: door => passes(door),\n state: context.state,\n /*\n * The application's API, as the person - the same request state the door would have seen had they typed\n * the row in: domain, user, and what their address and prohibitions say. No `tx` is handed on, so the\n * door opens its own transaction per row.\n */\n execute: async (mutation, variables) => {\n const { tx: _tx, afterCommit: _after, ...state } = context.state as any\n const result: any = await GraphqlLocalClient.client.mutate({ mutation: gql(mutation), variables, context: { state, t: context.t } })\n return { data: result.data, errors: result.errors }\n },\n report: (message, error) => logger.error(message, error)\n })\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare function loadSourceTexts(ids: string[], context: any): Promise<Map<string, string>>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadSourceTexts = loadSourceTexts;
4
+ /*
5
+ * The text of the files a proposal cites - read through the conversation's own gate, as readChatAttachment
6
+ * reads them (chat-session/attachment-tools.ts). A file of another conversation, or of a private one the
7
+ * caller does not sit in, is not read: it is left out, and the rows citing it say they were not checked.
8
+ */
9
+ const attachment_base_1 = require("@things-factory/attachment-base");
10
+ const shell_1 = require("@things-factory/shell");
11
+ const chat_session_js_1 = require("../chat-session/chat-session.js");
12
+ const session_visibility_js_1 = require("../chat-session/session-visibility.js");
13
+ const participant_lookup_js_1 = require("../chat-session-participant/participant-lookup.js");
14
+ const session_attachments_js_1 = require("../chat-session/session-attachments.js");
15
+ const attachment_policy_js_1 = require("../chat-session/attachment-policy.js");
16
+ /** The whole text is read - the check must see every line, not the part the model was shown. */
17
+ const MAX_CHARS = 2_000_000;
18
+ async function loadSourceTexts(ids, context) {
19
+ const { domain, user } = context?.state ?? {};
20
+ const texts = new Map();
21
+ if (!domain?.id)
22
+ return texts;
23
+ for (const id of [...new Set(ids)].slice(0, 20)) {
24
+ const row = await (0, shell_1.getRepository)(attachment_base_1.Attachment).findOne({ where: { id, domain: { id: domain.id }, refType: session_attachments_js_1.CHAT_ATTACHMENT_REF } });
25
+ const session = row && (await (0, shell_1.getRepository)(chat_session_js_1.ChatSession).findOne({ where: { id: row.refBy, domain: { id: domain.id } } }));
26
+ if (!row || !session)
27
+ continue;
28
+ if (!(0, session_visibility_js_1.mayReadSession)(session.visibility, await (0, participant_lookup_js_1.isSessionParticipant)(domain.id, session.id, user?.id)))
29
+ continue;
30
+ if ((0, attachment_policy_js_1.attachmentKindOf)({ type: row.mimetype, name: row.name }) !== 'text')
31
+ continue;
32
+ try {
33
+ texts.set(id, String(await attachment_base_1.STORAGE.readFile(row.path, 'utf8')).slice(0, MAX_CHARS));
34
+ }
35
+ catch {
36
+ /* gone from storage - the rows citing it say they were not checked */
37
+ }
38
+ }
39
+ return texts;
40
+ }
41
+ //# sourceMappingURL=entry-sources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-sources.js","sourceRoot":"","sources":["../../../server/service/data-entry/entry-sources.ts"],"names":[],"mappings":";;AAiBA,0CAiBC;AAlCD;;;;GAIG;AACH,qEAAqE;AACrE,iDAAqD;AAErD,qEAA6D;AAC7D,iFAAsE;AACtE,6FAAwF;AACxF,mFAA4E;AAC5E,+EAAuE;AAEvE,gGAAgG;AAChG,MAAM,SAAS,GAAG,SAAS,CAAA;AAEpB,KAAK,UAAU,eAAe,CAAC,GAAa,EAAE,OAAY;IAC/D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,KAAK,IAAI,EAAE,CAAA;IAC7C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAA;IACvC,IAAI,CAAC,MAAM,EAAE,EAAE;QAAE,OAAO,KAAK,CAAA;IAC7B,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,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n * reads them (chat-session/attachment-tools.ts). A file of another conversation, or of a private one the\n * caller does not sit in, is not read: it is left out, and the rows citing it say they were not checked.\n */\nimport { Attachment, STORAGE } from '@things-factory/attachment-base'\nimport { getRepository } from '@things-factory/shell'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\nimport { mayReadSession } from '../chat-session/session-visibility.js'\nimport { isSessionParticipant } from '../chat-session-participant/participant-lookup.js'\nimport { CHAT_ATTACHMENT_REF } from '../chat-session/session-attachments.js'\nimport { attachmentKindOf } from '../chat-session/attachment-policy.js'\n\n/** The whole text is read - the check must see every line, not the part the model was shown. */\nconst MAX_CHARS = 2_000_000\n\nexport async function loadSourceTexts(ids: string[], context: any): Promise<Map<string, string>> {\n const { domain, user } = context?.state ?? {}\n const texts = new Map<string, string>()\n if (!domain?.id) return texts\n for (const id of [...new Set(ids)].slice(0, 20)) {\n const row: any = await getRepository(Attachment).findOne({ where: { id, domain: { id: domain.id }, refType: CHAT_ATTACHMENT_REF } as any })\n const session: any = row && (await getRepository(ChatSession).findOne({ where: { id: row.refBy, domain: { id: domain.id } } as any }))\n if (!row || !session) continue\n if (!mayReadSession(session.visibility, await isSessionParticipant(domain.id, session.id, user?.id))) continue\n if (attachmentKindOf({ type: row.mimetype, name: row.name }) !== 'text') continue\n try {\n texts.set(id, String(await STORAGE.readFile(row.path, 'utf8')).slice(0, MAX_CHARS))\n } catch {\n /* gone from storage - the rows citing it say they were not checked */\n }\n }\n return texts\n}\n"]}
@@ -0,0 +1,157 @@
1
+ export type EntryFieldType = 'string' | 'text' | 'number' | 'integer' | 'date' | 'boolean' | 'enum';
2
+ export interface EntryField {
3
+ name: string;
4
+ type: EntryFieldType;
5
+ required?: boolean;
6
+ /** The allowed values of an `enum` field. */
7
+ values?: string[];
8
+ /** What the model reads about the field - English, like every tool description. */
9
+ description?: string;
10
+ /** i18n key of the column heading on the card. Absent: the field name. */
11
+ labelKey?: string;
12
+ /** A number field the card sums - and compares with the total the material prints (§ totals). */
13
+ total?: boolean;
14
+ }
15
+ /** Where a row came from - which file, and where in it. Shown on the card beside the row. */
16
+ export interface EntrySource {
17
+ attachmentId?: string;
18
+ /** "row 3", "the receipt photo", "the person's message" - the model's words. */
19
+ where?: string;
20
+ }
21
+ export interface EntryIssue {
22
+ /** The field it is about. Absent: the row as a whole. */
23
+ field?: string;
24
+ /** A code the screen translates: `ai-assistant.entry.issue.<code>`, or the target's own `messageKey`. */
25
+ code: string;
26
+ messageKey?: string;
27
+ params?: Record<string, unknown>;
28
+ /** A blocking issue keeps the row out when the person presses the button. */
29
+ blocking: boolean;
30
+ }
31
+ export interface EntryRowInput {
32
+ values?: Record<string, unknown>;
33
+ sources?: EntrySource[];
34
+ }
35
+ export interface EntryRow {
36
+ index: number;
37
+ values: Record<string, unknown>;
38
+ sources: EntrySource[];
39
+ issues: EntryIssue[];
40
+ /** The line of a text source where this row's numbers and dates were all found - the server's check, not the model's word. */
41
+ evidence?: {
42
+ attachmentId: string;
43
+ line: number;
44
+ };
45
+ }
46
+ export interface EntryContext {
47
+ /** The request state - domain, user, and when writing, `tx` and `afterCommit`. */
48
+ state: any;
49
+ }
50
+ export interface EntryApplied {
51
+ /** The created record's id, when there is one. */
52
+ id?: string;
53
+ /** A short name for the conversation line - "2026-09-12 · 택시 · ₩12,400". */
54
+ label?: string;
55
+ }
56
+ /** What happened, for an application that writes down every assistant call (office's AI audit). */
57
+ export interface EntryEvent {
58
+ phase: 'propose' | 'apply';
59
+ tool: string;
60
+ rows: number;
61
+ ok: boolean;
62
+ applied?: number;
63
+ missed?: number;
64
+ error?: string;
65
+ /** propose: the rows as the model gave them; apply: the proposal key and each row's result. */
66
+ detail?: unknown;
67
+ }
68
+ export interface EntryTarget {
69
+ /** `<app>.<record>` - `office.expense-line`. */
70
+ key: string;
71
+ /** i18n key of the record's name on the card. */
72
+ labelKey: string;
73
+ /** What one row is, for the model. */
74
+ description: string;
75
+ fields: EntryField[];
76
+ /**
77
+ * The application's own mutation that enters one record, as a GraphQL document with one root field -
78
+ * `mutation ($line: NewExpenseLine!) { addExpenseLine(line: $line) { id } }`. Its root field is the door:
79
+ * the propose tool is offered only to someone who passes it, and each row is entered by running it with
80
+ * the person's request state, so `@privilege`, `@transaction` and the door's own checks apply as they do
81
+ * to a person typing it in.
82
+ */
83
+ mutation: string;
84
+ /** The mutation's variables for one row. */
85
+ variables(row: EntryRow): Record<string, unknown>;
86
+ /** What the conversation says of an entered row - its id and a short name. */
87
+ appliedOf?(data: any, row: EntryRow): EntryApplied | undefined;
88
+ /** At most this many rows in one proposal. Default 200. */
89
+ maxRows?: number;
90
+ /**
91
+ * Read-only checks the application owns - a duplicate of what is already entered, a code that does not
92
+ * exist. Asked when the rows are proposed and again when they are entered: the records may have moved.
93
+ * Returns one list per row, in order.
94
+ */
95
+ check?(rows: EntryRow[], context: EntryContext): EntryIssue[][] | Promise<EntryIssue[][]>;
96
+ /** Told of every proposal and every entering - an application that audits its assistant writes it down. A throw is ignored. */
97
+ record?(event: EntryEvent, context: EntryContext): void | Promise<void>;
98
+ }
99
+ /**
100
+ * `Mutation.<root field>` of the target's mutation - the one declaration both the tool's gate and the
101
+ * entering read. A document that is not one mutation with one root field is refused at boot.
102
+ */
103
+ export declare function entryDoorOf(mutation: string): string;
104
+ /** Tells the target, and never lets its record keeping stop the work. */
105
+ export declare function recordEntryEvent(target: EntryTarget, event: EntryEvent, context: EntryContext): Promise<void>;
106
+ export declare const DEFAULT_MAX_ROWS = 200;
107
+ /** Validates and keeps a target - `registerEntryTarget` (entry-tools.ts) also opens its tool. A malformed declaration is refused at boot, not in a conversation. */
108
+ export declare function declareEntryTarget(target: EntryTarget): void;
109
+ export declare function entryTargetOf(key: string | undefined): EntryTarget | undefined;
110
+ export declare function entryTargets(): EntryTarget[];
111
+ /** For tests. */
112
+ export declare function clearEntryTargets(): void;
113
+ /** `office.expense-line` → `proposeOfficeExpenseLineEntries` - one tool per target, so each has its own door. */
114
+ export declare function entryToolName(key: string): string;
115
+ export declare function entryCategoryName(key: string): string;
116
+ /**
117
+ * The rows as the target reads them - each value in its field's type, and what was wrong said as an issue.
118
+ *
119
+ * A value that does not fit is **kept as it was written and marked**, never dropped or guessed: the card
120
+ * shows what the material said, and the person corrects it in the conversation.
121
+ */
122
+ export declare function normalizeEntryRows(target: EntryTarget, input: unknown): {
123
+ rows: EntryRow[];
124
+ cut: number;
125
+ };
126
+ /** Adds the target's own findings to each row. A check that throws marks nothing and is reported by the caller. */
127
+ export declare function withCheckedIssues(rows: EntryRow[], found: EntryIssue[][] | undefined): EntryRow[];
128
+ export declare function isBlocked(row: EntryRow): boolean;
129
+ /** The ways a number or a date is written in a file. */
130
+ export declare function writtenForms(type: EntryFieldType, value: unknown): string[];
131
+ /**
132
+ * A form found as a whole number - "12,400" is not found in "112,400", "12,4001", "12,400.50" or "12,400,000";
133
+ * "2026-09-12" not in "2026-09-120". A CSV's own commas are not part of the number.
134
+ */
135
+ export declare function lineHas(line: string, forms: string[]): boolean;
136
+ /**
137
+ * Checks each row against the text of the files it cites. `texts` holds what could be read, by attachment id;
138
+ * an id that is not there was an image, or could not be opened.
139
+ */
140
+ export declare function verifyRowsAgainstSources(rows: EntryRow[], fields: EntryField[], texts: Map<string, string>): EntryRow[];
141
+ export interface EntryTotal {
142
+ field: string;
143
+ /** The sum over every row, and over the rows that will be entered. */
144
+ all: number;
145
+ ready: number;
146
+ /** The total the material prints, as the model read it - and whether the server found it in the file. */
147
+ declared?: number;
148
+ declaredFound?: boolean;
149
+ /** declared - all. */
150
+ difference?: number;
151
+ }
152
+ /** The sums of the fields declared `total`, and how they stand against the total the material prints. */
153
+ export declare function entryTotals(rows: EntryRow[], fields: EntryField[], declared: {
154
+ field?: string;
155
+ value?: unknown;
156
+ attachmentId?: string;
157
+ } | undefined, texts: Map<string, string>): EntryTotal[];
@@ -0,0 +1,343 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_MAX_ROWS = void 0;
4
+ exports.entryDoorOf = entryDoorOf;
5
+ exports.recordEntryEvent = recordEntryEvent;
6
+ exports.declareEntryTarget = declareEntryTarget;
7
+ exports.entryTargetOf = entryTargetOf;
8
+ exports.entryTargets = entryTargets;
9
+ exports.clearEntryTargets = clearEntryTargets;
10
+ exports.entryToolName = entryToolName;
11
+ exports.entryCategoryName = entryCategoryName;
12
+ exports.normalizeEntryRows = normalizeEntryRows;
13
+ exports.withCheckedIssues = withCheckedIssues;
14
+ exports.isBlocked = isBlocked;
15
+ exports.writtenForms = writtenForms;
16
+ exports.lineHas = lineHas;
17
+ exports.verifyRowsAgainstSources = verifyRowsAgainstSources;
18
+ exports.entryTotals = entryTotals;
19
+ /*
20
+ * Data entry from material - what an application declares so the assistant can enter its records
21
+ * (operato-application/design/ai/data-entry.md).
22
+ *
23
+ * A person hands the conversation what the records are made of - a bank export, a photo of a receipt,
24
+ * lines pasted from a mail - and the assistant turns it into rows of one of the application's records.
25
+ * Nothing is written by the model. It proposes the rows; the card shows them with what was wrong in
26
+ * each and where each came from; a correction is said in the conversation and the model proposes again;
27
+ * the person presses the button; the server enters each row **through the application's own GraphQL
28
+ * mutation**, run with the person's request state - the same door, directives and checks as entering by hand.
29
+ * There is no second way into the record.
30
+ *
31
+ * This file is pure - no framework, no database - so the rules a row passes are tested without a server.
32
+ */
33
+ const graphql_1 = require("graphql");
34
+ /**
35
+ * `Mutation.<root field>` of the target's mutation - the one declaration both the tool's gate and the
36
+ * entering read. A document that is not one mutation with one root field is refused at boot.
37
+ */
38
+ function entryDoorOf(mutation) {
39
+ const doc = (0, graphql_1.parse)(mutation);
40
+ const operations = doc.definitions.filter((one) => one.kind === 'OperationDefinition');
41
+ if (operations.length !== 1 || operations[0].operation !== 'mutation')
42
+ throw new Error('is not one mutation');
43
+ const fields = operations[0].selectionSet.selections.filter((one) => one.kind === 'Field');
44
+ if (fields.length !== 1)
45
+ throw new Error('must have exactly one root field');
46
+ return `Mutation.${fields[0].name.value}`;
47
+ }
48
+ /** Tells the target, and never lets its record keeping stop the work. */
49
+ async function recordEntryEvent(target, event, context) {
50
+ if (!target.record)
51
+ return;
52
+ try {
53
+ await target.record(event, context);
54
+ }
55
+ catch {
56
+ /* an audit that failed to write is the application's to report */
57
+ }
58
+ }
59
+ exports.DEFAULT_MAX_ROWS = 200;
60
+ const targets = new Map();
61
+ const KEY = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
62
+ /** Validates and keeps a target - `registerEntryTarget` (entry-tools.ts) also opens its tool. A malformed declaration is refused at boot, not in a conversation. */
63
+ function declareEntryTarget(target) {
64
+ if (!KEY.test(target?.key ?? ''))
65
+ throw new Error(`[ai-assistant] entry target key '${target?.key}' is not '<app>.<record>'.`);
66
+ try {
67
+ entryDoorOf(target.mutation ?? '');
68
+ }
69
+ catch (error) {
70
+ throw new Error(`[ai-assistant] entry target '${target.key}': its mutation ${error?.message ?? 'does not parse'}.`);
71
+ }
72
+ if (typeof target.variables !== 'function')
73
+ throw new Error(`[ai-assistant] entry target '${target.key}' has no variables.`);
74
+ if (!target.fields?.length)
75
+ throw new Error(`[ai-assistant] entry target '${target.key}' declares no fields.`);
76
+ const names = new Set();
77
+ for (const field of target.fields) {
78
+ if (names.has(field.name))
79
+ throw new Error(`[ai-assistant] entry target '${target.key}' declares '${field.name}' twice.`);
80
+ names.add(field.name);
81
+ if (field.type === 'enum' && !field.values?.length)
82
+ throw new Error(`[ai-assistant] entry target '${target.key}': enum field '${field.name}' lists no values.`);
83
+ }
84
+ targets.set(target.key, target);
85
+ }
86
+ function entryTargetOf(key) {
87
+ return key ? targets.get(key) : undefined;
88
+ }
89
+ function entryTargets() {
90
+ return [...targets.values()];
91
+ }
92
+ /** For tests. */
93
+ function clearEntryTargets() {
94
+ targets.clear();
95
+ }
96
+ /** `office.expense-line` → `proposeOfficeExpenseLineEntries` - one tool per target, so each has its own door. */
97
+ function entryToolName(key) {
98
+ const pascal = key
99
+ .split(/[.-]/)
100
+ .filter(Boolean)
101
+ .map(part => part[0].toUpperCase() + part.slice(1))
102
+ .join('');
103
+ return `propose${pascal}Entries`;
104
+ }
105
+ function entryCategoryName(key) {
106
+ return `data-entry:${key}`;
107
+ }
108
+ const empty = (value) => value === undefined || value === null || (typeof value === 'string' && !value.trim());
109
+ /** "12,400" · "₩12,400" · "12 400" → 12400. Only the separators people write; anything else is not a number. */
110
+ function toNumber(value) {
111
+ if (typeof value === 'number')
112
+ return Number.isFinite(value) ? value : undefined;
113
+ if (typeof value !== 'string')
114
+ return undefined;
115
+ const cleaned = value.trim().replace(/^[₩$€¥£]\s*/, '').replace(/[,\s]/g, '').replace(/원$/, '');
116
+ if (!/^-?\d+(\.\d+)?$/.test(cleaned))
117
+ return undefined;
118
+ return Number(cleaned);
119
+ }
120
+ /** A calendar date as `YYYY-MM-DD` - "2026.9.12", "2026/09/12" too. A day that does not exist is not a date. */
121
+ function toDate(value) {
122
+ if (typeof value !== 'string')
123
+ return undefined;
124
+ const match = value.trim().match(/^(\d{4})[-./](\d{1,2})[-./](\d{1,2})\.?$/);
125
+ if (!match)
126
+ return undefined;
127
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
128
+ const date = new Date(Date.UTC(year, month - 1, day));
129
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
130
+ return undefined;
131
+ return `${match[1]}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
132
+ }
133
+ function toBoolean(value) {
134
+ if (typeof value === 'boolean')
135
+ return value;
136
+ if (typeof value !== 'string')
137
+ return undefined;
138
+ const text = value.trim().toLowerCase();
139
+ if (['true', 'yes', 'y', '1'].includes(text))
140
+ return true;
141
+ if (['false', 'no', 'n', '0'].includes(text))
142
+ return false;
143
+ return undefined;
144
+ }
145
+ /**
146
+ * The rows as the target reads them - each value in its field's type, and what was wrong said as an issue.
147
+ *
148
+ * A value that does not fit is **kept as it was written and marked**, never dropped or guessed: the card
149
+ * shows what the material said, and the person corrects it in the conversation.
150
+ */
151
+ function normalizeEntryRows(target, input) {
152
+ const list = Array.isArray(input) ? input : [];
153
+ const max = target.maxRows ?? exports.DEFAULT_MAX_ROWS;
154
+ const fields = new Map(target.fields.map(field => [field.name, field]));
155
+ const rows = list.slice(0, max).map((raw, index) => {
156
+ const given = raw && typeof raw.values === 'object' && raw.values ? raw.values : {};
157
+ const values = {};
158
+ const issues = [];
159
+ for (const name of Object.keys(given)) {
160
+ if (!fields.has(name))
161
+ issues.push({ field: name, code: 'unknown-field', blocking: false });
162
+ }
163
+ for (const field of target.fields) {
164
+ const value = given[field.name];
165
+ if (empty(value)) {
166
+ if (field.required)
167
+ issues.push({ field: field.name, code: 'required', blocking: true });
168
+ continue;
169
+ }
170
+ let read;
171
+ let code = '';
172
+ switch (field.type) {
173
+ case 'number':
174
+ read = toNumber(value);
175
+ code = 'not-a-number';
176
+ break;
177
+ case 'integer':
178
+ read = toNumber(value);
179
+ if (read !== undefined && !Number.isInteger(read))
180
+ read = undefined;
181
+ code = 'not-an-integer';
182
+ break;
183
+ case 'date':
184
+ read = toDate(value);
185
+ code = 'not-a-date';
186
+ break;
187
+ case 'boolean':
188
+ read = toBoolean(value);
189
+ code = 'not-a-boolean';
190
+ break;
191
+ case 'enum':
192
+ read = field.values.includes(String(value).trim()) ? String(value).trim() : undefined;
193
+ code = 'not-in-list';
194
+ break;
195
+ default:
196
+ read = String(value).trim();
197
+ }
198
+ if (read === undefined) {
199
+ values[field.name] = value;
200
+ issues.push({ field: field.name, code, params: code === 'not-in-list' ? { values: field.values } : undefined, blocking: true });
201
+ }
202
+ else {
203
+ values[field.name] = read;
204
+ }
205
+ }
206
+ const sources = Array.isArray(raw?.sources)
207
+ ? raw.sources
208
+ .filter((one) => one && (one.attachmentId || one.where))
209
+ .map((one) => ({
210
+ ...(typeof one.attachmentId === 'string' ? { attachmentId: one.attachmentId } : {}),
211
+ ...(typeof one.where === 'string' ? { where: one.where.slice(0, 120) } : {})
212
+ }))
213
+ : [];
214
+ if (!sources.length)
215
+ issues.push({ code: 'no-source', blocking: false });
216
+ return { index, values, sources, issues };
217
+ });
218
+ return { rows, cut: Math.max(0, list.length - max) };
219
+ }
220
+ /** Adds the target's own findings to each row. A check that throws marks nothing and is reported by the caller. */
221
+ function withCheckedIssues(rows, found) {
222
+ if (!found)
223
+ return rows;
224
+ return rows.map((row, i) => (found[i]?.length ? { ...row, issues: [...row.issues, ...found[i]] } : row));
225
+ }
226
+ function isBlocked(row) {
227
+ return row.issues.some(issue => issue.blocking);
228
+ }
229
+ /* ── Checking the rows against the material (design/ai/data-entry.md §4-1) ─────────────────────────────
230
+ *
231
+ * A row cites where it came from; the model's word is not proof. For a text source the server looks: the
232
+ * row's numbers and dates must stand together on one line of the cited file. Found - the row carries that
233
+ * line as evidence. A value the file does not have is marked, unless the row also cites the person's
234
+ * message (a correction said in the conversation). A photo cannot be read here - the row says so.
235
+ * Names and descriptions are not looked for: the model tidies them, and a tidied name is not a wrong one.
236
+ */
237
+ const PERSON = /person|message|user|사용자|말/i;
238
+ /** The ways a number or a date is written in a file. */
239
+ function writtenForms(type, value) {
240
+ if (type === 'number' || type === 'integer') {
241
+ if (typeof value !== 'number' || !Number.isFinite(value))
242
+ return [];
243
+ const negative = value < 0;
244
+ const abs = Math.abs(value);
245
+ const fixed = Number.isInteger(abs) ? String(abs) : abs.toFixed(2).replace(/0+$/, '').replace(/\.$/, '');
246
+ const [int, frac] = fixed.split('.');
247
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
248
+ const forms = new Set();
249
+ for (const whole of [int, grouped]) {
250
+ forms.add(frac ? `${whole}.${frac}` : whole);
251
+ if (!frac)
252
+ forms.add(`${whole}.00`);
253
+ }
254
+ return [...forms].map(form => (negative ? `-${form}` : form));
255
+ }
256
+ if (type === 'date') {
257
+ const match = typeof value === 'string' ? value.match(/^(\d{4})-(\d{2})-(\d{2})$/) : null;
258
+ if (!match)
259
+ return [];
260
+ const [, y, m, d] = match;
261
+ const mm = String(Number(m));
262
+ const dd = String(Number(d));
263
+ return [`${y}-${m}-${d}`, `${y}.${m}.${d}`, `${y}/${m}/${d}`, `${y}${m}${d}`, `${y}.${mm}.${dd}`, `${y}/${mm}/${dd}`, `${y}-${mm}-${dd}`, `${y.slice(2)}.${m}.${d}`, `${y.slice(2)}/${m}/${d}`];
264
+ }
265
+ return [];
266
+ }
267
+ /**
268
+ * A form found as a whole number - "12,400" is not found in "112,400", "12,4001", "12,400.50" or "12,400,000";
269
+ * "2026-09-12" not in "2026-09-120". A CSV's own commas are not part of the number.
270
+ */
271
+ function lineHas(line, forms) {
272
+ const digit = (c) => !!c && c >= '0' && c <= '9';
273
+ return forms.some(form => {
274
+ for (let at = line.indexOf(form); at >= 0; at = line.indexOf(form, at + 1)) {
275
+ const before = line[at - 1];
276
+ const after = line[at + form.length];
277
+ /* A comma is also the column separator of a CSV: only a comma and three digits more continue the number. */
278
+ if (digit(before) || (before === '.' && digit(line[at - 2])))
279
+ continue;
280
+ if (digit(after) || (after === '.' && digit(line[at + form.length + 1])))
281
+ continue;
282
+ if (after === ',' && /^,\d{3}(?!\d)/.test(line.slice(at + form.length)))
283
+ continue;
284
+ return true;
285
+ }
286
+ return false;
287
+ });
288
+ }
289
+ /**
290
+ * Checks each row against the text of the files it cites. `texts` holds what could be read, by attachment id;
291
+ * an id that is not there was an image, or could not be opened.
292
+ */
293
+ function verifyRowsAgainstSources(rows, fields, texts) {
294
+ const checked = fields.filter(field => ['number', 'integer', 'date'].includes(field.type));
295
+ return rows.map(row => {
296
+ const files = row.sources.map(source => source.attachmentId).filter((id) => !!id);
297
+ if (!files.length || !checked.length)
298
+ return row;
299
+ const readable = files.filter(id => texts.has(id));
300
+ if (!readable.length)
301
+ return { ...row, issues: [...row.issues, { code: 'source-not-checked', blocking: false }] };
302
+ const forms = checked
303
+ .map(field => ({ field, forms: writtenForms(field.type, row.values[field.name]) }))
304
+ .filter(one => one.forms.length);
305
+ if (!forms.length)
306
+ return row;
307
+ for (const id of readable) {
308
+ const lines = texts.get(id).split(/\r?\n/);
309
+ const at = lines.findIndex(line => forms.every(one => lineHas(line, one.forms)));
310
+ if (at >= 0)
311
+ return { ...row, evidence: { attachmentId: id, line: at + 1 } };
312
+ }
313
+ const saidByPerson = row.sources.some(source => !source.attachmentId && PERSON.test(source.where ?? ''));
314
+ const issues = [...row.issues];
315
+ for (const one of forms) {
316
+ const anywhere = readable.some(id => texts.get(id).split(/\r?\n/).some(line => lineHas(line, one.forms)));
317
+ if (!anywhere && !saidByPerson)
318
+ issues.push({ field: one.field.name, code: 'not-in-source', blocking: false });
319
+ }
320
+ if (issues.length === row.issues.length)
321
+ issues.push({ code: 'source-scattered', blocking: false });
322
+ return { ...row, issues };
323
+ });
324
+ }
325
+ /** The sums of the fields declared `total`, and how they stand against the total the material prints. */
326
+ function entryTotals(rows, fields, declared, texts) {
327
+ return fields
328
+ .filter(field => field.total && (field.type === 'number' || field.type === 'integer'))
329
+ .map(field => {
330
+ const sum = (list) => Math.round(list.reduce((acc, row) => acc + (typeof row.values[field.name] === 'number' ? row.values[field.name] : 0), 0) * 100) / 100;
331
+ const total = { field: field.name, all: sum(rows), ready: sum(rows.filter(row => !isBlocked(row))) };
332
+ const value = declared && (declared.field ?? field.name) === field.name ? toNumber(declared.value) : undefined;
333
+ if (value !== undefined) {
334
+ total.declared = value;
335
+ total.difference = Math.round((value - total.all) * 100) / 100;
336
+ const text = declared.attachmentId ? texts.get(declared.attachmentId) : undefined;
337
+ if (text !== undefined)
338
+ total.declaredFound = text.split(/\r?\n/).some(line => lineHas(line, writtenForms(field.type, value)));
339
+ }
340
+ return total;
341
+ });
342
+ }
343
+ //# sourceMappingURL=entry-target.js.map