@things-factory/ai-assistant 10.1.79 → 10.1.81

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 (74) hide show
  1. package/client/components/assistant-chat.ts +102 -13
  2. package/client/components/assistant-dock.ts +160 -18
  3. package/client/components/assistant-mode.test.ts +16 -2
  4. package/client/components/assistant-session-manager.ts +52 -25
  5. package/client/components/assistant-session-toolbar.ts +4 -2
  6. package/client/components/chat-echo-dedup.ts +4 -0
  7. package/client/components/proposal-outcome-line.ts +36 -0
  8. package/client/components/proposal-request.test.ts +52 -0
  9. package/client/utils/assistant-navigation.test.ts +38 -0
  10. package/client/utils/assistant-navigation.ts +6 -0
  11. package/client/utils/assistant-surface.ts +21 -0
  12. package/dist-client/components/assistant-chat.d.ts +15 -0
  13. package/dist-client/components/assistant-chat.js +106 -13
  14. package/dist-client/components/assistant-chat.js.map +1 -1
  15. package/dist-client/components/assistant-dock.d.ts +13 -0
  16. package/dist-client/components/assistant-dock.js +175 -20
  17. package/dist-client/components/assistant-dock.js.map +1 -1
  18. package/dist-client/components/assistant-mode.test.js +14 -2
  19. package/dist-client/components/assistant-mode.test.js.map +1 -1
  20. package/dist-client/components/assistant-session-manager.d.ts +4 -0
  21. package/dist-client/components/assistant-session-manager.js +68 -26
  22. package/dist-client/components/assistant-session-manager.js.map +1 -1
  23. package/dist-client/components/assistant-session-toolbar.d.ts +1 -0
  24. package/dist-client/components/assistant-session-toolbar.js +8 -2
  25. package/dist-client/components/assistant-session-toolbar.js.map +1 -1
  26. package/dist-client/components/chat-echo-dedup.d.ts +2 -0
  27. package/dist-client/components/chat-echo-dedup.js +2 -0
  28. package/dist-client/components/chat-echo-dedup.js.map +1 -1
  29. package/dist-client/components/proposal-outcome-line.d.ts +29 -0
  30. package/dist-client/components/proposal-outcome-line.js +15 -0
  31. package/dist-client/components/proposal-outcome-line.js.map +1 -1
  32. package/dist-client/components/proposal-request.test.d.ts +1 -0
  33. package/dist-client/components/proposal-request.test.js +45 -0
  34. package/dist-client/components/proposal-request.test.js.map +1 -0
  35. package/dist-client/tsconfig.tsbuildinfo +1 -1
  36. package/dist-client/utils/assistant-navigation.d.ts +6 -0
  37. package/dist-client/utils/assistant-navigation.js +9 -0
  38. package/dist-client/utils/assistant-navigation.js.map +1 -0
  39. package/dist-client/utils/assistant-navigation.test.d.ts +1 -0
  40. package/dist-client/utils/assistant-navigation.test.js +37 -0
  41. package/dist-client/utils/assistant-navigation.test.js.map +1 -0
  42. package/dist-client/utils/assistant-surface.d.ts +19 -0
  43. package/dist-client/utils/assistant-surface.js.map +1 -1
  44. package/dist-server/service/assistant-chat-resolver.js +1 -0
  45. package/dist-server/service/assistant-chat-resolver.js.map +1 -1
  46. package/dist-server/service/chat-message/chat-message.d.ts +10 -0
  47. package/dist-server/service/chat-message/chat-message.js +29 -0
  48. package/dist-server/service/chat-message/chat-message.js.map +1 -1
  49. package/dist-server/service/chat-message/proposal-outcome.d.ts +8 -0
  50. package/dist-server/service/chat-message/proposal-outcome.js +35 -1
  51. package/dist-server/service/chat-message/proposal-outcome.js.map +1 -1
  52. package/dist-server/service/chat-session/session-inbox.d.ts +7 -0
  53. package/dist-server/service/chat-session/session-inbox.js +7 -0
  54. package/dist-server/service/chat-session/session-inbox.js.map +1 -1
  55. package/dist-server/service/chat-session-resolver.d.ts +1 -0
  56. package/dist-server/service/chat-session-resolver.js +63 -9
  57. package/dist-server/service/chat-session-resolver.js.map +1 -1
  58. package/dist-server/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +3 -3
  60. package/server/service/assistant-chat-resolver.ts +1 -0
  61. package/server/service/chat-message/chat-message.ts +32 -0
  62. package/server/service/chat-message/proposal-outcome.test.ts +53 -2
  63. package/server/service/chat-message/proposal-outcome.ts +33 -0
  64. package/server/service/chat-session/session-inbox.ts +7 -0
  65. package/server/service/chat-session-resolver.ts +71 -12
  66. package/test/assistant-dock.test.ts +8 -3
  67. package/test/assistant-session-toolbar.test.ts +7 -1
  68. package/test/open-doors.test.ts +2 -1
  69. package/test/session-discovery.test.ts +42 -0
  70. package/translations/en.json +26 -1
  71. package/translations/ja.json +26 -1
  72. package/translations/ko.json +26 -1
  73. package/translations/ms.json +26 -1
  74. package/translations/zh.json +26 -1
@@ -0,0 +1,6 @@
1
+ /** Screen changes offer a new subject; identity changes must never carry the old conversation. */
2
+ export declare function surfaceTransition(input: {
3
+ identityChanged: boolean;
4
+ sameSubject: boolean;
5
+ active: boolean;
6
+ }): 'reset' | 'refresh' | 'offer' | 'follow';
@@ -0,0 +1,9 @@
1
+ /** Screen changes offer a new subject; identity changes must never carry the old conversation. */
2
+ export function surfaceTransition(input) {
3
+ if (input.identityChanged)
4
+ return 'reset';
5
+ if (input.sameSubject)
6
+ return 'refresh';
7
+ return input.active ? 'offer' : 'follow';
8
+ }
9
+ //# sourceMappingURL=assistant-navigation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-navigation.js","sourceRoot":"","sources":["../../client/utils/assistant-navigation.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,MAAM,UAAU,iBAAiB,CAAC,KAA0E;IAC1G,IAAI,KAAK,CAAC,eAAe;QAAE,OAAO,OAAO,CAAA;IACzC,IAAI,KAAK,CAAC,WAAW;QAAE,OAAO,SAAS,CAAA;IACvC,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAA;AAC1C,CAAC","sourcesContent":["/** Screen changes offer a new subject; identity changes must never carry the old conversation. */\nexport function surfaceTransition(input: { identityChanged: boolean; sameSubject: boolean; active: boolean }): 'reset' | 'refresh' | 'offer' | 'follow' {\n if (input.identityChanged) return 'reset'\n if (input.sameSubject) return 'refresh'\n return input.active ? 'offer' : 'follow'\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import { surfaceTransition } from './assistant-navigation.js';
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ describe('a screen offers context without taking over an active conversation', () => {
5
+ test.each([false, true])('a different identity resets even when active=%s', active => {
6
+ for (const sameSubject of [false, true]) {
7
+ expect(surfaceTransition({ identityChanged: true, sameSubject, active })).toBe('reset');
8
+ }
9
+ });
10
+ test('an empty conversation follows the screen', () => {
11
+ expect(surfaceTransition({ identityChanged: false, sameSubject: false, active: false })).toBe('follow');
12
+ });
13
+ test('an existing conversation, draft or ongoing response offers a switch', () => {
14
+ expect(surfaceTransition({ identityChanged: false, sameSubject: false, active: true })).toBe('offer');
15
+ });
16
+ test('returning to the same subject refreshes without reopening', () => {
17
+ expect(surfaceTransition({ identityChanged: false, sameSubject: true, active: true })).toBe('refresh');
18
+ });
19
+ });
20
+ describe('navigation wiring', () => {
21
+ const dock = readFileSync(join(__dirname, '../components/assistant-dock.ts'), 'utf8');
22
+ test('history hides rather than unmounts the chat and its unsent input', () => {
23
+ expect(dock).toContain('?hidden=${this.showingHistory}');
24
+ expect(dock).toContain('ready && !this.loading && !this.failure');
25
+ });
26
+ test('identity changes clear a carried ask and reread capability', () => {
27
+ expect(dock).toContain("if (transition === 'reset')");
28
+ expect(dock).toContain('this.asking = undefined');
29
+ expect(dock).toContain("this.capability = 'unknown'");
30
+ });
31
+ test('all direct board actions check the current screen, not the retained editor', () => {
32
+ expect(dock).toContain('if (!this.mayApplyOnScreen()) return');
33
+ expect(dock.match(/if \(this.mayApplyOnScreen\(\)\)/g)).toHaveLength(2);
34
+ expect(dock).toContain("errorCode: 'conversation-screen-changed'");
35
+ });
36
+ });
37
+ //# sourceMappingURL=assistant-navigation.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-navigation.test.js","sourceRoot":"","sources":["../../client/utils/assistant-navigation.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,W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AE,MAAM,CAAC,CAAA;IACrF,IAAI,CAAC,kEAAkE,EAAE,GAAG,EAAE;QAC5E,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,gCAAgC,CAAC,CAAA;QACxD,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,yCAAyC,CAAC,CAAA;IACnE,CAAC,CAAC,CAAA;IACF,IAAI,CAAC,4DAA4D,EAAE,GAAG,EAAE;QACtE,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,6BAA6B,CAAC,CAAA;QACrD,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,yBAAyB,CAAC,CAAA;QACjD,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,6BAA6B,CAAC,CAAA;IACvD,CAAC,CAAC,CAAA;IACF,IAAI,CAAC,4EAA4E,EAAE,GAAG,EAAE;QACtF,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,sCAAsC,CAAC,CAAA;QAC9D,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,mCAAmC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QACvE,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,0CAA0C,CAAC,CAAA;IACpE,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["import { surfaceTransition } from './assistant-navigation.js'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\ndescribe('a screen offers context without taking over an active conversation', () => {\n test.each([false, true])('a different identity resets even when active=%s', active => {\n for (const sameSubject of [false, true]) {\n expect(surfaceTransition({ identityChanged: true, sameSubject, active })).toBe('reset')\n }\n })\n test('an empty conversation follows the screen', () => {\n expect(surfaceTransition({ identityChanged: false, sameSubject: false, active: false })).toBe('follow')\n })\n test('an existing conversation, draft or ongoing response offers a switch', () => {\n expect(surfaceTransition({ identityChanged: false, sameSubject: false, active: true })).toBe('offer')\n })\n test('returning to the same subject refreshes without reopening', () => {\n expect(surfaceTransition({ identityChanged: false, sameSubject: true, active: true })).toBe('refresh')\n })\n})\n\ndescribe('navigation wiring', () => {\n const dock = readFileSync(join(__dirname, '../components/assistant-dock.ts'), 'utf8')\n test('history hides rather than unmounts the chat and its unsent input', () => {\n expect(dock).toContain('?hidden=${this.showingHistory}')\n expect(dock).toContain('ready && !this.loading && !this.failure')\n })\n test('identity changes clear a carried ask and reread capability', () => {\n expect(dock).toContain(\"if (transition === 'reset')\")\n expect(dock).toContain('this.asking = undefined')\n expect(dock).toContain(\"this.capability = 'unknown'\")\n })\n test('all direct board actions check the current screen, not the retained editor', () => {\n expect(dock).toContain('if (!this.mayApplyOnScreen()) return')\n expect(dock.match(/if \\(this.mayApplyOnScreen\\(\\)\\)/g)).toHaveLength(2)\n expect(dock).toContain(\"errorCode: 'conversation-screen-changed'\")\n })\n})\n"]}
@@ -1,3 +1,4 @@
1
+ import type { ProposalOutcome } from './assistant-proposals.js';
1
2
  /** The row a conversation hangs on - its session anchor (ADR-0072 decision 6). */
2
3
  export interface AssistantAnchor {
3
4
  anchorType: string;
@@ -9,6 +10,15 @@ export interface AssistantStuck {
9
10
  message: string;
10
11
  }
11
12
  export type AnchorResult = AssistantAnchor | AssistantStuck;
13
+ /** A route the person can take from a surface when the next useful action lives in the app. */
14
+ export interface AssistantSurfaceNextStep {
15
+ /** The small, concrete action shown below the dock header. */
16
+ label(): string;
17
+ /** A route inside the current application. */
18
+ href: string;
19
+ /** Why this is the useful next action, in the person's words. */
20
+ description?(): string;
21
+ }
12
22
  export declare function isAnchor(result: AnchorResult | undefined): result is AssistantAnchor;
13
23
  /** For a surface that authors a board - the chat gets the board, the dock applies its patches. */
14
24
  export interface BoardSurface {
@@ -44,11 +54,20 @@ export interface AssistantSurface {
44
54
  label(): string;
45
55
  detail?(): string;
46
56
  icon?: string;
57
+ /** An app-owned route that helps the person make this surface useful (for example, create the first Twin). */
58
+ nextStep?: AssistantSurfaceNextStep;
47
59
  /** Read at the moment of sending - never cached, so a draft cannot go stale. */
48
60
  hostContext?(): Record<string, unknown>;
49
61
  board?: BoardSurface;
50
62
  /** The dock opened another conversation for this surface - e.g. the board modeller records its direct edits under it. */
51
63
  sessionChanged?(sessionId: string): void;
64
+ /**
65
+ * What became of a proposal whose outcome never reached the conversation (ADR-0097 Q-D4 ④) - asked by
66
+ * "check result", never to run it again. Answer from the host's own record, keyed by the proposal's key.
67
+ * `undefined` when the host cannot tell (not saved, undone, never applied): the card stays "no answer
68
+ * received" - an unknown result is not a refusal.
69
+ */
70
+ proposalOutcome?(proposalKey: string, proposal: any): Promise<ProposalOutcome | undefined> | ProposalOutcome | undefined;
52
71
  }
53
72
  type Listener = () => void;
54
73
  /** An editor with a draft says it is on screen. The last one provided wins until it is cleared. */
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-surface.js","sourceRoot":"","sources":["../../client/utils/assistant-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAA;AAgBtC,MAAM,UAAU,QAAQ,CAAC,MAAgC;IACvD,OAAO,CAAC,CAAC,MAAM,IAAI,UAAU,IAAI,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAA;AAC9D,CAAC;AAsCD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA4B,CAAA;AACpD,IAAI,SAA6B,CAAA;AACjC,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwE,CAAA;AACrG,IAAI,IAAkC,CAAA;AACtC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAY,CAAA;AAErC,SAAS,OAAO;IACd,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QAC3B,IAAI,CAAC;YACH,QAAQ,EAAE,CAAA;QACZ,CAAC;QAAC,MAAM,CAAC;YACP,mDAAmD;QACrD,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,uBAAuB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ells the AI dock (design/ai/shared-dock.md §3).\n *\n * Before this there were five ways: `context.subject` (warehouse), `BoardEditHost` (twin), `StationAITarget`\n * (plant), window events (figure) and the board modeller's own panel. The dock now reads one answer:\n *\n * 1. an editor that holds a draft provides a surface provideAssistantSurface(owner, surface)\n * 2. a page that shows one thing says so in its context get context() { return { subject: { type, id } } }\n * and the app says once how such a subject becomes a surface registerSubjectSurface(type, make)\n * 3. otherwise the app's home registerAssistantHome(surface)\n *\n * The first that answers wins. The dock follows changes through `subscribeAssistantSurface`.\n */\nimport { store } from '@operato/shell'\n\n/** The row a conversation hangs on - its session anchor (ADR-0072 decision 6). */\nexport interface AssistantAnchor {\n anchorType: string\n anchorId: string\n}\n\n/** No anchor could stand - said to the person as a fact and what to do. */\nexport interface AssistantStuck {\n stuck: string\n message: string\n}\n\nexport type AnchorResult = AssistantAnchor | AssistantStuck\n\nexport function isAnchor(result: AnchorResult | undefined): result is AssistantAnchor {\n return !!result && 'anchorId' in result && !!result.anchorId\n}\n\n/** For a surface that authors a board - the chat gets the board, the dock applies its patches. */\nexport interface BoardSurface {\n currentBoard?: () => any\n boardProvider?: () => any\n selectedRefids?: () => number[]\n knownTypes?: () => string[]\n categories?: () => any[]\n componentSchemas?: () => any\n searchProvider?: (query: string) => any[]\n applyPatch(detail: any): Promise<{ applied: number; missed: number; note?: string }> | { applied: number; missed: number; note?: string }\n revertPatch?(patchId: string): Promise<void> | void\n applyAction?(detail: any): Promise<void> | void\n /** The chat door for board authoring, until board-ai joins the neutral door (ADR-0061 decision 0-1). */\n chatEndpoint?: 'boardAIChat' | 'assistantChat'\n}\n\nexport interface AssistantSurface {\n /** Identity - a different key is a different conversation. */\n key: string\n /** Matched against the server's mode `subjects` (assistantModes(subject)). */\n subject: string\n /** The session anchor, or why none could stand. May ask the server (a row uuid, a domain id). */\n anchor(): Promise<AnchorResult> | AnchorResult\n /** Words for the header - never a raw identifier. */\n label(): string\n detail?(): string\n icon?: string\n /** Read at the moment of sending - never cached, so a draft cannot go stale. */\n hostContext?(): Record<string, unknown>\n board?: BoardSurface\n /** The dock opened another conversation for this surface - e.g. the board modeller records its direct edits under it. */\n sessionChanged?(sessionId: string): void\n}\n\ntype Listener = () => void\n\nconst provided = new Map<object, AssistantSurface>()\nlet lastOwner: object | undefined\nconst subjectMakers = new Map<string, (subject: { type: string; id?: string }) => AssistantSurface>()\nlet home: AssistantSurface | undefined\nconst listeners = new Set<Listener>()\n\nfunction changed() {\n listeners.forEach(listener => {\n try {\n listener()\n } catch {\n /* one listener's error does not stop the others */\n }\n })\n}\n\n/** An editor with a draft says it is on screen. The last one provided wins until it is cleared. */\nexport function provideAssistantSurface(owner: object, surface: AssistantSurface): void {\n provided.set(owner, surface)\n lastOwner = owner\n changed()\n}\n\n/** The editor is gone or inactive. A later provider that replaced it is left alone. */\nexport function clearAssistantSurface(owner: object): void {\n if (!provided.delete(owner)) return\n if (lastOwner === owner) lastOwner = [...provided.keys()].pop()\n changed()\n}\n\n/** The editor's draft or identity changed - the dock reads it again. */\nexport function notifyAssistantSurface(owner: object): void {\n if (provided.has(owner)) changed()\n}\n\n/** How a page's `context.subject` of this type becomes a surface - declared once by the app. */\nexport function registerSubjectSurface(type: string, make: (subject: { type: string; id?: string }) => AssistantSurface): void {\n subjectMakers.set(type, make)\n changed()\n}\n\n/** The app's own conversation when the screen shows nothing in particular - a factory, a site, a catalog. */\nexport function registerAssistantHome(surface: AssistantSurface): void {\n home = surface\n changed()\n}\n\nexport function subscribeAssistantSurface(listener: Listener): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nlet pageSubjectKey = ''\nlet pageSurface: AssistantSurface | undefined\n\nfunction surfaceFromPage(): AssistantSurface | undefined {\n const subject = (store.getState() as any)?.route?.context?.subject\n const type = subject?.type\n const make = type ? subjectMakers.get(type) : undefined\n if (!make) return undefined\n const key = JSON.stringify([type, subject?.id ?? ''])\n if (key !== pageSubjectKey) {\n pageSubjectKey = key\n pageSurface = make({ type, id: subject?.id })\n }\n return pageSurface\n}\n\n/** What the dock talks about now: a provided editor, else the page's subject, else the app's home. */\nexport function currentAssistantSurface(): AssistantSurface | undefined {\n return (lastOwner && provided.get(lastOwner)) || surfaceFromPage() || home\n}\n\n/** The app's home surface - for the header's \"back to the app's conversation\". */\nexport function assistantHomeSurface(): AssistantSurface | undefined {\n return home\n}\n\n/* The page context lives in the store; a page change is a surface change. */\nlet lastRouteSubject = ''\nstore.subscribe(() => {\n const subject = (store.getState() as any)?.route?.context?.subject\n const key = JSON.stringify([subject?.type ?? '', subject?.id ?? ''])\n if (key !== lastRouteSubject) {\n lastRouteSubject = key\n changed()\n }\n})\n"]}
1
+ {"version":3,"file":"assistant-surface.js","sourceRoot":"","sources":["../../client/utils/assistant-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAA;AA4BtC,MAAM,UAAU,QAAQ,CAAC,MAAgC;IACvD,OAAO,CAAC,CAAC,MAAM,IAAI,UAAU,IAAI,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAA;AAC9D,CAAC;AA+CD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA4B,CAAA;AACpD,IAAI,SAA6B,CAAA;AACjC,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwE,CAAA;AACrG,IAAI,IAAkC,CAAA;AACtC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAY,CAAA;AAErC,SAAS,OAAO;IACd,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QAC3B,IAAI,CAAC;YACH,QAAQ,EAAE,CAAA;QACZ,CAAC;QAAC,MAAM,CAAC;YACP,mDAAmD;QACrD,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,uBAAuB,CAAC,KAAa,EAAE,OAAyB;IAC9E,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;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,CAAC,CAAC,CAAC,SAAS,CAAA;IACvD,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAA;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACrD,IAAI,GAAG,KAAK,cAAc,EAAE,CAAC;QAC3B,cAAc,GAAG,GAAG,CAAA;QACpB,WAAW,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAA;IAC/C,CAAC;IACD,OAAO,WAAW,CAAA;AACpB,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,uBAAuB;IACrC,OAAO,CAAC,SAAS,IAAI,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,eAAe,EAAE,IAAI,IAAI,CAAA;AAC5E,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,oBAAoB;IAClC,OAAO,IAAI,CAAA;AACb,CAAC;AAED,6EAA6E;AAC7E,IAAI,gBAAgB,GAAG,EAAE,CAAA;AACzB,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;IACnB,MAAM,OAAO,GAAI,KAAK,CAAC,QAAQ,EAAU,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAA;IAClE,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,IAAI,IAAI,EAAE,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACpE,IAAI,GAAG,KAAK,gBAAgB,EAAE,CAAC;QAC7B,gBAAgB,GAAG,GAAG,CAAA;QACtB,OAAO,EAAE,CAAA;IACX,CAAC;AACH,CAAC,CAAC,CAAA","sourcesContent":["/*\n * What the screen shows - the one way a screen tells the AI dock (design/ai/shared-dock.md §3).\n *\n * Before this there were five ways: `context.subject` (warehouse), `BoardEditHost` (twin), `StationAITarget`\n * (plant), window events (figure) and the board modeller's own panel. The dock now reads one answer:\n *\n * 1. an editor that holds a draft provides a surface provideAssistantSurface(owner, surface)\n * 2. a page that shows one thing says so in its context get context() { return { subject: { type, id } } }\n * and the app says once how such a subject becomes a surface registerSubjectSurface(type, make)\n * 3. otherwise the app's home registerAssistantHome(surface)\n *\n * The first that answers wins. The dock follows changes through `subscribeAssistantSurface`.\n */\nimport { store } from '@operato/shell'\n\nimport type { ProposalOutcome } from './assistant-proposals.js'\n\n/** The row a conversation hangs on - its session anchor (ADR-0072 decision 6). */\nexport interface AssistantAnchor {\n anchorType: string\n anchorId: string\n}\n\n/** No anchor could stand - said to the person as a fact and what to do. */\nexport interface AssistantStuck {\n stuck: string\n message: string\n}\n\nexport type AnchorResult = AssistantAnchor | AssistantStuck\n\n/** A route the person can take from a surface when the next useful action lives in the app. */\nexport interface AssistantSurfaceNextStep {\n /** The small, concrete action shown below the dock header. */\n label(): string\n /** A route inside the current application. */\n href: string\n /** Why this is the useful next action, in the person's words. */\n description?(): string\n}\n\nexport function isAnchor(result: AnchorResult | undefined): result is AssistantAnchor {\n return !!result && 'anchorId' in result && !!result.anchorId\n}\n\n/** For a surface that authors a board - the chat gets the board, the dock applies its patches. */\nexport interface BoardSurface {\n currentBoard?: () => any\n boardProvider?: () => any\n selectedRefids?: () => number[]\n knownTypes?: () => string[]\n categories?: () => any[]\n componentSchemas?: () => any\n searchProvider?: (query: string) => any[]\n applyPatch(detail: any): Promise<{ applied: number; missed: number; note?: string }> | { applied: number; missed: number; note?: string }\n revertPatch?(patchId: string): Promise<void> | void\n applyAction?(detail: any): Promise<void> | void\n /** The chat door for board authoring, until board-ai joins the neutral door (ADR-0061 decision 0-1). */\n chatEndpoint?: 'boardAIChat' | 'assistantChat'\n}\n\nexport interface AssistantSurface {\n /** Identity - a different key is a different conversation. */\n key: string\n /** Matched against the server's mode `subjects` (assistantModes(subject)). */\n subject: string\n /** The session anchor, or why none could stand. May ask the server (a row uuid, a domain id). */\n anchor(): Promise<AnchorResult> | AnchorResult\n /** Words for the header - never a raw identifier. */\n label(): string\n detail?(): string\n icon?: string\n /** An app-owned route that helps the person make this surface useful (for example, create the first Twin). */\n nextStep?: AssistantSurfaceNextStep\n /** Read at the moment of sending - never cached, so a draft cannot go stale. */\n hostContext?(): Record<string, unknown>\n board?: BoardSurface\n /** The dock opened another conversation for this surface - e.g. the board modeller records its direct edits under it. */\n sessionChanged?(sessionId: string): void\n /**\n * What became of a proposal whose outcome never reached the conversation (ADR-0097 Q-D4 ④) - asked by\n * \"check result\", never to run it again. Answer from the host's own record, keyed by the proposal's key.\n * `undefined` when the host cannot tell (not saved, undone, never applied): the card stays \"no answer\n * received\" - an unknown result is not a refusal.\n */\n proposalOutcome?(proposalKey: string, proposal: any): Promise<ProposalOutcome | undefined> | ProposalOutcome | undefined\n}\n\ntype Listener = () => void\n\nconst provided = new Map<object, AssistantSurface>()\nlet lastOwner: object | undefined\nconst subjectMakers = new Map<string, (subject: { type: string; id?: string }) => AssistantSurface>()\nlet home: AssistantSurface | undefined\nconst listeners = new Set<Listener>()\n\nfunction changed() {\n listeners.forEach(listener => {\n try {\n listener()\n } catch {\n /* one listener's error does not stop the others */\n }\n })\n}\n\n/** An editor with a draft says it is on screen. The last one provided wins until it is cleared. */\nexport function provideAssistantSurface(owner: object, surface: AssistantSurface): void {\n provided.set(owner, surface)\n lastOwner = owner\n changed()\n}\n\n/** The editor is gone or inactive. A later provider that replaced it is left alone. */\nexport function clearAssistantSurface(owner: object): void {\n if (!provided.delete(owner)) return\n if (lastOwner === owner) lastOwner = [...provided.keys()].pop()\n changed()\n}\n\n/** The editor's draft or identity changed - the dock reads it again. */\nexport function notifyAssistantSurface(owner: object): void {\n if (provided.has(owner)) changed()\n}\n\n/** How a page's `context.subject` of this type becomes a surface - declared once by the app. */\nexport function registerSubjectSurface(type: string, make: (subject: { type: string; id?: string }) => AssistantSurface): void {\n subjectMakers.set(type, make)\n changed()\n}\n\n/** The app's own conversation when the screen shows nothing in particular - a factory, a site, a catalog. */\nexport function registerAssistantHome(surface: AssistantSurface): void {\n home = surface\n changed()\n}\n\nexport function subscribeAssistantSurface(listener: Listener): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nlet pageSubjectKey = ''\nlet pageSurface: AssistantSurface | undefined\n\nfunction surfaceFromPage(): AssistantSurface | undefined {\n const subject = (store.getState() as any)?.route?.context?.subject\n const type = subject?.type\n const make = type ? subjectMakers.get(type) : undefined\n if (!make) return undefined\n const key = JSON.stringify([type, subject?.id ?? ''])\n if (key !== pageSubjectKey) {\n pageSubjectKey = key\n pageSurface = make({ type, id: subject?.id })\n }\n return pageSurface\n}\n\n/** What the dock talks about now: a provided editor, else the page's subject, else the app's home. */\nexport function currentAssistantSurface(): AssistantSurface | undefined {\n return (lastOwner && provided.get(lastOwner)) || surfaceFromPage() || home\n}\n\n/** The app's home surface - for the header's \"back to the app's conversation\". */\nexport function assistantHomeSurface(): AssistantSurface | undefined {\n return home\n}\n\n/* The page context lives in the store; a page change is a surface change. */\nlet lastRouteSubject = ''\nstore.subscribe(() => {\n const subject = (store.getState() as any)?.route?.context?.subject\n const key = JSON.stringify([subject?.type ?? '', subject?.id ?? ''])\n if (key !== lastRouteSubject) {\n lastRouteSubject = key\n changed()\n }\n})\n"]}
@@ -496,6 +496,7 @@ let AssistantChatResolver = class AssistantChatResolver {
496
496
  */
497
497
  doors: answerDoors,
498
498
  toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,
499
+ proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,
499
500
  groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,
500
501
  creator: user,
501
502
  updater: user,
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-chat-resolver.js","sourceRoot":"","sources":["../../server/service/assistant-chat-resolver.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,+CAAoG;AAC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,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI;YACvE,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI;YACrF,aAAa,EAAE,aAAa,IAAI,IAAI;SACrC,CAAA;IACH,CAAC;CACF,CAAA;AA9XY,sDAAqB;AAiB1B;IAVL,IAAA,uBAAQ,EAAC,GAAG,EAAE,CAAC,mBAAmB,EAAE;QACnC,WAAW,EACT,0JAA0J;KAC7J,CAAC;IACF;;;;OAIG;;IACF,IAAA,wBAAS,EAAC,uFAAuF,CAAC;IAC9E,mBAAA,IAAA,kBAAG,EAAC,OAAO,CAAC,CAAA;IAA6B,mBAAA,IAAA,kBAAG,GAAE,CAAA;;6CAA1B,kBAAkB;;0DA4W1D;gCA7XU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CA8XjC","sourcesContent":["/*\n * The neutral door into a conversation.\n *\n * ── Why this exists (2026-09-11) ───────────────────────────────────────────────\n * The chat component moved here from `board-ai`, but the only mutation it could call stayed\n * behind. operato-figure mounted the dock, registered four tools, and got\n * `Cannot query field \"boardAIChat\" on type \"Mutation\"` — it does not load board-ai. The twin has\n * the same shape and it does not show: its space deliberation runs through board-ai's door purely\n * because the board authoring half of the same product already loaded that package.\n *\n * ── Why the board resolver was not moved ───────────────────────────────────────\n * `board-ai-resolver.ts` is 692 lines and the larger part of it is board authoring itself:\n * `currentBoard` as a BoardModel, PatchEntry, board patch broadcasts, refid injection for\n * component mentions. Moving that here would teach this package the board document, which is the\n * dependency we just cut, pointing the other way.\n *\n * So the door moved and the editor did not. `boardAIChat` stays in board-ai for board authoring;\n * this one is for a surface that asks questions and runs registered tools.\n *\n * ── What this is not ───────────────────────────────────────────────────────────\n * It has no document, so it takes no document and returns no patch. Tools that write to a\n * document are not offered here — `registryAssistantChat` enforces that, and it decides what may\n * be dispatched from the same list it offers, so the two cannot drift apart.\n */\nimport { Arg, Ctx, Directive, Field, InputType, Mutation, ObjectType, Resolver } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\nimport '@things-factory/auth-base'\n\nimport { config } from '@things-factory/env'\nimport { getRepository } from '@things-factory/shell'\nimport {\n createAIClient,\n findToolSpec,\n getDefaultAIClient,\n registryAssistantChat,\n type AIClient\n} from '@things-factory/ai-client-base'\n\nimport { ChatSession } from './chat-session/chat-session.js'\nimport { assertStationSession } from './chat-session/station-session-guard.js'\nimport { ChatMessage } from './chat-message/chat-message.js'\nimport { buildLlmHistory } from './chat-message/llm-history.js'\nimport { splitByCap } from './chat-message/history-summary.js'\nimport { foldSessionHistory } from './chat-message/fold-session-history.js'\nimport { groundingSourcesFor } from './grounding-sources.js'\nimport { publishChatMessage } from './chat-message/chat-message-publish.js'\nimport { publishSessionActivity } from './chat-session/session-activity-publish.js'\nimport { activityPatch, autoSessionName } from './chat-session/session-inbox.js'\nimport { toolAccessFor } from './tool-access.js'\nimport { ChatSessionParticipant } from './chat-session-participant/chat-session-participant.js'\nimport { doorsForAnswer } from './chat-message/message-doors.js'\nimport { judgeSessionKind } from './chat-session/session-kind.js'\nimport { readerGate } from './chat-message/reader-gate.js'\nimport { inviteMentionedUsers } from './chat-session-participant/mention-invite.js'\nimport { buildInviteNotification } from './chat-session-participant/invite-notification.js'\nimport { isSessionParticipant } from './chat-session-participant/participant-lookup.js'\nimport { assertMayWriteSession } from './chat-session/session-write-gate.js'\nimport { attachmentHistoryLine, refuseAttachments } from './chat-session/attachment-policy.js'\nimport { attachmentForModel, describeAttachment, findChatAttachment } from './chat-session/session-attachments.js'\nimport { getAssistantMode } from './assistant-mode/registry.js'\nimport { resolveModeSettings } from './assistant-mode/resolve.js'\nimport { requestTranslator } from './request-translator.js'\n\n/**\n * How many stored messages reach the model.\n *\n * A deliberation runs for days. Without a cap the prompt grows without bound and the oldest turns\n * bury the recent ones. Kept the same as the board conversation's cap so the two surfaces of one\n * product do not remember differently.\n */\nconst LLM_HISTORY_MAX_TURNS = 40\n\n@InputType()\nclass AssistantMessageInput {\n @Field({ description: \"Role: 'user' or 'assistant'\" })\n role: string\n\n @Field({ description: 'Message content' })\n content: string\n}\n\n@InputType({ description: 'Which conversation this is, and what it is about.' })\nclass AssistantModeInput {\n @Field({ description: 'A mode kind the app server registered — `<app>.<surface>`, e.g. \"twin.space\".' })\n kind: string\n\n @Field({\n nullable: true,\n description:\n 'What this conversation is about — the space, the station, the model being edited. With `kind` it is the conversation\\'s lifetime: when either changes the screen closes the conversation and starts another.'\n })\n target?: string\n}\n\n@InputType({ description: 'One turn of a conversation that has no document of its own.' })\nclass AssistantChatInput {\n @Field({\n nullable: true,\n description: 'ChatSession id. Omit for a one-off question with no persistence.'\n })\n sessionId?: string\n\n @Field(() => [AssistantMessageInput], {\n description:\n 'Conversation, newest last. For a persisted session only the last user message is appended; the rest is read from storage.'\n })\n messages: AssistantMessageInput[]\n\n @Field(() => AssistantModeInput, {\n description:\n 'Which conversation this is. The persona, the tool categories, the model and the limits come from the mode the app server registered (ADR-0061 decision 7) — a caller choosing its own tool categories would be a caller choosing its own authority.'\n })\n mode: AssistantModeInput\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'What this surface is looking at (e.g. { figureId } while modelling). Tools read it so the model never has to ask the user for identifiers. Client-supplied — never used for authorization; a tool verifies the scope belongs to the caller tenant.'\n })\n hostContext?: any\n\n @Field({\n nullable: true,\n description:\n 'Last message to keep from the stored history. The client keeps its own truncation when a user edits a message, so pass the last kept id to hide the retracted span from the model.'\n })\n truncateAfterMessageId?: string\n\n @Field(() => [String], {\n nullable: true,\n description: 'Files stored with this conversation by attachToConversation, sent with this turn.'\n })\n attachmentIds?: string[]\n\n}\n\n@ObjectType()\nclass AssistantChatOutput {\n @Field({ description: 'The reply, including the notice when the loop stopped early.' })\n reply: string\n\n @Field({ description: 'AI client identifier (provider:model).' })\n clientId: string\n\n @Field({ nullable: true, description: 'Echo of the session id, when persisted.' })\n sessionId?: string\n\n @Field({ nullable: true, description: 'Stored ChatMessage id of the user input.' })\n userMessageId?: string\n\n @Field({ nullable: true, description: 'Stored ChatMessage id of the reply.' })\n assistantMessageId?: string\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Set when this turn did not fit: { omitted, summarized } — how many earlier messages the model did not see, and whether a summary stood in for them. Without it the person watches the conversation lose its beginning in silence, while the model is told.'\n })\n historyFolded?: any\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Tool usages during the turn — {name, arguments, result, kind}. The surface shows them foldably.'\n })\n toolUsages?: any\n\n @Field(() => [String], {\n nullable: true,\n description:\n 'Tool names offered to the model this turn. A surface that expected a category and sees it missing here knows the registration did not happen, rather than reading a vague answer as a refusal.'\n })\n offeredTools?: string[]\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Actions a tool recorded without executing — each carries what the tool returned alongside `proposed: true`. The surface renders a confirm button; executing is the user\\'s act.'\n })\n proposals?: any\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Identifiers in the reply that appear in nothing the model received. Hallucination candidates surfaced to the user; the reply itself is not altered. Null when the answer is grounded.'\n })\n groundingWarnings?: any\n}\n\nfunction resolveAIClient(): AIClient | undefined {\n const existing = getDefaultAIClient()\n if (existing) return existing\n const cfg = config.get('aiClient', null) as any\n if (cfg && cfg.provider) return createAIClient(cfg)\n return undefined\n}\n\n@Resolver()\nexport class AssistantChatResolver {\n /*\n * No `@transaction`, for the same reason the board conversation has none: a model call takes\n * seconds to tens of seconds, and holding a write lock for that long collides with everything\n * else on SQLite. Writes are short and around the call. For a conversation, a partly stored\n * history is safer than a lost one.\n */\n @Mutation(() => AssistantChatOutput, {\n description:\n 'Ask the assistant a question on a surface that has no document of its own. Tools come from the registry; with a sessionId the conversation is persisted.'\n })\n /*\n * `ai-assistant:mutation` — the same door as the board conversation's, which moved here on\n * 2026-09-10. No `legacy` alias: this operation is new, so no one was ever passing under an old\n * name, and declaring an alias would open a second name that nothing needs.\n */\n @Directive('@privilege(category: \"ai-assistant\", privilege: \"mutation\", domainOwnerGranted: true)')\n async assistantChat(@Arg('input') input: AssistantChatInput, @Ctx() context: any): Promise<AssistantChatOutput> {\n const client = resolveAIClient()\n if (!client) {\n throw new Error(\n 'No AI client configured. Set config.aiClient = { provider, model, apiKey } or call setDefaultAIClient(...).'\n )\n }\n\n /*\n * Read the declaration before anything is stored. A kind this server does not have is a\n * mismatched deployment, and the person should see that instead of a conversation with no\n * persona and no tools.\n */\n const t = requestTranslator(context)\n const settings = resolveModeSettings(input.mode, t)\n\n const { domain, user } = context.state\n const sessionRepo = getRepository(ChatSession)\n const messageRepo = getRepository(ChatMessage)\n\n let session: ChatSession | undefined\n if (input.sessionId) {\n const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } as any })\n if (!found) throw new Error(`ChatSession ${input.sessionId} not found`)\n /*\n * A private conversation is written by its people only - and here more than anywhere: the answer is\n * built on this conversation's history, so an outsider's question would read it back to them.\n */\n await assertMayWriteSession({\n session: found as any,\n userId: user?.id,\n isParticipant: () => isSessionParticipant(domain.id, found.id!, user?.id),\n t: (key, options) => t(key, options as any)\n })\n if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {\n throw new Error(\n context.t('ai-assistant.text.other-figure-history', {\n defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'\n })\n )\n }\n if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {\n throw new Error(\n context.t('ai-assistant.text.application-vs-model-history', {\n defaultValue: 'this conversation is about the application, not about a model. open the one you want.'\n })\n )\n }\n /*\n * 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이\n * 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.\n */\n const verdict = judgeSessionKind((found as any).kind, input.mode.kind)\n if (verdict.action === 'refuse') {\n throw new Error(\n t('ai-assistant.text.session-kind-mismatch', {\n ...verdict.params,\n defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'\n })\n )\n }\n if (verdict.action === 'stamp') {\n /* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */\n await sessionRepo.update(found.id!, { kind: verdict.kind } as any)\n ;(found as any).kind = verdict.kind\n }\n session = found\n }\n\n assertStationSession(session, input.hostContext, t)\n\n const lastUserMessage = input.messages[input.messages.length - 1]\n let userMessageId: string | undefined\n\n /*\n * Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by\n * attachToConversation; one that is not this conversation's is refused, never read. The policy is the\n * mode's - checked again here, since the door is the authority, not the screen.\n */\n const attachmentRows: any[] = []\n if (input.attachmentIds?.length) {\n if (!session) throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }))\n for (const id of input.attachmentIds) {\n const row = await findChatAttachment(domain.id, session.id!, id)\n if (!row) throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }))\n attachmentRows.push(row)\n }\n const refusal = refuseAttachments(\n getAssistantMode(input.mode.kind)?.attachments,\n attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) }))\n )\n if (refusal) throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...(refusal as any), defaultValue: refusal.code }))\n }\n\n if (session && lastUserMessage?.role === 'user') {\n const previousLast = await messageRepo.findOne({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'DESC' }\n })\n const saved = await messageRepo.save({\n session: { id: session.id } as any,\n role: 'user',\n content: lastUserMessage.content,\n /*\n * This door is the one people call to ask the assistant, so a turn stored here was for the\n * assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never\n * from the request — two sources for one fact can disagree.\n */\n addressee: 'assistant',\n attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(describeAttachment)) : undefined,\n creator: user,\n updater: user,\n parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined\n } as any)\n userMessageId = saved.id\n\n /*\n * Session activity is denormalised for the list: most-recent ordering and another\n * participant's unread badge read it. Best effort — a conversation must not fail because a\n * list sorts one position late.\n */\n try {\n const patch: any = activityPatch(lastUserMessage.content)\n if (!session.name) patch.name = autoSessionName(lastUserMessage.content)\n await sessionRepo.update(session.id!, patch)\n } catch {\n /* noop */\n }\n\n /*\n * 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을\n * 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다.\n */\n const invite = await inviteMentionedUsers({\n content: lastUserMessage.content,\n sessionId: session.id!,\n domainId: domain.id,\n inviter: user,\n participants: getRepository(ChatSessionParticipant),\n visibility: (session as any).visibility\n })\n if (invite.invited.length > 0) {\n const payload = buildInviteNotification(invite.invited, undefined, user, (session as any)?.name)\n try {\n if (payload) await (context.state as any)?.notify?.(payload)\n } catch {\n /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다. */\n }\n }\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: saved } as any)\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: lastUserMessage.content,\n actorId: user?.id\n })\n }\n\n /*\n * 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.\n *\n * 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드\n * 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —\n * 모델에게는 「N 개 생략」을 적어 보내면서.\n */\n const readRows = session\n ? await messageRepo.find({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'ASC' },\n relations: ['creator']\n })\n : []\n /*\n * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도\n * 안 지난 사람이 \"아까 그 수 다시 말해 줘\" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은\n * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런\n * 말이 없었다고 답하고, 그것은 거짓말이다.\n */\n const storedRows = await readerGate(context)(readRows)\n const capped = splitByCap(\n storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })),\n LLM_HISTORY_MAX_TURNS\n )\n const historyFolded =\n capped.dropped.length > 0\n ? { omitted: capped.dropped.length, summarized: Boolean((session as any)?.lastSummary) }\n : undefined\n\n const conversation = session\n ? buildLlmHistory(\n /*\n * The model reads who spoke and who they spoke to. The entity carries the speaker as a\n * relation and the addressee as a column; the history wants them as plain fields, and\n * without this mapping every line arrived unattributed — a room of people read as one\n * voice (ADR-0070 A15 decision ②).\n */\n storedRows.map(message => ({\n id: message.id,\n role: message.role,\n /*\n * A file sent in an earlier turn is not sent again - one line names it, and the model opens it\n * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).\n */\n content:\n message.id !== userMessageId && (message as any).attachmentsJson?.length\n ? [message.content, ...(message as any).attachmentsJson.map(attachmentHistoryLine)].join('\\n')\n : message.content,\n senderId: (message as any).creator?.id,\n senderName: (message as any).creator?.name,\n addressee: (message as any).addressee\n })),\n {\n maxTurns: LLM_HISTORY_MAX_TURNS,\n truncateAfterMessageId: input.truncateAfterMessageId,\n /* The message just stored is this turn's question — truncation must never drop it. */\n keepMessageIds: userMessageId ? [userMessageId] : undefined,\n summary: (session as any).lastSummary\n ? { text: (session as any).lastSummary, upToMessageId: (session as any).summaryUpToMessageId }\n : undefined\n }\n )\n : input.messages.map(message => ({ role: message.role as any, content: message.content }))\n\n if (attachmentRows.length && conversation.length > 0) {\n const last = conversation[conversation.length - 1]\n if (last.role === 'user' && typeof last.content === 'string') {\n const parts: any[] = [{ type: 'text', text: last.content }]\n for (const row of attachmentRows) {\n const file = await attachmentForModel(row)\n if (file.type === 'image') {\n parts.push({ type: 'image', source: { kind: 'base64', data: file.data, mediaType: file.mediaType } })\n } else {\n parts.push({\n type: 'text',\n text: `[attachment ${row.id}: ${file.name}${file.truncated ? ' - cut, the file is longer' : ''}]\\n${file.text}`\n })\n }\n }\n last.content = parts as any\n }\n } else if (input.hostContext?.image?.data && conversation.length > 0) {\n /* The screen-image path (figure's rendered view) - not a file of the conversation. */\n const last = conversation[conversation.length - 1]\n if (last.role === 'user' && typeof last.content === 'string') {\n const raw = input.hostContext.image\n const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\\/[a-zA-Z]+;base64,/, '') : raw.data\n const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)\n last.content = [\n { type: 'text', text: last.content },\n { type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }\n ] as any\n }\n }\n\n const result = await registryAssistantChat({\n client,\n messages: conversation as any,\n systemPrompt: settings.systemPrompt,\n toolCategories: settings.toolCategories,\n /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n toolAccess: toolAccessFor(context),\n /* The stop notice is a sentence a person reads — the server writes it in their language (ADR-0054). */\n t,\n hostContext: input.hostContext,\n /*\n * 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다\n * (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한\n * 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고\n * 자체를 안 보게 된다.\n */\n groundingSources: groundingSourcesFor({\n systemPrompt: settings.systemPrompt,\n messages: conversation as any,\n hostContext: input.hostContext\n }),\n state: context.state,\n model: settings.model,\n temperature: settings.temperature,\n maxTokens: settings.maxTokens,\n requireToolOnFirstTurn: settings.requireToolOnFirstTurn\n })\n\n /*\n * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면\n * 가려진 답이 목록에는 그대로 뜬다.\n */\n const answerDoors = doorsForAnswer(\n (result.loop.toolUsages ?? []).map((usage: any) => usage?.name).filter(Boolean),\n name => (findToolSpec(name, settings.toolCategories) as any)?.doors\n )\n\n let assistantMessageId: string | undefined\n if (session) {\n const stored = await messageRepo.save({\n session: { id: session.id } as any,\n role: 'assistant',\n content: result.reply,\n /*\n * 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이\n * 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면\n * 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.\n */\n doors: answerDoors,\n toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,\n groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,\n creator: user,\n updater: user,\n parentMessage: userMessageId ? ({ id: userMessageId } as any) : undefined\n })\n assistantMessageId = stored.id\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: stored } as any)\n /* The reply is session activity too. Leaving it out shows other participants \"nothing new\". */\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: result.reply,\n actorId: user?.id\n })\n\n await sessionRepo.update(session.id!, {\n aiClientId: client.id,\n updater: user,\n ...activityPatch(result.reply, new Date(), answerDoors)\n } as any)\n\n /*\n * 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에\n * 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음\n * 턴이 「N 개 생략」으로 정직하게 알린다.\n *\n * 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)\n * 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴\n * 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.\n */\n void foldSessionHistory({\n sessionId: session.id!,\n domainId: domain.id,\n client,\n maxTurns: LLM_HISTORY_MAX_TURNS,\n locale: context.state?.lng\n })\n }\n\n return {\n reply: result.reply,\n clientId: client.id,\n sessionId: session?.id,\n userMessageId,\n assistantMessageId,\n toolUsages: result.loop.toolUsages?.length ? result.loop.toolUsages : null,\n offeredTools: result.offeredTools,\n proposals: result.loop.proposals?.length ? result.loop.proposals : null,\n groundingWarnings: result.groundingWarnings?.length ? result.groundingWarnings : null,\n historyFolded: historyFolded ?? null\n }\n }\n}\n"]}
1
+ {"version":3,"file":"assistant-chat-resolver.js","sourceRoot":"","sources":["../../server/service/assistant-chat-resolver.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,+CAAoG;AACpG,qDAA6C;AAC7C,qCAAkC;AAElC,6CAA4C;AAC5C,iDAAqD;AACrD,mEAMuC;AAEvC,oEAA4D;AAC5D,sFAA8E;AAC9E,oEAA4D;AAC5D,kEAA+D;AAC/D,0EAA8D;AAC9D,oFAA2E;AAC3E,iEAA4D;AAC5D,oFAA2E;AAC3E,4FAAmF;AACnF,sEAAgF;AAChF,qDAAgD;AAChD,wGAA+F;AAC/F,sEAAgE;AAChE,oEAAiE;AACjE,kEAA0D;AAC1D,oFAAmF;AACnF,8FAA2F;AAC3F,4FAAuF;AACvF,gFAA4E;AAC5E,8EAA8F;AAC9F,kFAAkH;AAClH,8DAA+D;AAC/D,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SACrC,CAAA;IACH,CAAC;CACF,CAAA;AA/XY,sDAAqB;AAiB1B;IAVL,IAAA,uBAAQ,EAAC,GAAG,EAAE,CAAC,mBAAmB,EAAE;QACnC,WAAW,EACT,0JAA0J;KAC7J,CAAC;IACF;;;;OAIG;;IACF,IAAA,wBAAS,EAAC,uFAAuF,CAAC;IAC9E,mBAAA,IAAA,kBAAG,EAAC,OAAO,CAAC,CAAA;IAA6B,mBAAA,IAAA,kBAAG,GAAE,CAAA;;6CAA1B,kBAAkB;;0DA6W1D;gCA9XU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CA+XjC","sourcesContent":["/*\n * The neutral door into a conversation.\n *\n * ── Why this exists (2026-09-11) ───────────────────────────────────────────────\n * The chat component moved here from `board-ai`, but the only mutation it could call stayed\n * behind. operato-figure mounted the dock, registered four tools, and got\n * `Cannot query field \"boardAIChat\" on type \"Mutation\"` — it does not load board-ai. The twin has\n * the same shape and it does not show: its space deliberation runs through board-ai's door purely\n * because the board authoring half of the same product already loaded that package.\n *\n * ── Why the board resolver was not moved ───────────────────────────────────────\n * `board-ai-resolver.ts` is 692 lines and the larger part of it is board authoring itself:\n * `currentBoard` as a BoardModel, PatchEntry, board patch broadcasts, refid injection for\n * component mentions. Moving that here would teach this package the board document, which is the\n * dependency we just cut, pointing the other way.\n *\n * So the door moved and the editor did not. `boardAIChat` stays in board-ai for board authoring;\n * this one is for a surface that asks questions and runs registered tools.\n *\n * ── What this is not ───────────────────────────────────────────────────────────\n * It has no document, so it takes no document and returns no patch. Tools that write to a\n * document are not offered here — `registryAssistantChat` enforces that, and it decides what may\n * be dispatched from the same list it offers, so the two cannot drift apart.\n */\nimport { Arg, Ctx, Directive, Field, InputType, Mutation, ObjectType, Resolver } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\nimport '@things-factory/auth-base'\n\nimport { config } from '@things-factory/env'\nimport { getRepository } from '@things-factory/shell'\nimport {\n createAIClient,\n findToolSpec,\n getDefaultAIClient,\n registryAssistantChat,\n type AIClient\n} from '@things-factory/ai-client-base'\n\nimport { ChatSession } from './chat-session/chat-session.js'\nimport { assertStationSession } from './chat-session/station-session-guard.js'\nimport { ChatMessage } from './chat-message/chat-message.js'\nimport { buildLlmHistory } from './chat-message/llm-history.js'\nimport { splitByCap } from './chat-message/history-summary.js'\nimport { foldSessionHistory } from './chat-message/fold-session-history.js'\nimport { groundingSourcesFor } from './grounding-sources.js'\nimport { publishChatMessage } from './chat-message/chat-message-publish.js'\nimport { publishSessionActivity } from './chat-session/session-activity-publish.js'\nimport { activityPatch, autoSessionName } from './chat-session/session-inbox.js'\nimport { toolAccessFor } from './tool-access.js'\nimport { ChatSessionParticipant } from './chat-session-participant/chat-session-participant.js'\nimport { doorsForAnswer } from './chat-message/message-doors.js'\nimport { judgeSessionKind } from './chat-session/session-kind.js'\nimport { readerGate } from './chat-message/reader-gate.js'\nimport { inviteMentionedUsers } from './chat-session-participant/mention-invite.js'\nimport { buildInviteNotification } from './chat-session-participant/invite-notification.js'\nimport { isSessionParticipant } from './chat-session-participant/participant-lookup.js'\nimport { assertMayWriteSession } from './chat-session/session-write-gate.js'\nimport { attachmentHistoryLine, refuseAttachments } from './chat-session/attachment-policy.js'\nimport { attachmentForModel, describeAttachment, findChatAttachment } from './chat-session/session-attachments.js'\nimport { getAssistantMode } from './assistant-mode/registry.js'\nimport { resolveModeSettings } from './assistant-mode/resolve.js'\nimport { requestTranslator } from './request-translator.js'\n\n/**\n * How many stored messages reach the model.\n *\n * A deliberation runs for days. Without a cap the prompt grows without bound and the oldest turns\n * bury the recent ones. Kept the same as the board conversation's cap so the two surfaces of one\n * product do not remember differently.\n */\nconst LLM_HISTORY_MAX_TURNS = 40\n\n@InputType()\nclass AssistantMessageInput {\n @Field({ description: \"Role: 'user' or 'assistant'\" })\n role: string\n\n @Field({ description: 'Message content' })\n content: string\n}\n\n@InputType({ description: 'Which conversation this is, and what it is about.' })\nclass AssistantModeInput {\n @Field({ description: 'A mode kind the app server registered — `<app>.<surface>`, e.g. \"twin.space\".' })\n kind: string\n\n @Field({\n nullable: true,\n description:\n 'What this conversation is about — the space, the station, the model being edited. With `kind` it is the conversation\\'s lifetime: when either changes the screen closes the conversation and starts another.'\n })\n target?: string\n}\n\n@InputType({ description: 'One turn of a conversation that has no document of its own.' })\nclass AssistantChatInput {\n @Field({\n nullable: true,\n description: 'ChatSession id. Omit for a one-off question with no persistence.'\n })\n sessionId?: string\n\n @Field(() => [AssistantMessageInput], {\n description:\n 'Conversation, newest last. For a persisted session only the last user message is appended; the rest is read from storage.'\n })\n messages: AssistantMessageInput[]\n\n @Field(() => AssistantModeInput, {\n description:\n 'Which conversation this is. The persona, the tool categories, the model and the limits come from the mode the app server registered (ADR-0061 decision 7) — a caller choosing its own tool categories would be a caller choosing its own authority.'\n })\n mode: AssistantModeInput\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'What this surface is looking at (e.g. { figureId } while modelling). Tools read it so the model never has to ask the user for identifiers. Client-supplied — never used for authorization; a tool verifies the scope belongs to the caller tenant.'\n })\n hostContext?: any\n\n @Field({\n nullable: true,\n description:\n 'Last message to keep from the stored history. The client keeps its own truncation when a user edits a message, so pass the last kept id to hide the retracted span from the model.'\n })\n truncateAfterMessageId?: string\n\n @Field(() => [String], {\n nullable: true,\n description: 'Files stored with this conversation by attachToConversation, sent with this turn.'\n })\n attachmentIds?: string[]\n\n}\n\n@ObjectType()\nclass AssistantChatOutput {\n @Field({ description: 'The reply, including the notice when the loop stopped early.' })\n reply: string\n\n @Field({ description: 'AI client identifier (provider:model).' })\n clientId: string\n\n @Field({ nullable: true, description: 'Echo of the session id, when persisted.' })\n sessionId?: string\n\n @Field({ nullable: true, description: 'Stored ChatMessage id of the user input.' })\n userMessageId?: string\n\n @Field({ nullable: true, description: 'Stored ChatMessage id of the reply.' })\n assistantMessageId?: string\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Set when this turn did not fit: { omitted, summarized } — how many earlier messages the model did not see, and whether a summary stood in for them. Without it the person watches the conversation lose its beginning in silence, while the model is told.'\n })\n historyFolded?: any\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Tool usages during the turn — {name, arguments, result, kind}. The surface shows them foldably.'\n })\n toolUsages?: any\n\n @Field(() => [String], {\n nullable: true,\n description:\n 'Tool names offered to the model this turn. A surface that expected a category and sees it missing here knows the registration did not happen, rather than reading a vague answer as a refusal.'\n })\n offeredTools?: string[]\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Actions a tool recorded without executing — each carries what the tool returned alongside `proposed: true`. The surface renders a confirm button; executing is the user\\'s act.'\n })\n proposals?: any\n\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Identifiers in the reply that appear in nothing the model received. Hallucination candidates surfaced to the user; the reply itself is not altered. Null when the answer is grounded.'\n })\n groundingWarnings?: any\n}\n\nfunction resolveAIClient(): AIClient | undefined {\n const existing = getDefaultAIClient()\n if (existing) return existing\n const cfg = config.get('aiClient', null) as any\n if (cfg && cfg.provider) return createAIClient(cfg)\n return undefined\n}\n\n@Resolver()\nexport class AssistantChatResolver {\n /*\n * No `@transaction`, for the same reason the board conversation has none: a model call takes\n * seconds to tens of seconds, and holding a write lock for that long collides with everything\n * else on SQLite. Writes are short and around the call. For a conversation, a partly stored\n * history is safer than a lost one.\n */\n @Mutation(() => AssistantChatOutput, {\n description:\n 'Ask the assistant a question on a surface that has no document of its own. Tools come from the registry; with a sessionId the conversation is persisted.'\n })\n /*\n * `ai-assistant:mutation` — the same door as the board conversation's, which moved here on\n * 2026-09-10. No `legacy` alias: this operation is new, so no one was ever passing under an old\n * name, and declaring an alias would open a second name that nothing needs.\n */\n @Directive('@privilege(category: \"ai-assistant\", privilege: \"mutation\", domainOwnerGranted: true)')\n async assistantChat(@Arg('input') input: AssistantChatInput, @Ctx() context: any): Promise<AssistantChatOutput> {\n const client = resolveAIClient()\n if (!client) {\n throw new Error(\n 'No AI client configured. Set config.aiClient = { provider, model, apiKey } or call setDefaultAIClient(...).'\n )\n }\n\n /*\n * Read the declaration before anything is stored. A kind this server does not have is a\n * mismatched deployment, and the person should see that instead of a conversation with no\n * persona and no tools.\n */\n const t = requestTranslator(context)\n const settings = resolveModeSettings(input.mode, t)\n\n const { domain, user } = context.state\n const sessionRepo = getRepository(ChatSession)\n const messageRepo = getRepository(ChatMessage)\n\n let session: ChatSession | undefined\n if (input.sessionId) {\n const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } as any })\n if (!found) throw new Error(`ChatSession ${input.sessionId} not found`)\n /*\n * A private conversation is written by its people only - and here more than anywhere: the answer is\n * built on this conversation's history, so an outsider's question would read it back to them.\n */\n await assertMayWriteSession({\n session: found as any,\n userId: user?.id,\n isParticipant: () => isSessionParticipant(domain.id, found.id!, user?.id),\n t: (key, options) => t(key, options as any)\n })\n if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {\n throw new Error(\n context.t('ai-assistant.text.other-figure-history', {\n defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'\n })\n )\n }\n if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {\n throw new Error(\n context.t('ai-assistant.text.application-vs-model-history', {\n defaultValue: 'this conversation is about the application, not about a model. open the one you want.'\n })\n )\n }\n /*\n * 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이\n * 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.\n */\n const verdict = judgeSessionKind((found as any).kind, input.mode.kind)\n if (verdict.action === 'refuse') {\n throw new Error(\n t('ai-assistant.text.session-kind-mismatch', {\n ...verdict.params,\n defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'\n })\n )\n }\n if (verdict.action === 'stamp') {\n /* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */\n await sessionRepo.update(found.id!, { kind: verdict.kind } as any)\n ;(found as any).kind = verdict.kind\n }\n session = found\n }\n\n assertStationSession(session, input.hostContext, t)\n\n const lastUserMessage = input.messages[input.messages.length - 1]\n let userMessageId: string | undefined\n\n /*\n * Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by\n * attachToConversation; one that is not this conversation's is refused, never read. The policy is the\n * mode's - checked again here, since the door is the authority, not the screen.\n */\n const attachmentRows: any[] = []\n if (input.attachmentIds?.length) {\n if (!session) throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }))\n for (const id of input.attachmentIds) {\n const row = await findChatAttachment(domain.id, session.id!, id)\n if (!row) throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }))\n attachmentRows.push(row)\n }\n const refusal = refuseAttachments(\n getAssistantMode(input.mode.kind)?.attachments,\n attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) }))\n )\n if (refusal) throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...(refusal as any), defaultValue: refusal.code }))\n }\n\n if (session && lastUserMessage?.role === 'user') {\n const previousLast = await messageRepo.findOne({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'DESC' }\n })\n const saved = await messageRepo.save({\n session: { id: session.id } as any,\n role: 'user',\n content: lastUserMessage.content,\n /*\n * This door is the one people call to ask the assistant, so a turn stored here was for the\n * assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never\n * from the request — two sources for one fact can disagree.\n */\n addressee: 'assistant',\n attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(describeAttachment)) : undefined,\n creator: user,\n updater: user,\n parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined\n } as any)\n userMessageId = saved.id\n\n /*\n * Session activity is denormalised for the list: most-recent ordering and another\n * participant's unread badge read it. Best effort — a conversation must not fail because a\n * list sorts one position late.\n */\n try {\n const patch: any = activityPatch(lastUserMessage.content)\n if (!session.name) patch.name = autoSessionName(lastUserMessage.content)\n await sessionRepo.update(session.id!, patch)\n } catch {\n /* noop */\n }\n\n /*\n * 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을\n * 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다.\n */\n const invite = await inviteMentionedUsers({\n content: lastUserMessage.content,\n sessionId: session.id!,\n domainId: domain.id,\n inviter: user,\n participants: getRepository(ChatSessionParticipant),\n visibility: (session as any).visibility\n })\n if (invite.invited.length > 0) {\n const payload = buildInviteNotification(invite.invited, undefined, user, (session as any)?.name)\n try {\n if (payload) await (context.state as any)?.notify?.(payload)\n } catch {\n /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다. */\n }\n }\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: saved } as any)\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: lastUserMessage.content,\n actorId: user?.id\n })\n }\n\n /*\n * 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.\n *\n * 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드\n * 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —\n * 모델에게는 「N 개 생략」을 적어 보내면서.\n */\n const readRows = session\n ? await messageRepo.find({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'ASC' },\n relations: ['creator']\n })\n : []\n /*\n * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도\n * 안 지난 사람이 \"아까 그 수 다시 말해 줘\" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은\n * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런\n * 말이 없었다고 답하고, 그것은 거짓말이다.\n */\n const storedRows = await readerGate(context)(readRows)\n const capped = splitByCap(\n storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })),\n LLM_HISTORY_MAX_TURNS\n )\n const historyFolded =\n capped.dropped.length > 0\n ? { omitted: capped.dropped.length, summarized: Boolean((session as any)?.lastSummary) }\n : undefined\n\n const conversation = session\n ? buildLlmHistory(\n /*\n * The model reads who spoke and who they spoke to. The entity carries the speaker as a\n * relation and the addressee as a column; the history wants them as plain fields, and\n * without this mapping every line arrived unattributed — a room of people read as one\n * voice (ADR-0070 A15 decision ②).\n */\n storedRows.map(message => ({\n id: message.id,\n role: message.role,\n /*\n * A file sent in an earlier turn is not sent again - one line names it, and the model opens it\n * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).\n */\n content:\n message.id !== userMessageId && (message as any).attachmentsJson?.length\n ? [message.content, ...(message as any).attachmentsJson.map(attachmentHistoryLine)].join('\\n')\n : message.content,\n senderId: (message as any).creator?.id,\n senderName: (message as any).creator?.name,\n addressee: (message as any).addressee\n })),\n {\n maxTurns: LLM_HISTORY_MAX_TURNS,\n truncateAfterMessageId: input.truncateAfterMessageId,\n /* The message just stored is this turn's question — truncation must never drop it. */\n keepMessageIds: userMessageId ? [userMessageId] : undefined,\n summary: (session as any).lastSummary\n ? { text: (session as any).lastSummary, upToMessageId: (session as any).summaryUpToMessageId }\n : undefined\n }\n )\n : input.messages.map(message => ({ role: message.role as any, content: message.content }))\n\n if (attachmentRows.length && conversation.length > 0) {\n const last = conversation[conversation.length - 1]\n if (last.role === 'user' && typeof last.content === 'string') {\n const parts: any[] = [{ type: 'text', text: last.content }]\n for (const row of attachmentRows) {\n const file = await attachmentForModel(row)\n if (file.type === 'image') {\n parts.push({ type: 'image', source: { kind: 'base64', data: file.data, mediaType: file.mediaType } })\n } else {\n parts.push({\n type: 'text',\n text: `[attachment ${row.id}: ${file.name}${file.truncated ? ' - cut, the file is longer' : ''}]\\n${file.text}`\n })\n }\n }\n last.content = parts as any\n }\n } else if (input.hostContext?.image?.data && conversation.length > 0) {\n /* The screen-image path (figure's rendered view) - not a file of the conversation. */\n const last = conversation[conversation.length - 1]\n if (last.role === 'user' && typeof last.content === 'string') {\n const raw = input.hostContext.image\n const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\\/[a-zA-Z]+;base64,/, '') : raw.data\n const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)\n last.content = [\n { type: 'text', text: last.content },\n { type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }\n ] as any\n }\n }\n\n const result = await registryAssistantChat({\n client,\n messages: conversation as any,\n systemPrompt: settings.systemPrompt,\n toolCategories: settings.toolCategories,\n /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n toolAccess: toolAccessFor(context),\n /* The stop notice is a sentence a person reads — the server writes it in their language (ADR-0054). */\n t,\n hostContext: input.hostContext,\n /*\n * 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다\n * (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한\n * 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고\n * 자체를 안 보게 된다.\n */\n groundingSources: groundingSourcesFor({\n systemPrompt: settings.systemPrompt,\n messages: conversation as any,\n hostContext: input.hostContext\n }),\n state: context.state,\n model: settings.model,\n temperature: settings.temperature,\n maxTokens: settings.maxTokens,\n requireToolOnFirstTurn: settings.requireToolOnFirstTurn\n })\n\n /*\n * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면\n * 가려진 답이 목록에는 그대로 뜬다.\n */\n const answerDoors = doorsForAnswer(\n (result.loop.toolUsages ?? []).map((usage: any) => usage?.name).filter(Boolean),\n name => (findToolSpec(name, settings.toolCategories) as any)?.doors\n )\n\n let assistantMessageId: string | undefined\n if (session) {\n const stored = await messageRepo.save({\n session: { id: session.id } as any,\n role: 'assistant',\n content: result.reply,\n /*\n * 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이\n * 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면\n * 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.\n */\n doors: answerDoors,\n toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,\n proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,\n groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,\n creator: user,\n updater: user,\n parentMessage: userMessageId ? ({ id: userMessageId } as any) : undefined\n })\n assistantMessageId = stored.id\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: stored } as any)\n /* The reply is session activity too. Leaving it out shows other participants \"nothing new\". */\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: result.reply,\n actorId: user?.id\n })\n\n await sessionRepo.update(session.id!, {\n aiClientId: client.id,\n updater: user,\n ...activityPatch(result.reply, new Date(), answerDoors)\n } as any)\n\n /*\n * 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에\n * 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음\n * 턴이 「N 개 생략」으로 정직하게 알린다.\n *\n * 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)\n * 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴\n * 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.\n */\n void foldSessionHistory({\n sessionId: session.id!,\n domainId: domain.id,\n client,\n maxTurns: LLM_HISTORY_MAX_TURNS,\n locale: context.state?.lng\n })\n }\n\n return {\n reply: result.reply,\n clientId: client.id,\n sessionId: session?.id,\n userMessageId,\n assistantMessageId,\n toolUsages: result.loop.toolUsages?.length ? result.loop.toolUsages : null,\n offeredTools: result.offeredTools,\n proposals: result.loop.proposals?.length ? result.loop.proposals : null,\n groundingWarnings: result.groundingWarnings?.length ? result.groundingWarnings : null,\n historyFolded: historyFolded ?? null\n }\n }\n}\n"]}
@@ -53,6 +53,16 @@ export declare class ChatMessage {
53
53
  toolUsages?: string;
54
54
  /** GraphQL 노출용 — JSON 배열로 parse. */
55
55
  get toolUsagesJson(): any;
56
+ /**
57
+ * The proposals this answer made - JSON-stringified, like `toolUsages` (ADR-0097 Q-D4 ④).
58
+ *
59
+ * A card lived only in the mutation's answer, so a refresh took it away, and with it the one place the
60
+ * person could see that a proposal was requested and never answered. Stored, the card comes back with
61
+ * its state read from the conversation's rows. Cleared with the body when the row is redacted
62
+ * (`message-doors.ts` VALUE_CARRYING) - a proposal carries the same values as the answer.
63
+ */
64
+ proposals?: string;
65
+ get proposalsJson(): any;
56
66
  /**
57
67
  * 접지 경고 — 이 답이 언급했으나 근거(프롬프트·보드 문맥·이력·도구 결과)에 없던 식별자 목록.
58
68
  *
@@ -30,6 +30,16 @@ let ChatMessage = class ChatMessage {
30
30
  return null;
31
31
  }
32
32
  }
33
+ get proposalsJson() {
34
+ if (!this.proposals)
35
+ return null;
36
+ try {
37
+ return JSON.parse(this.proposals);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
33
43
  get attachmentsJson() {
34
44
  if (!this.attachments)
35
45
  return null;
@@ -134,6 +144,25 @@ tslib_1.__decorate([
134
144
  tslib_1.__metadata("design:type", Object),
135
145
  tslib_1.__metadata("design:paramtypes", [])
136
146
  ], ChatMessage.prototype, "toolUsagesJson", null);
147
+ tslib_1.__decorate([
148
+ (0, typeorm_1.Column)({
149
+ type: DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'
150
+ ? 'longtext'
151
+ : DATABASE_TYPE == 'oracle'
152
+ ? 'clob'
153
+ : DATABASE_TYPE == 'mssql'
154
+ ? 'nvarchar'
155
+ : 'text',
156
+ length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,
157
+ nullable: true
158
+ }),
159
+ tslib_1.__metadata("design:type", String)
160
+ ], ChatMessage.prototype, "proposals", void 0);
161
+ tslib_1.__decorate([
162
+ (0, type_graphql_1.Field)(() => graphql_scalars_1.GraphQLJSON, { nullable: true, description: 'Proposals this answer made - the cards the panel draws. Only on assistant messages.' }),
163
+ tslib_1.__metadata("design:type", Object),
164
+ tslib_1.__metadata("design:paramtypes", [])
165
+ ], ChatMessage.prototype, "proposalsJson", null);
137
166
  tslib_1.__decorate([
138
167
  (0, typeorm_1.Column)({ type: 'text', nullable: true }),
139
168
  tslib_1.__metadata("design:type", String)
@@ -1 +1 @@
1
- {"version":3,"file":"chat-message.js","sourceRoot":"","sources":["../../../server/service/chat-message/chat-message.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;GAOG;AACH,qCAUgB;AAChB,+CAAoD;AACpD,qDAA6C;AAE7C,yDAAgD;AAChD,6CAA4C;AAE5C,qEAA6D;AAE7D,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAA;AAK7B,IAAM,WAAW,GAAjB,MAAM,WAAW;IAyGtB,oCAAoC;IACpC,IAKI,cAAc;QAChB,IAAI,CAAC,IAAI,CAAC,UAAU;YAAE,OAAO,IAAI,CAAA;QACjC,IAAI,CAAC;YACH,OAAO,IAAI,CA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gB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,wBAAwB,EAAE,CAAC;sCACrD,IAAI;8CAAA;sBA7NL,WAAW;IAHvB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,mBAAmB,EAAE,CAAC,OAAoB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1F,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;GAC1D,WAAW,CA8NvB","sourcesContent":["/**\n * ChatMessage — ChatSession 의 한 메시지.\n *\n * role: 'user' | 'assistant' | 'system'\n * 'system' 은 사용자 직접 편집/import 진행 등 시스템이 자동 생성하는 컨텍스트 메시지.\n *\n * relatedPatchId / relatedImportSessionId 로 메시지가 트리거한 패치·임포트와 연결.\n */\nimport {\n Column,\n CreateDateColumn,\n DeleteDateColumn,\n Entity,\n Index,\n ManyToOne,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\nimport { Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport { User } from '@things-factory/auth-base'\nimport { config } from '@things-factory/env'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\n@Entity()\n@Index('ix_chat_message_1', (message: ChatMessage) => [message.session, message.createdAt])\n@ObjectType({ description: 'A single chat message in a ChatSession.' })\nexport class ChatMessage {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { nullable: true })\n readonly id?: string\n\n @ManyToOne(type => ChatSession, session => session.messages, { onDelete: 'CASCADE' })\n session?: ChatSession\n\n @RelationId((message: ChatMessage) => message.session)\n sessionId?: string\n\n @Column({ type: 'varchar', length: 16 })\n @Field({ description: \"'user' | 'assistant' | 'system'\" })\n role!: string\n\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n @Field({ description: 'Message content' })\n content!: string\n\n /**\n * 이 말이 누구에게 한 말인가 — `'assistant'` · `'room'`(ADR-0070 A15 결정 ①).\n *\n * **값은 그 행을 쓴 문이 찍는다.** 어시스턴트에게 묻는 문(`assistantChat`)이 저장한 사람의 행은\n * `assistant` 이고, 사람끼리의 문(`appendSessionTurns`)이 저장한 행은 `room` 이다. 클라이언트가\n * 인자로 보내지 않는다 — 인자로 받으면 「어느 문을 불렀나」와 「무엇을 적어 보냈나」 두 사실이\n * 생기고, 둘은 어긋날 수 있다.\n *\n * 사람의 행에만 뜻이 있다. 어시스턴트의 답은 `parentMessage` 로 자기를 부른 턴에 귀속되고,\n * `system` 행은 누구에게 한 말이 아니다.\n */\n @Column({ type: 'varchar', length: 16, nullable: true })\n @Field({ nullable: true, description: \"Who this turn was for: 'assistant' | 'room'. Written by the door that stored it, never sent by the client.\" })\n addressee?: string\n\n /**\n * 이 행의 값이 지나온 문들 — ADR-0073 판정 1.\n *\n * 어시스턴트의 답과 제안 행에만 채워진다. 사람의 말은 빈 목록이다 — 사람이 자기 입으로 한 말에는\n * 문이 없다. 답을 저장할 때 그 턴에 부른 도구들의 `doors`(ADR-0072)를 합쳐 옮겨 적는다.\n *\n * 읽을 때마다 **읽는 사람**이 이 문을 전부 지나는지 보고, 못 지나면 본문 대신 한 줄이 나간다. 그래서\n * 이 칸은 \"누가 볼 수 있나\"를 적은 것이고, 저장된 값 자체는 누구에게도 달라지지 않는다.\n *\n * 목록이 비면 누구나 읽는다. 등록기가 모르는 도구가 답에 끼면 `unresolved:<도구>` 가 적히고 아무도\n * 못 지난다 — 모르는 값은 가려지는 쪽으로 넘어뜨린다.\n */\n @Column({ type: 'simple-array', nullable: true })\n @Field(() => [String], {\n nullable: true,\n description:\n 'GraphQL doors the tools behind this answer went through. Empty for what people typed. A reader who does not pass all of them gets a one-line notice in place of the content.'\n })\n doors?: string[]\n\n /**\n * 이 행이 **이 사람에게** 가려져 나갔는가 — 저장하지 않는다.\n *\n * 같은 행이 사람마다 다르게 나가므로 칸에 적을 값이 없다. 읽어 나갈 때 채운다. 화면은 이것으로\n * 자물쇠를 그리고, 본문에 온 한 줄을 어시스턴트의 말로 오해하지 않는다.\n */\n @Field({ nullable: true, description: 'True when the content was replaced because this reader does not pass the row doors.' })\n redacted?: boolean\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'PatchEntry.id this message triggered (if any).' })\n relatedPatchId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'ImportSession.id this message triggered (if any).' })\n relatedImportSessionId?: string\n\n /**\n * AI 가 응답을 만드는 동안 호출한 도구 trace — JSON-stringified.\n *\n * 컬럼은 string (PatchEntry.ops 와 동일 패턴), GraphQL 노출은 toolUsagesJson getter\n * 로 parse 된 객체. UI 의 fold-able 박스 (\"AI 가 이런 도구를 사용했습니다\") 가\n * 페이지 reload / loadHistory 후에도 살아있도록 영속.\n *\n * 형태: ToolUsage[] (assistant.ts 의 시간순 trace, summarizeToolResult 로 압축).\n * null 이면 도구 호출 없었던 메시지 (text-only 응답).\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n toolUsages?: string\n\n /** GraphQL 노출용 — JSON 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Tool usage trace — array of {name, arguments, result, kind}. Only on assistant messages.'\n })\n get toolUsagesJson(): any {\n if (!this.toolUsages) return null\n try {\n return JSON.parse(this.toolUsages)\n } catch {\n return null\n }\n }\n\n /**\n * 접지 경고 — 이 답이 언급했으나 근거(프롬프트·보드 문맥·이력·도구 결과)에 없던 식별자 목록.\n *\n * **왜 영속하는가**: 도크의 협의는 여러 사람이 며칠에 걸쳐 읽는다. 경고가 그 자리에서만\n * 보이고 새로 고치면 사라지면, 나중에 읽는 사람은 검증되지 않은 문장을 검증된 것으로 읽는다.\n * 다시 계산할 수도 없다 — 근거였던 도구 결과 원문은 남지 않고 압축본만 남기 때문이다.\n *\n * 형태: string[] 를 JSON-stringify. 비었으면 null(= 접지 정상).\n */\n /**\n * The files sent with this turn - `[{ id, name, mimetype, size }]` as JSON (design/ai/shared-dock.md §9-2).\n * The files themselves live in attachment-base under the conversation and are opened only through it.\n */\n @Column({ type: 'text', nullable: true })\n attachments?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Files sent with this turn: [{ id, name, mimetype, size }].' })\n get attachmentsJson(): any {\n if (!this.attachments) return null\n try {\n return JSON.parse(this.attachments)\n } catch {\n return null\n }\n }\n\n @Column({ type: 'varchar', length: 1024, nullable: true })\n groundingWarnings?: string\n\n /** GraphQL 노출용 — 식별자 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Ungrounded identifiers mentioned by this reply (hallucination candidates). Null when grounded.'\n })\n get groundingWarningsJson(): any {\n if (!this.groundingWarnings) return null\n try {\n return JSON.parse(this.groundingWarnings)\n } catch {\n return null\n }\n }\n\n /**\n * 메시지를 일으킨 사용자.\n * - role='user' → 보낸 사용자\n * - role='assistant' → 그 응답을 트리거한 사용자 (직전 user 메시지의 작성자)\n * - role='system' → 시스템 액션을 일으킨 사용자 (예: 직접 편집한 사용자)\n *\n * nullable — legacy 메시지 (이 필드 추가 이전에 작성) 는 null. 또한 ad-hoc 모드 / 시스템\n * 자동 메시지 중 사용자 컨텍스트가 없는 경우도 null 가능.\n */\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'User who triggered this message.' })\n creator?: User\n\n @RelationId((message: ChatMessage) => message.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Last user to update this message (for future edit support).' })\n updater?: User\n\n @RelationId((message: ChatMessage) => message.updater)\n updaterId?: string\n\n /**\n * 부모 메시지 — 이 메시지가 \"응답하는 대상\" / \"이어가는 메시지\" 의 id.\n *\n * 의미 (role 별):\n * - 'user' → 직전 in-session 메시지 (보통 assistant 또는 system). 첫 turn 은 null.\n * - 'assistant' → 이 응답이 답하는 user 메시지. (regenerate 로 같은 user 메시지를 부모로\n * 하는 형제 assistant 메시지가 생기면 자연스럽게 branching tree 가 됨)\n * - 'system' → 직전 in-session 메시지 (timeline 연속성 유지).\n *\n * 이 한 컬럼으로 향후 어떤 흐름이든 표현 가능 — linear chain / branching (regenerate) /\n * tree (replies-to-specific-message) 등. UI/쿼리는 점진 도입.\n *\n * onDelete: 'SET NULL' — 부모 메시지가 삭제돼도 child 는 남되 dangling 마킹.\n */\n @ManyToOne(type => ChatMessage, { nullable: true, onDelete: 'SET NULL' })\n parentMessage?: ChatMessage\n\n @RelationId((message: ChatMessage) => message.parentMessage)\n @Field({\n nullable: true,\n description:\n 'Id of the message this one is in-response-to / continues. Enables linear / branching / tree structures.'\n })\n parentMessageId?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Creation timestamp.' })\n createdAt?: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Last update timestamp (relevant once message editing is supported).' })\n updatedAt?: Date\n\n @DeleteDateColumn()\n @Field({ nullable: true, description: 'Soft delete timestamp.' })\n deletedAt?: Date\n}\n"]}
1
+ {"version":3,"file":"chat-message.js","sourceRoot":"","sources":["../../../server/service/chat-message/chat-message.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;GAOG;AACH,qCAUgB;AAChB,+CAAoD;AACpD,qDAA6C;AAE7C,yDAAgD;AAChD,6CAA4C;AAE5C,qEAA6D;AAE7D,MA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EAAC,mBAAmB,EAAE,CAAC,OAAoB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1F,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;GAC1D,WAAW,CA8PvB","sourcesContent":["/**\n * ChatMessage — ChatSession 의 한 메시지.\n *\n * role: 'user' | 'assistant' | 'system'\n * 'system' 은 사용자 직접 편집/import 진행 등 시스템이 자동 생성하는 컨텍스트 메시지.\n *\n * relatedPatchId / relatedImportSessionId 로 메시지가 트리거한 패치·임포트와 연결.\n */\nimport {\n Column,\n CreateDateColumn,\n DeleteDateColumn,\n Entity,\n Index,\n ManyToOne,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\nimport { Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport { User } from '@things-factory/auth-base'\nimport { config } from '@things-factory/env'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\n@Entity()\n@Index('ix_chat_message_1', (message: ChatMessage) => [message.session, message.createdAt])\n@ObjectType({ description: 'A single chat message in a ChatSession.' })\nexport class ChatMessage {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { nullable: true })\n readonly id?: string\n\n @ManyToOne(type => ChatSession, session => session.messages, { onDelete: 'CASCADE' })\n session?: ChatSession\n\n @RelationId((message: ChatMessage) => message.session)\n sessionId?: string\n\n @Column({ type: 'varchar', length: 16 })\n @Field({ description: \"'user' | 'assistant' | 'system'\" })\n role!: string\n\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n @Field({ description: 'Message content' })\n content!: string\n\n /**\n * 이 말이 누구에게 한 말인가 — `'assistant'` · `'room'`(ADR-0070 A15 결정 ①).\n *\n * **값은 그 행을 쓴 문이 찍는다.** 어시스턴트에게 묻는 문(`assistantChat`)이 저장한 사람의 행은\n * `assistant` 이고, 사람끼리의 문(`appendSessionTurns`)이 저장한 행은 `room` 이다. 클라이언트가\n * 인자로 보내지 않는다 — 인자로 받으면 「어느 문을 불렀나」와 「무엇을 적어 보냈나」 두 사실이\n * 생기고, 둘은 어긋날 수 있다.\n *\n * 사람의 행에만 뜻이 있다. 어시스턴트의 답은 `parentMessage` 로 자기를 부른 턴에 귀속되고,\n * `system` 행은 누구에게 한 말이 아니다.\n */\n @Column({ type: 'varchar', length: 16, nullable: true })\n @Field({ nullable: true, description: \"Who this turn was for: 'assistant' | 'room'. Written by the door that stored it, never sent by the client.\" })\n addressee?: string\n\n /**\n * 이 행의 값이 지나온 문들 — ADR-0073 판정 1.\n *\n * 어시스턴트의 답과 제안 행에만 채워진다. 사람의 말은 빈 목록이다 — 사람이 자기 입으로 한 말에는\n * 문이 없다. 답을 저장할 때 그 턴에 부른 도구들의 `doors`(ADR-0072)를 합쳐 옮겨 적는다.\n *\n * 읽을 때마다 **읽는 사람**이 이 문을 전부 지나는지 보고, 못 지나면 본문 대신 한 줄이 나간다. 그래서\n * 이 칸은 \"누가 볼 수 있나\"를 적은 것이고, 저장된 값 자체는 누구에게도 달라지지 않는다.\n *\n * 목록이 비면 누구나 읽는다. 등록기가 모르는 도구가 답에 끼면 `unresolved:<도구>` 가 적히고 아무도\n * 못 지난다 — 모르는 값은 가려지는 쪽으로 넘어뜨린다.\n */\n @Column({ type: 'simple-array', nullable: true })\n @Field(() => [String], {\n nullable: true,\n description:\n 'GraphQL doors the tools behind this answer went through. Empty for what people typed. A reader who does not pass all of them gets a one-line notice in place of the content.'\n })\n doors?: string[]\n\n /**\n * 이 행이 **이 사람에게** 가려져 나갔는가 — 저장하지 않는다.\n *\n * 같은 행이 사람마다 다르게 나가므로 칸에 적을 값이 없다. 읽어 나갈 때 채운다. 화면은 이것으로\n * 자물쇠를 그리고, 본문에 온 한 줄을 어시스턴트의 말로 오해하지 않는다.\n */\n @Field({ nullable: true, description: 'True when the content was replaced because this reader does not pass the row doors.' })\n redacted?: boolean\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'PatchEntry.id this message triggered (if any).' })\n relatedPatchId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'ImportSession.id this message triggered (if any).' })\n relatedImportSessionId?: string\n\n /**\n * AI 가 응답을 만드는 동안 호출한 도구 trace — JSON-stringified.\n *\n * 컬럼은 string (PatchEntry.ops 와 동일 패턴), GraphQL 노출은 toolUsagesJson getter\n * 로 parse 된 객체. UI 의 fold-able 박스 (\"AI 가 이런 도구를 사용했습니다\") 가\n * 페이지 reload / loadHistory 후에도 살아있도록 영속.\n *\n * 형태: ToolUsage[] (assistant.ts 의 시간순 trace, summarizeToolResult 로 압축).\n * null 이면 도구 호출 없었던 메시지 (text-only 응답).\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n toolUsages?: string\n\n /** GraphQL 노출용 — JSON 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Tool usage trace — array of {name, arguments, result, kind}. Only on assistant messages.'\n })\n get toolUsagesJson(): any {\n if (!this.toolUsages) return null\n try {\n return JSON.parse(this.toolUsages)\n } catch {\n return null\n }\n }\n\n /**\n * The proposals this answer made - JSON-stringified, like `toolUsages` (ADR-0097 Q-D4 ④).\n *\n * A card lived only in the mutation's answer, so a refresh took it away, and with it the one place the\n * person could see that a proposal was requested and never answered. Stored, the card comes back with\n * its state read from the conversation's rows. Cleared with the body when the row is redacted\n * (`message-doors.ts` VALUE_CARRYING) - a proposal carries the same values as the answer.\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n proposals?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Proposals this answer made - the cards the panel draws. Only on assistant messages.' })\n get proposalsJson(): any {\n if (!this.proposals) return null\n try {\n return JSON.parse(this.proposals)\n } catch {\n return null\n }\n }\n\n /**\n * 접지 경고 — 이 답이 언급했으나 근거(프롬프트·보드 문맥·이력·도구 결과)에 없던 식별자 목록.\n *\n * **왜 영속하는가**: 도크의 협의는 여러 사람이 며칠에 걸쳐 읽는다. 경고가 그 자리에서만\n * 보이고 새로 고치면 사라지면, 나중에 읽는 사람은 검증되지 않은 문장을 검증된 것으로 읽는다.\n * 다시 계산할 수도 없다 — 근거였던 도구 결과 원문은 남지 않고 압축본만 남기 때문이다.\n *\n * 형태: string[] 를 JSON-stringify. 비었으면 null(= 접지 정상).\n */\n /**\n * The files sent with this turn - `[{ id, name, mimetype, size }]` as JSON (design/ai/shared-dock.md §9-2).\n * The files themselves live in attachment-base under the conversation and are opened only through it.\n */\n @Column({ type: 'text', nullable: true })\n attachments?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Files sent with this turn: [{ id, name, mimetype, size }].' })\n get attachmentsJson(): any {\n if (!this.attachments) return null\n try {\n return JSON.parse(this.attachments)\n } catch {\n return null\n }\n }\n\n @Column({ type: 'varchar', length: 1024, nullable: true })\n groundingWarnings?: string\n\n /** GraphQL 노출용 — 식별자 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Ungrounded identifiers mentioned by this reply (hallucination candidates). Null when grounded.'\n })\n get groundingWarningsJson(): any {\n if (!this.groundingWarnings) return null\n try {\n return JSON.parse(this.groundingWarnings)\n } catch {\n return null\n }\n }\n\n /**\n * 메시지를 일으킨 사용자.\n * - role='user' → 보낸 사용자\n * - role='assistant' → 그 응답을 트리거한 사용자 (직전 user 메시지의 작성자)\n * - role='system' → 시스템 액션을 일으킨 사용자 (예: 직접 편집한 사용자)\n *\n * nullable — legacy 메시지 (이 필드 추가 이전에 작성) 는 null. 또한 ad-hoc 모드 / 시스템\n * 자동 메시지 중 사용자 컨텍스트가 없는 경우도 null 가능.\n */\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'User who triggered this message.' })\n creator?: User\n\n @RelationId((message: ChatMessage) => message.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Last user to update this message (for future edit support).' })\n updater?: User\n\n @RelationId((message: ChatMessage) => message.updater)\n updaterId?: string\n\n /**\n * 부모 메시지 — 이 메시지가 \"응답하는 대상\" / \"이어가는 메시지\" 의 id.\n *\n * 의미 (role 별):\n * - 'user' → 직전 in-session 메시지 (보통 assistant 또는 system). 첫 turn 은 null.\n * - 'assistant' → 이 응답이 답하는 user 메시지. (regenerate 로 같은 user 메시지를 부모로\n * 하는 형제 assistant 메시지가 생기면 자연스럽게 branching tree 가 됨)\n * - 'system' → 직전 in-session 메시지 (timeline 연속성 유지).\n *\n * 이 한 컬럼으로 향후 어떤 흐름이든 표현 가능 — linear chain / branching (regenerate) /\n * tree (replies-to-specific-message) 등. UI/쿼리는 점진 도입.\n *\n * onDelete: 'SET NULL' — 부모 메시지가 삭제돼도 child 는 남되 dangling 마킹.\n */\n @ManyToOne(type => ChatMessage, { nullable: true, onDelete: 'SET NULL' })\n parentMessage?: ChatMessage\n\n @RelationId((message: ChatMessage) => message.parentMessage)\n @Field({\n nullable: true,\n description:\n 'Id of the message this one is in-response-to / continues. Enables linear / branching / tree structures.'\n })\n parentMessageId?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Creation timestamp.' })\n createdAt?: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Last update timestamp (relevant once message editing is supported).' })\n updatedAt?: Date\n\n @DeleteDateColumn()\n @Field({ nullable: true, description: 'Soft delete timestamp.' })\n deletedAt?: Date\n}\n"]}
@@ -16,3 +16,11 @@ export declare const PROPOSAL_VERDICTS: ProposalVerdict[];
16
16
  * English, like the other lines the model reads. The panel turns it into the reader's language.
17
17
  */
18
18
  export declare function formatProposalOutcomeLine(key: string, outcome: ProposalOutcome): string;
19
+ export declare const PROPOSAL_REQUESTED = "requested";
20
+ /** `proposal <key>: requested` */
21
+ export declare function formatProposalRequestedLine(key: string): string;
22
+ /**
23
+ * Whether this proposal was already taken in this conversation — requested, or answered.
24
+ * The caller passes the conversation's system lines; the answer is the rule, kept testable.
25
+ */
26
+ export declare function proposalAlreadyTaken(key: string, systemLines: readonly (string | null | undefined)[]): boolean;
@@ -12,8 +12,10 @@
12
12
  * panel's parser is tested against this formatter.
13
13
  */
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.PROPOSAL_VERDICTS = exports.PROPOSAL_OUTCOME_PREFIX = void 0;
15
+ exports.PROPOSAL_REQUESTED = exports.PROPOSAL_VERDICTS = exports.PROPOSAL_OUTCOME_PREFIX = void 0;
16
16
  exports.formatProposalOutcomeLine = formatProposalOutcomeLine;
17
+ exports.formatProposalRequestedLine = formatProposalRequestedLine;
18
+ exports.proposalAlreadyTaken = proposalAlreadyTaken;
17
19
  exports.PROPOSAL_OUTCOME_PREFIX = 'proposal ';
18
20
  exports.PROPOSAL_VERDICTS = ['accepted', 'refused', 'unavailable', 'declined'];
19
21
  /**
@@ -28,4 +30,36 @@ function formatProposalOutcomeLine(key, outcome) {
28
30
  : '';
29
31
  return `${exports.PROPOSAL_OUTCOME_PREFIX}${key}: ${outcome.verdict}${reason}${counted}`;
30
32
  }
33
+ /*
34
+ * "Requested" — written before the host is asked to run a proposal (ADR-0097 Q-D4 ④).
35
+ *
36
+ * The card used to remember that it was pressed in the page's memory only. After a refresh a
37
+ * proposal whose outcome never came back had its button again, and pressing it asked the host to
38
+ * apply it a second time. The request is now a row, like the outcome, so every reader sees it: the
39
+ * card after a refresh, another window, and the model ("requested, no answer yet").
40
+ *
41
+ * It is not a verdict — nothing happened yet. It only says the host was asked.
42
+ */
43
+ exports.PROPOSAL_REQUESTED = 'requested';
44
+ /** `proposal <key>: requested` */
45
+ function formatProposalRequestedLine(key) {
46
+ return `${exports.PROPOSAL_OUTCOME_PREFIX}${key}: ${exports.PROPOSAL_REQUESTED}`;
47
+ }
48
+ /**
49
+ * Whether this proposal was already taken in this conversation — requested, or answered.
50
+ * The caller passes the conversation's system lines; the answer is the rule, kept testable.
51
+ */
52
+ function proposalAlreadyTaken(key, systemLines) {
53
+ const requested = formatProposalRequestedLine(key);
54
+ const answered = `${exports.PROPOSAL_OUTCOME_PREFIX}${key}: `;
55
+ return systemLines.some(line => {
56
+ const text = (line ?? '').trim();
57
+ if (text === requested)
58
+ return true;
59
+ if (!text.startsWith(answered))
60
+ return false;
61
+ const rest = text.slice(answered.length);
62
+ return exports.PROPOSAL_VERDICTS.some(verdict => rest === verdict || rest.startsWith(`${verdict} `));
63
+ });
64
+ }
31
65
  //# sourceMappingURL=proposal-outcome.js.map