@things-factory/ai-assistant 10.1.47 → 10.1.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/components/assistant-chat.ts +97 -19
- package/client/components/assistant-dock.ts +617 -0
- package/client/components/assistant-mode.ts +2 -0
- package/client/components/assistant-session-manager.ts +607 -0
- package/client/components/chat-echo-dedup.ts +4 -0
- package/client/components/chat-input-builder.ts +4 -1
- package/client/components/panel-aria.test.ts +13 -8
- package/client/index.ts +8 -0
- package/client/setup-assistant-dock.ts +109 -0
- package/client/utils/assistant-activity.ts +122 -0
- package/client/utils/assistant-ask.ts +44 -0
- package/client/utils/assistant-proposals.ts +50 -0
- package/client/utils/assistant-session-actions.ts +18 -0
- package/client/utils/assistant-session-admin.ts +167 -0
- package/client/utils/assistant-session-controller.ts +2 -0
- package/client/utils/assistant-session-transport.ts +6 -2
- package/client/utils/assistant-surface.ts +157 -0
- package/client/utils/attachment-policy.ts +71 -0
- package/dist-client/components/assistant-chat.d.ts +6 -0
- package/dist-client/components/assistant-chat.js +98 -20
- package/dist-client/components/assistant-chat.js.map +1 -1
- package/dist-client/components/assistant-dock.d.ts +74 -0
- package/dist-client/components/assistant-dock.js +641 -0
- package/dist-client/components/assistant-dock.js.map +1 -0
- package/dist-client/components/assistant-mode.d.ts +6 -0
- package/dist-client/components/assistant-mode.js.map +1 -1
- package/dist-client/components/assistant-session-manager.d.ts +77 -0
- package/dist-client/components/assistant-session-manager.js +652 -0
- package/dist-client/components/assistant-session-manager.js.map +1 -0
- package/dist-client/components/chat-echo-dedup.js +4 -0
- package/dist-client/components/chat-echo-dedup.js.map +1 -1
- package/dist-client/components/chat-input-builder.d.ts +2 -0
- package/dist-client/components/chat-input-builder.js +2 -1
- package/dist-client/components/chat-input-builder.js.map +1 -1
- package/dist-client/components/panel-aria.test.js +12 -8
- package/dist-client/components/panel-aria.test.js.map +1 -1
- package/dist-client/index.d.ts +8 -0
- package/dist-client/index.js +8 -0
- package/dist-client/index.js.map +1 -1
- package/dist-client/setup-assistant-dock.d.ts +15 -0
- package/dist-client/setup-assistant-dock.js +110 -0
- package/dist-client/setup-assistant-dock.js.map +1 -0
- package/dist-client/tsconfig.tsbuildinfo +1 -1
- package/dist-client/utils/assistant-activity.d.ts +22 -0
- package/dist-client/utils/assistant-activity.js +104 -0
- package/dist-client/utils/assistant-activity.js.map +1 -0
- package/dist-client/utils/assistant-ask.d.ts +23 -0
- package/dist-client/utils/assistant-ask.js +18 -0
- package/dist-client/utils/assistant-ask.js.map +1 -0
- package/dist-client/utils/assistant-proposals.d.ts +29 -0
- package/dist-client/utils/assistant-proposals.js +22 -0
- package/dist-client/utils/assistant-proposals.js.map +1 -0
- package/dist-client/utils/assistant-session-actions.d.ts +12 -0
- package/dist-client/utils/assistant-session-actions.js +19 -0
- package/dist-client/utils/assistant-session-actions.js.map +1 -0
- package/dist-client/utils/assistant-session-admin.d.ts +72 -0
- package/dist-client/utils/assistant-session-admin.js +81 -0
- package/dist-client/utils/assistant-session-admin.js.map +1 -0
- package/dist-client/utils/assistant-session-controller.d.ts +2 -0
- package/dist-client/utils/assistant-session-controller.js.map +1 -1
- package/dist-client/utils/assistant-session-transport.js +6 -2
- package/dist-client/utils/assistant-session-transport.js.map +1 -1
- package/dist-client/utils/assistant-surface.d.ts +72 -0
- package/dist-client/utils/assistant-surface.js +99 -0
- package/dist-client/utils/assistant-surface.js.map +1 -0
- package/dist-client/utils/attachment-policy.d.ts +35 -0
- package/dist-client/utils/attachment-policy.js +56 -0
- package/dist-client/utils/attachment-policy.js.map +1 -0
- package/dist-server/service/assistant-chat-resolver.d.ts +1 -0
- package/dist-server/service/assistant-chat-resolver.js +71 -3
- package/dist-server/service/assistant-chat-resolver.js.map +1 -1
- package/dist-server/service/assistant-mode/assistant-mode-resolver.d.ts +1 -0
- package/dist-server/service/assistant-mode/assistant-mode-resolver.js +7 -0
- package/dist-server/service/assistant-mode/assistant-mode-resolver.js.map +1 -1
- package/dist-server/service/assistant-mode/resolve.d.ts +3 -0
- package/dist-server/service/assistant-mode/resolve.js +6 -2
- package/dist-server/service/assistant-mode/resolve.js.map +1 -1
- package/dist-server/service/assistant-mode/types.d.ts +6 -0
- package/dist-server/service/assistant-mode/types.js +0 -9
- package/dist-server/service/assistant-mode/types.js.map +1 -1
- package/dist-server/service/chat-message/chat-message.d.ts +6 -0
- package/dist-server/service/chat-message/chat-message.js +19 -0
- package/dist-server/service/chat-message/chat-message.js.map +1 -1
- package/dist-server/service/chat-session/attachment-policy.d.ts +44 -0
- package/dist-server/service/chat-session/attachment-policy.js +56 -0
- package/dist-server/service/chat-session/attachment-policy.js.map +1 -0
- package/dist-server/service/chat-session/attachment-route.d.ts +3 -0
- package/dist-server/service/chat-session/attachment-route.js +44 -0
- package/dist-server/service/chat-session/attachment-route.js.map +1 -0
- package/dist-server/service/chat-session/attachment-tools.d.ts +3 -0
- package/dist-server/service/chat-session/attachment-tools.js +59 -0
- package/dist-server/service/chat-session/attachment-tools.js.map +1 -0
- package/dist-server/service/chat-session/session-attachments.d.ts +36 -0
- package/dist-server/service/chat-session/session-attachments.js +84 -0
- package/dist-server/service/chat-session/session-attachments.js.map +1 -0
- package/dist-server/service/chat-session/session-inbox.d.ts +29 -0
- package/dist-server/service/chat-session/session-inbox.js +32 -8
- package/dist-server/service/chat-session/session-inbox.js.map +1 -1
- package/dist-server/service/chat-session/session-purge.d.ts +14 -0
- package/dist-server/service/chat-session/session-purge.js +77 -0
- package/dist-server/service/chat-session/session-purge.js.map +1 -0
- package/dist-server/service/chat-session/session-retention.d.ts +6 -0
- package/dist-server/service/chat-session/session-retention.js +20 -0
- package/dist-server/service/chat-session/session-retention.js.map +1 -0
- package/dist-server/service/chat-session/session-visibility.d.ts +8 -0
- package/dist-server/service/chat-session/session-visibility.js +11 -0
- package/dist-server/service/chat-session/session-visibility.js.map +1 -1
- package/dist-server/service/chat-session/session-write-gate.d.ts +11 -0
- package/dist-server/service/chat-session/session-write-gate.js +24 -0
- package/dist-server/service/chat-session/session-write-gate.js.map +1 -0
- package/dist-server/service/chat-session-participant/invite-notification.d.ts +1 -1
- package/dist-server/service/chat-session-participant/invite-notification.js +21 -6
- package/dist-server/service/chat-session-participant/invite-notification.js.map +1 -1
- package/dist-server/service/chat-session-participant/participant-lookup-roles.d.ts +3 -0
- package/dist-server/service/chat-session-participant/participant-lookup-roles.js +10 -0
- package/dist-server/service/chat-session-participant/participant-lookup-roles.js.map +1 -0
- package/dist-server/service/chat-session-participant/participant-lookup.d.ts +2 -0
- package/dist-server/service/chat-session-participant/participant-lookup.js +26 -0
- package/dist-server/service/chat-session-participant/participant-lookup.js.map +1 -0
- package/dist-server/service/chat-session-resolver.d.ts +17 -2
- package/dist-server/service/chat-session-resolver.js +135 -15
- package/dist-server/service/chat-session-resolver.js.map +1 -1
- package/dist-server/service/index.d.ts +5 -0
- package/dist-server/service/index.js +5 -0
- package/dist-server/service/index.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +9 -2
- package/server/service/assistant-chat-resolver.ts +71 -4
- package/server/service/assistant-mode/assistant-mode-resolver.ts +6 -0
- package/server/service/assistant-mode/resolve.ts +9 -2
- package/server/service/assistant-mode/types.ts +6 -0
- package/server/service/chat-message/chat-message.ts +17 -0
- package/server/service/chat-session/attachment-policy.test.ts +42 -0
- package/server/service/chat-session/attachment-policy.ts +68 -0
- package/server/service/chat-session/attachment-route.ts +45 -0
- package/server/service/chat-session/attachment-tools.ts +63 -0
- package/server/service/chat-session/session-attachments.ts +89 -0
- package/server/service/chat-session/session-inbox.test.ts +71 -1
- package/server/service/chat-session/session-inbox.ts +61 -11
- package/server/service/chat-session/session-purge.test.ts +24 -0
- package/server/service/chat-session/session-purge.ts +81 -0
- package/server/service/chat-session/session-retention.ts +17 -0
- package/server/service/chat-session/session-visibility.ts +11 -0
- package/server/service/chat-session/session-write-gate.test.ts +53 -0
- package/server/service/chat-session/session-write-gate.ts +31 -0
- package/server/service/chat-session-participant/invite-notification.test.ts +15 -0
- package/server/service/chat-session-participant/invite-notification.ts +24 -6
- package/server/service/chat-session-participant/participant-lookup-roles.ts +6 -0
- package/server/service/chat-session-participant/participant-lookup.ts +22 -0
- package/server/service/chat-session-resolver.ts +130 -13
- package/server/service/index.ts +5 -0
- package/test/assistant-dock.test.ts +118 -0
- package/test/assistant-session-manager.test.ts +126 -0
- package/test/attachment-policy-agree.test.ts +32 -0
- package/test/open-doors.test.ts +5 -2
- package/translations/en.json +61 -1
- package/translations/ja.json +61 -1
- package/translations/ko.json +61 -1
- package/translations/ms.json +61 -1
- package/translations/zh.json +61 -1
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** The row a conversation hangs on - its session anchor (ADR-0072 decision 6). */
|
|
2
|
+
export interface AssistantAnchor {
|
|
3
|
+
anchorType: string;
|
|
4
|
+
anchorId: string;
|
|
5
|
+
}
|
|
6
|
+
/** No anchor could stand - said to the person as a fact and what to do. */
|
|
7
|
+
export interface AssistantStuck {
|
|
8
|
+
stuck: string;
|
|
9
|
+
message: string;
|
|
10
|
+
}
|
|
11
|
+
export type AnchorResult = AssistantAnchor | AssistantStuck;
|
|
12
|
+
export declare function isAnchor(result: AnchorResult | undefined): result is AssistantAnchor;
|
|
13
|
+
/** For a surface that authors a board - the chat gets the board, the dock applies its patches. */
|
|
14
|
+
export interface BoardSurface {
|
|
15
|
+
currentBoard?: () => any;
|
|
16
|
+
boardProvider?: () => any;
|
|
17
|
+
selectedRefids?: () => number[];
|
|
18
|
+
knownTypes?: () => string[];
|
|
19
|
+
categories?: () => any[];
|
|
20
|
+
componentSchemas?: () => any;
|
|
21
|
+
searchProvider?: (query: string) => any[];
|
|
22
|
+
applyPatch(detail: any): Promise<{
|
|
23
|
+
applied: number;
|
|
24
|
+
missed: number;
|
|
25
|
+
note?: string;
|
|
26
|
+
}> | {
|
|
27
|
+
applied: number;
|
|
28
|
+
missed: number;
|
|
29
|
+
note?: string;
|
|
30
|
+
};
|
|
31
|
+
revertPatch?(patchId: string): Promise<void> | void;
|
|
32
|
+
applyAction?(detail: any): Promise<void> | void;
|
|
33
|
+
/** The chat door for board authoring, until board-ai joins the neutral door (ADR-0061 decision 0-1). */
|
|
34
|
+
chatEndpoint?: 'boardAIChat' | 'assistantChat';
|
|
35
|
+
}
|
|
36
|
+
export interface AssistantSurface {
|
|
37
|
+
/** Identity - a different key is a different conversation. */
|
|
38
|
+
key: string;
|
|
39
|
+
/** Matched against the server's mode `subjects` (assistantModes(subject)). */
|
|
40
|
+
subject: string;
|
|
41
|
+
/** The session anchor, or why none could stand. May ask the server (a row uuid, a domain id). */
|
|
42
|
+
anchor(): Promise<AnchorResult> | AnchorResult;
|
|
43
|
+
/** Words for the header - never a raw identifier. */
|
|
44
|
+
label(): string;
|
|
45
|
+
detail?(): string;
|
|
46
|
+
icon?: string;
|
|
47
|
+
/** Read at the moment of sending - never cached, so a draft cannot go stale. */
|
|
48
|
+
hostContext?(): Record<string, unknown>;
|
|
49
|
+
board?: BoardSurface;
|
|
50
|
+
/** The dock opened another conversation for this surface - e.g. the board modeller records its direct edits under it. */
|
|
51
|
+
sessionChanged?(sessionId: string): void;
|
|
52
|
+
}
|
|
53
|
+
type Listener = () => void;
|
|
54
|
+
/** An editor with a draft says it is on screen. The last one provided wins until it is cleared. */
|
|
55
|
+
export declare function provideAssistantSurface(owner: object, surface: AssistantSurface): void;
|
|
56
|
+
/** The editor is gone or inactive. A later provider that replaced it is left alone. */
|
|
57
|
+
export declare function clearAssistantSurface(owner: object): void;
|
|
58
|
+
/** The editor's draft or identity changed - the dock reads it again. */
|
|
59
|
+
export declare function notifyAssistantSurface(owner: object): void;
|
|
60
|
+
/** How a page's `context.subject` of this type becomes a surface - declared once by the app. */
|
|
61
|
+
export declare function registerSubjectSurface(type: string, make: (subject: {
|
|
62
|
+
type: string;
|
|
63
|
+
id?: string;
|
|
64
|
+
}) => AssistantSurface): void;
|
|
65
|
+
/** The app's own conversation when the screen shows nothing in particular - a factory, a site, a catalog. */
|
|
66
|
+
export declare function registerAssistantHome(surface: AssistantSurface): void;
|
|
67
|
+
export declare function subscribeAssistantSurface(listener: Listener): () => void;
|
|
68
|
+
/** What the dock talks about now: a provided editor, else the page's subject, else the app's home. */
|
|
69
|
+
export declare function currentAssistantSurface(): AssistantSurface | undefined;
|
|
70
|
+
/** The app's home surface - for the header's "back to the app's conversation". */
|
|
71
|
+
export declare function assistantHomeSurface(): AssistantSurface | undefined;
|
|
72
|
+
export {};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What the screen shows - the one way a screen tells the AI dock (design/ai/shared-dock.md §3).
|
|
3
|
+
*
|
|
4
|
+
* Before this there were five ways: `context.subject` (warehouse), `BoardEditHost` (twin), `StationAITarget`
|
|
5
|
+
* (plant), window events (figure) and the board modeller's own panel. The dock now reads one answer:
|
|
6
|
+
*
|
|
7
|
+
* 1. an editor that holds a draft provides a surface provideAssistantSurface(owner, surface)
|
|
8
|
+
* 2. a page that shows one thing says so in its context get context() { return { subject: { type, id } } }
|
|
9
|
+
* and the app says once how such a subject becomes a surface registerSubjectSurface(type, make)
|
|
10
|
+
* 3. otherwise the app's home registerAssistantHome(surface)
|
|
11
|
+
*
|
|
12
|
+
* The first that answers wins. The dock follows changes through `subscribeAssistantSurface`.
|
|
13
|
+
*/
|
|
14
|
+
import { store } from '@operato/shell';
|
|
15
|
+
export function isAnchor(result) {
|
|
16
|
+
return !!result && 'anchorId' in result && !!result.anchorId;
|
|
17
|
+
}
|
|
18
|
+
const provided = new Map();
|
|
19
|
+
let lastOwner;
|
|
20
|
+
const subjectMakers = new Map();
|
|
21
|
+
let home;
|
|
22
|
+
const listeners = new Set();
|
|
23
|
+
function changed() {
|
|
24
|
+
listeners.forEach(listener => {
|
|
25
|
+
try {
|
|
26
|
+
listener();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
/* one listener's error does not stop the others */
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** An editor with a draft says it is on screen. The last one provided wins until it is cleared. */
|
|
34
|
+
export function provideAssistantSurface(owner, surface) {
|
|
35
|
+
provided.set(owner, surface);
|
|
36
|
+
lastOwner = owner;
|
|
37
|
+
changed();
|
|
38
|
+
}
|
|
39
|
+
/** The editor is gone or inactive. A later provider that replaced it is left alone. */
|
|
40
|
+
export function clearAssistantSurface(owner) {
|
|
41
|
+
if (!provided.delete(owner))
|
|
42
|
+
return;
|
|
43
|
+
if (lastOwner === owner)
|
|
44
|
+
lastOwner = [...provided.keys()].pop();
|
|
45
|
+
changed();
|
|
46
|
+
}
|
|
47
|
+
/** The editor's draft or identity changed - the dock reads it again. */
|
|
48
|
+
export function notifyAssistantSurface(owner) {
|
|
49
|
+
if (provided.has(owner))
|
|
50
|
+
changed();
|
|
51
|
+
}
|
|
52
|
+
/** How a page's `context.subject` of this type becomes a surface - declared once by the app. */
|
|
53
|
+
export function registerSubjectSurface(type, make) {
|
|
54
|
+
subjectMakers.set(type, make);
|
|
55
|
+
changed();
|
|
56
|
+
}
|
|
57
|
+
/** The app's own conversation when the screen shows nothing in particular - a factory, a site, a catalog. */
|
|
58
|
+
export function registerAssistantHome(surface) {
|
|
59
|
+
home = surface;
|
|
60
|
+
changed();
|
|
61
|
+
}
|
|
62
|
+
export function subscribeAssistantSurface(listener) {
|
|
63
|
+
listeners.add(listener);
|
|
64
|
+
return () => listeners.delete(listener);
|
|
65
|
+
}
|
|
66
|
+
let pageSubjectKey = '';
|
|
67
|
+
let pageSurface;
|
|
68
|
+
function surfaceFromPage() {
|
|
69
|
+
const subject = store.getState()?.route?.context?.subject;
|
|
70
|
+
const type = subject?.type;
|
|
71
|
+
const make = type ? subjectMakers.get(type) : undefined;
|
|
72
|
+
if (!make)
|
|
73
|
+
return undefined;
|
|
74
|
+
const key = JSON.stringify([type, subject?.id ?? '']);
|
|
75
|
+
if (key !== pageSubjectKey) {
|
|
76
|
+
pageSubjectKey = key;
|
|
77
|
+
pageSurface = make({ type, id: subject?.id });
|
|
78
|
+
}
|
|
79
|
+
return pageSurface;
|
|
80
|
+
}
|
|
81
|
+
/** What the dock talks about now: a provided editor, else the page's subject, else the app's home. */
|
|
82
|
+
export function currentAssistantSurface() {
|
|
83
|
+
return (lastOwner && provided.get(lastOwner)) || surfaceFromPage() || home;
|
|
84
|
+
}
|
|
85
|
+
/** The app's home surface - for the header's "back to the app's conversation". */
|
|
86
|
+
export function assistantHomeSurface() {
|
|
87
|
+
return home;
|
|
88
|
+
}
|
|
89
|
+
/* The page context lives in the store; a page change is a surface change. */
|
|
90
|
+
let lastRouteSubject = '';
|
|
91
|
+
store.subscribe(() => {
|
|
92
|
+
const subject = store.getState()?.route?.context?.subject;
|
|
93
|
+
const key = JSON.stringify([subject?.type ?? '', subject?.id ?? '']);
|
|
94
|
+
if (key !== lastRouteSubject) {
|
|
95
|
+
lastRouteSubject = key;
|
|
96
|
+
changed();
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
//# sourceMappingURL=assistant-surface.js.map
|
|
@@ -0,0 +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;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AA;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\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"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type AttachmentKind = 'image' | 'text';
|
|
2
|
+
export interface AttachmentPolicy {
|
|
3
|
+
kinds: AttachmentKind[];
|
|
4
|
+
maxBytes?: number;
|
|
5
|
+
maxFiles?: number;
|
|
6
|
+
}
|
|
7
|
+
export declare const DEFAULT_MAX_BYTES: number;
|
|
8
|
+
export declare const DEFAULT_MAX_FILES = 5;
|
|
9
|
+
export declare function attachmentKindOf(file: {
|
|
10
|
+
type?: string;
|
|
11
|
+
name?: string;
|
|
12
|
+
}): AttachmentKind | null;
|
|
13
|
+
export type AttachmentRefusal = {
|
|
14
|
+
code: 'attachments-not-accepted';
|
|
15
|
+
} | {
|
|
16
|
+
code: 'attachment-kind-not-accepted';
|
|
17
|
+
name: string;
|
|
18
|
+
kinds: AttachmentKind[];
|
|
19
|
+
} | {
|
|
20
|
+
code: 'attachment-too-large';
|
|
21
|
+
name: string;
|
|
22
|
+
maxBytes: number;
|
|
23
|
+
} | {
|
|
24
|
+
code: 'too-many-attachments';
|
|
25
|
+
maxFiles: number;
|
|
26
|
+
};
|
|
27
|
+
export declare function refuseAttachments(policy: AttachmentPolicy | null | undefined, files: {
|
|
28
|
+
name?: string;
|
|
29
|
+
type?: string;
|
|
30
|
+
size?: number;
|
|
31
|
+
}[]): AttachmentRefusal | null;
|
|
32
|
+
/** The file picker's `accept` for a policy. */
|
|
33
|
+
export declare function acceptOf(policy: AttachmentPolicy | null | undefined): string;
|
|
34
|
+
/** Where a conversation's file opens - the gated route, under the page's domain path. */
|
|
35
|
+
export declare function chatAttachmentUrl(sessionId: string, attachmentId: string): string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What a conversation accepts as attachments - the screen's copy of the server rule
|
|
3
|
+
* (server/service/chat-session/attachment-policy.ts, design/ai/shared-dock.md §9-1).
|
|
4
|
+
*
|
|
5
|
+
* The screen checks first so the person hears "no" before anything is sent; the door checks again and is
|
|
6
|
+
* the authority. `test/attachment-policy-agree.test.ts` runs both copies over one table so they cannot drift.
|
|
7
|
+
*/
|
|
8
|
+
export const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
|
|
9
|
+
export const DEFAULT_MAX_FILES = 5;
|
|
10
|
+
const TEXT_TYPES = ['text/plain', 'text/csv', 'text/markdown', 'application/json'];
|
|
11
|
+
const TEXT_EXTENSIONS = ['.txt', '.csv', '.md', '.json'];
|
|
12
|
+
export function attachmentKindOf(file) {
|
|
13
|
+
const type = (file.type || '').toLowerCase();
|
|
14
|
+
if (type.startsWith('image/'))
|
|
15
|
+
return 'image';
|
|
16
|
+
if (TEXT_TYPES.includes(type))
|
|
17
|
+
return 'text';
|
|
18
|
+
const name = (file.name || '').toLowerCase();
|
|
19
|
+
if (TEXT_EXTENSIONS.some(ext => name.endsWith(ext)))
|
|
20
|
+
return 'text';
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
export function refuseAttachments(policy, files) {
|
|
24
|
+
if (!files.length)
|
|
25
|
+
return null;
|
|
26
|
+
if (!policy || !policy.kinds?.length)
|
|
27
|
+
return { code: 'attachments-not-accepted' };
|
|
28
|
+
const maxFiles = policy.maxFiles ?? DEFAULT_MAX_FILES;
|
|
29
|
+
if (files.length > maxFiles)
|
|
30
|
+
return { code: 'too-many-attachments', maxFiles };
|
|
31
|
+
const maxBytes = policy.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
const kind = attachmentKindOf(file);
|
|
34
|
+
if (!kind || !policy.kinds.includes(kind)) {
|
|
35
|
+
return { code: 'attachment-kind-not-accepted', name: file.name || '', kinds: policy.kinds };
|
|
36
|
+
}
|
|
37
|
+
if ((file.size ?? 0) > maxBytes)
|
|
38
|
+
return { code: 'attachment-too-large', name: file.name || '', maxBytes };
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
/** The file picker's `accept` for a policy. */
|
|
43
|
+
export function acceptOf(policy) {
|
|
44
|
+
const accept = [];
|
|
45
|
+
if (policy?.kinds?.includes('image'))
|
|
46
|
+
accept.push('image/*');
|
|
47
|
+
if (policy?.kinds?.includes('text'))
|
|
48
|
+
accept.push(...TEXT_EXTENSIONS, ...TEXT_TYPES);
|
|
49
|
+
return accept.join(',');
|
|
50
|
+
}
|
|
51
|
+
/** Where a conversation's file opens - the gated route, under the page's domain path. */
|
|
52
|
+
export function chatAttachmentUrl(sessionId, attachmentId) {
|
|
53
|
+
const domainPath = /^\/domain\/[^/]+/.exec(location.pathname)?.[0] ?? '';
|
|
54
|
+
return `${domainPath}/chat-attachments/${encodeURIComponent(sessionId)}/${encodeURIComponent(attachmentId)}`;
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=attachment-policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachment-policy.js","sourceRoot":"","sources":["../../client/utils/attachment-policy.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAAG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AAS,CAAC,IAAI,kBAAkB,CAAC,YAAY,CAAC,EAAE,CAAA;AAC9G,CAAC","sourcesContent":["/*\n * What a conversation accepts as attachments - the screen's copy of the server rule\n * (server/service/chat-session/attachment-policy.ts, design/ai/shared-dock.md §9-1).\n *\n * The screen checks first so the person hears \"no\" before anything is sent; the door checks again and is\n * the authority. `test/attachment-policy-agree.test.ts` runs both copies over one table so they cannot drift.\n */\n\nexport type AttachmentKind = 'image' | 'text'\n\nexport interface AttachmentPolicy {\n kinds: AttachmentKind[]\n maxBytes?: number\n maxFiles?: number\n}\n\nexport const DEFAULT_MAX_BYTES = 5 * 1024 * 1024\nexport const DEFAULT_MAX_FILES = 5\n\nconst TEXT_TYPES = ['text/plain', 'text/csv', 'text/markdown', 'application/json']\nconst TEXT_EXTENSIONS = ['.txt', '.csv', '.md', '.json']\n\nexport function attachmentKindOf(file: { type?: string; name?: string }): AttachmentKind | null {\n const type = (file.type || '').toLowerCase()\n if (type.startsWith('image/')) return 'image'\n if (TEXT_TYPES.includes(type)) return 'text'\n const name = (file.name || '').toLowerCase()\n if (TEXT_EXTENSIONS.some(ext => name.endsWith(ext))) return 'text'\n return null\n}\n\nexport type AttachmentRefusal =\n | { code: 'attachments-not-accepted' }\n | { code: 'attachment-kind-not-accepted'; name: string; kinds: AttachmentKind[] }\n | { code: 'attachment-too-large'; name: string; maxBytes: number }\n | { code: 'too-many-attachments'; maxFiles: number }\n\nexport function refuseAttachments(\n policy: AttachmentPolicy | null | undefined,\n files: { name?: string; type?: string; size?: number }[]\n): AttachmentRefusal | null {\n if (!files.length) return null\n if (!policy || !policy.kinds?.length) return { code: 'attachments-not-accepted' }\n\n const maxFiles = policy.maxFiles ?? DEFAULT_MAX_FILES\n if (files.length > maxFiles) return { code: 'too-many-attachments', maxFiles }\n\n const maxBytes = policy.maxBytes ?? DEFAULT_MAX_BYTES\n for (const file of files) {\n const kind = attachmentKindOf(file)\n if (!kind || !policy.kinds.includes(kind)) {\n return { code: 'attachment-kind-not-accepted', name: file.name || '', kinds: policy.kinds }\n }\n if ((file.size ?? 0) > maxBytes) return { code: 'attachment-too-large', name: file.name || '', maxBytes }\n }\n return null\n}\n\n/** The file picker's `accept` for a policy. */\nexport function acceptOf(policy: AttachmentPolicy | null | undefined): string {\n const accept: string[] = []\n if (policy?.kinds?.includes('image')) accept.push('image/*')\n if (policy?.kinds?.includes('text')) accept.push(...TEXT_EXTENSIONS, ...TEXT_TYPES)\n return accept.join(',')\n}\n\n/** Where a conversation's file opens - the gated route, under the page's domain path. */\nexport function chatAttachmentUrl(sessionId: string, attachmentId: string): string {\n const domainPath = /^\\/domain\\/[^/]+/.exec(location.pathname)?.[0] ?? ''\n return `${domainPath}/chat-attachments/${encodeURIComponent(sessionId)}/${encodeURIComponent(attachmentId)}`\n}\n"]}
|
|
@@ -49,6 +49,11 @@ const session_kind_js_1 = require("./chat-session/session-kind.js");
|
|
|
49
49
|
const reader_gate_js_1 = require("./chat-message/reader-gate.js");
|
|
50
50
|
const mention_invite_js_1 = require("./chat-session-participant/mention-invite.js");
|
|
51
51
|
const invite_notification_js_1 = require("./chat-session-participant/invite-notification.js");
|
|
52
|
+
const participant_lookup_js_1 = require("./chat-session-participant/participant-lookup.js");
|
|
53
|
+
const session_write_gate_js_1 = require("./chat-session/session-write-gate.js");
|
|
54
|
+
const attachment_policy_js_1 = require("./chat-session/attachment-policy.js");
|
|
55
|
+
const session_attachments_js_1 = require("./chat-session/session-attachments.js");
|
|
56
|
+
const registry_js_1 = require("./assistant-mode/registry.js");
|
|
52
57
|
const resolve_js_1 = require("./assistant-mode/resolve.js");
|
|
53
58
|
const request_translator_js_1 = require("./request-translator.js");
|
|
54
59
|
/**
|
|
@@ -123,6 +128,13 @@ tslib_1.__decorate([
|
|
|
123
128
|
}),
|
|
124
129
|
tslib_1.__metadata("design:type", String)
|
|
125
130
|
], AssistantChatInput.prototype, "truncateAfterMessageId", void 0);
|
|
131
|
+
tslib_1.__decorate([
|
|
132
|
+
(0, type_graphql_1.Field)(() => [String], {
|
|
133
|
+
nullable: true,
|
|
134
|
+
description: 'Files stored with this conversation by attachToConversation, sent with this turn.'
|
|
135
|
+
}),
|
|
136
|
+
tslib_1.__metadata("design:type", Array)
|
|
137
|
+
], AssistantChatInput.prototype, "attachmentIds", void 0);
|
|
126
138
|
AssistantChatInput = tslib_1.__decorate([
|
|
127
139
|
(0, type_graphql_1.InputType)({ description: 'One turn of a conversation that has no document of its own.' })
|
|
128
140
|
], AssistantChatInput);
|
|
@@ -222,6 +234,16 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
222
234
|
const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } });
|
|
223
235
|
if (!found)
|
|
224
236
|
throw new Error(`ChatSession ${input.sessionId} not found`);
|
|
237
|
+
/*
|
|
238
|
+
* A private conversation is written by its people only - and here more than anywhere: the answer is
|
|
239
|
+
* built on this conversation's history, so an outsider's question would read it back to them.
|
|
240
|
+
*/
|
|
241
|
+
await (0, session_write_gate_js_1.assertMayWriteSession)({
|
|
242
|
+
session: found,
|
|
243
|
+
userId: user?.id,
|
|
244
|
+
isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, found.id, user?.id),
|
|
245
|
+
t: (key, options) => t(key, options)
|
|
246
|
+
});
|
|
225
247
|
if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {
|
|
226
248
|
throw new Error(context.t('ai-assistant.text.other-figure-history', {
|
|
227
249
|
defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'
|
|
@@ -253,6 +275,25 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
253
275
|
(0, station_session_guard_js_1.assertStationSession)(session, input.hostContext, t);
|
|
254
276
|
const lastUserMessage = input.messages[input.messages.length - 1];
|
|
255
277
|
let userMessageId;
|
|
278
|
+
/*
|
|
279
|
+
* Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by
|
|
280
|
+
* attachToConversation; one that is not this conversation's is refused, never read. The policy is the
|
|
281
|
+
* mode's - checked again here, since the door is the authority, not the screen.
|
|
282
|
+
*/
|
|
283
|
+
const attachmentRows = [];
|
|
284
|
+
if (input.attachmentIds?.length) {
|
|
285
|
+
if (!session)
|
|
286
|
+
throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }));
|
|
287
|
+
for (const id of input.attachmentIds) {
|
|
288
|
+
const row = await (0, session_attachments_js_1.findChatAttachment)(domain.id, session.id, id);
|
|
289
|
+
if (!row)
|
|
290
|
+
throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }));
|
|
291
|
+
attachmentRows.push(row);
|
|
292
|
+
}
|
|
293
|
+
const refusal = (0, attachment_policy_js_1.refuseAttachments)((0, registry_js_1.getAssistantMode)(input.mode.kind)?.attachments, attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) })));
|
|
294
|
+
if (refusal)
|
|
295
|
+
throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...refusal, defaultValue: refusal.code }));
|
|
296
|
+
}
|
|
256
297
|
if (session && lastUserMessage?.role === 'user') {
|
|
257
298
|
const previousLast = await messageRepo.findOne({
|
|
258
299
|
where: { session: { id: session.id } },
|
|
@@ -268,6 +309,7 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
268
309
|
* from the request — two sources for one fact can disagree.
|
|
269
310
|
*/
|
|
270
311
|
addressee: 'assistant',
|
|
312
|
+
attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(session_attachments_js_1.describeAttachment)) : undefined,
|
|
271
313
|
creator: user,
|
|
272
314
|
updater: user,
|
|
273
315
|
parentMessage: previousLast ? { id: previousLast.id } : undefined
|
|
@@ -300,7 +342,7 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
300
342
|
visibility: session.visibility
|
|
301
343
|
});
|
|
302
344
|
if (invite.invited.length > 0) {
|
|
303
|
-
const payload = (0, invite_notification_js_1.buildInviteNotification)(invite.invited, undefined, user);
|
|
345
|
+
const payload = (0, invite_notification_js_1.buildInviteNotification)(invite.invited, undefined, user, session?.name);
|
|
304
346
|
try {
|
|
305
347
|
if (payload)
|
|
306
348
|
await context.state?.notify?.(payload);
|
|
@@ -356,7 +398,13 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
356
398
|
storedRows.map(message => ({
|
|
357
399
|
id: message.id,
|
|
358
400
|
role: message.role,
|
|
359
|
-
|
|
401
|
+
/*
|
|
402
|
+
* A file sent in an earlier turn is not sent again - one line names it, and the model opens it
|
|
403
|
+
* with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
|
|
404
|
+
*/
|
|
405
|
+
content: message.id !== userMessageId && message.attachmentsJson?.length
|
|
406
|
+
? [message.content, ...message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine)].join('\n')
|
|
407
|
+
: message.content,
|
|
360
408
|
senderId: message.creator?.id,
|
|
361
409
|
senderName: message.creator?.name,
|
|
362
410
|
addressee: message.addressee
|
|
@@ -370,7 +418,27 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
370
418
|
: undefined
|
|
371
419
|
})
|
|
372
420
|
: input.messages.map(message => ({ role: message.role, content: message.content }));
|
|
373
|
-
if (
|
|
421
|
+
if (attachmentRows.length && conversation.length > 0) {
|
|
422
|
+
const last = conversation[conversation.length - 1];
|
|
423
|
+
if (last.role === 'user' && typeof last.content === 'string') {
|
|
424
|
+
const parts = [{ type: 'text', text: last.content }];
|
|
425
|
+
for (const row of attachmentRows) {
|
|
426
|
+
const file = await (0, session_attachments_js_1.attachmentForModel)(row);
|
|
427
|
+
if (file.type === 'image') {
|
|
428
|
+
parts.push({ type: 'image', source: { kind: 'base64', data: file.data, mediaType: file.mediaType } });
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
parts.push({
|
|
432
|
+
type: 'text',
|
|
433
|
+
text: `[attachment ${row.id}: ${file.name}${file.truncated ? ' - cut, the file is longer' : ''}]\n${file.text}`
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
last.content = parts;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
else if (input.hostContext?.image?.data && conversation.length > 0) {
|
|
441
|
+
/* The screen-image path (figure's rendered view) - not a file of the conversation. */
|
|
374
442
|
const last = conversation[conversation.length - 1];
|
|
375
443
|
if (last.role === 'user' && typeof last.content === 'string') {
|
|
376
444
|
const raw = input.hostContext.image;
|
|
@@ -1 +1 @@
|
|
|
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,4DAAiE;AACjE,mEAA2D;AAE3D;;;;;;GAMG;AACH,MAAM,qBAAqB,GAAG,EAAE,CAAA;AAGhC,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;CAM1B,CAAA;AAJC;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,6BAA6B,EAAE,CAAC;;mDAC1C;AAGZ;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,iBAAiB,EAAE,CAAC;;sDAC3B;AALX,qBAAqB;IAD1B,IAAA,wBAAS,GAAE;GACN,qBAAqB,CAM1B;AAGD,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;CAUvB,CAAA;AARC;IADC,IAAA,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;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;;0DAoT1D;gCArUU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CAsUjC","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 { 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}\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 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 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 creator: user,\n updater: user,\n parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined\n })\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)\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 content: 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 (input.hostContext?.image?.data && conversation.length > 0) {\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","s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AI,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI;YAC1E,YAAY,EAAE,MAAM,CAAC,YAAY;YACjC,SAAS,EAAE,MAAM,CAAC,IAAI,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"]}
|