@things-factory/ai-assistant 10.1.214 → 10.1.215

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 (69) hide show
  1. package/client/components/assistant-dock.ts +6 -3
  2. package/client/components/assistant-session-manager.ts +263 -12
  3. package/client/utils/assistant-session-actions.ts +12 -0
  4. package/client/utils/assistant-session-admin.ts +70 -5
  5. package/dist-client/components/assistant-dock.js +6 -3
  6. package/dist-client/components/assistant-dock.js.map +1 -1
  7. package/dist-client/components/assistant-session-manager.d.ts +37 -0
  8. package/dist-client/components/assistant-session-manager.js +281 -13
  9. package/dist-client/components/assistant-session-manager.js.map +1 -1
  10. package/dist-client/tsconfig.tsbuildinfo +1 -1
  11. package/dist-client/utils/assistant-session-actions.d.ts +15 -0
  12. package/dist-client/utils/assistant-session-actions.js +11 -0
  13. package/dist-client/utils/assistant-session-actions.js.map +1 -1
  14. package/dist-client/utils/assistant-session-admin.d.ts +32 -1
  15. package/dist-client/utils/assistant-session-admin.js +36 -5
  16. package/dist-client/utils/assistant-session-admin.js.map +1 -1
  17. package/dist-server/service/assistant-chat-resolver.js +1 -1
  18. package/dist-server/service/assistant-chat-resolver.js.map +1 -1
  19. package/dist-server/service/assistant-mode/index.d.ts +1 -1
  20. package/dist-server/service/assistant-mode/index.js +2 -1
  21. package/dist-server/service/assistant-mode/index.js.map +1 -1
  22. package/dist-server/service/assistant-mode/mode-categories.d.ts +15 -0
  23. package/dist-server/service/assistant-mode/mode-categories.js +7 -1
  24. package/dist-server/service/assistant-mode/mode-categories.js.map +1 -1
  25. package/dist-server/service/chat-session/session-cleanup.d.ts +28 -0
  26. package/dist-server/service/chat-session/session-cleanup.js +69 -0
  27. package/dist-server/service/chat-session/session-cleanup.js.map +1 -0
  28. package/dist-server/service/chat-session/session-inbox.d.ts +15 -0
  29. package/dist-server/service/chat-session/session-inbox.js +11 -0
  30. package/dist-server/service/chat-session/session-inbox.js.map +1 -1
  31. package/dist-server/service/chat-session/session-purge.d.ts +4 -0
  32. package/dist-server/service/chat-session/session-purge.js +45 -11
  33. package/dist-server/service/chat-session/session-purge.js.map +1 -1
  34. package/dist-server/service/chat-session-resolver.d.ts +24 -2
  35. package/dist-server/service/chat-session-resolver.js +193 -13
  36. package/dist-server/service/chat-session-resolver.js.map +1 -1
  37. package/dist-server/service/data-read/list-read.d.ts +3 -1
  38. package/dist-server/service/data-read/list-read.js +27 -2
  39. package/dist-server/service/data-read/list-read.js.map +1 -1
  40. package/dist-server/service/data-read/read-target.d.ts +16 -0
  41. package/dist-server/service/data-read/read-target.js +18 -1
  42. package/dist-server/service/data-read/read-target.js.map +1 -1
  43. package/dist-server/service/data-read/read-tools.js +3 -1
  44. package/dist-server/service/data-read/read-tools.js.map +1 -1
  45. package/dist-server/tsconfig.tsbuildinfo +1 -1
  46. package/package.json +6 -6
  47. package/server/service/assistant-chat-resolver.ts +2 -2
  48. package/server/service/assistant-mode/conversation-category.test.ts +15 -2
  49. package/server/service/assistant-mode/index.ts +1 -1
  50. package/server/service/assistant-mode/mode-categories.ts +17 -1
  51. package/server/service/assistant-mode/open-subject-door.test.ts +3 -1
  52. package/server/service/chat-session/session-cleanup.test.ts +83 -0
  53. package/server/service/chat-session/session-cleanup.ts +69 -0
  54. package/server/service/chat-session/session-inbox.ts +13 -0
  55. package/server/service/chat-session/session-purge.ts +46 -10
  56. package/server/service/chat-session-resolver.ts +150 -14
  57. package/server/service/data-read/list-read.ts +30 -3
  58. package/server/service/data-read/list-status.test.ts +46 -0
  59. package/server/service/data-read/read-target.ts +32 -1
  60. package/server/service/data-read/read-tools.ts +2 -1
  61. package/test/assistant-dock.test.ts +12 -1
  62. package/test/assistant-session-manager.test.ts +53 -1
  63. package/test/open-doors.test.ts +3 -1
  64. package/translations/en.json +37 -1
  65. package/translations/es.json +37 -1
  66. package/translations/ja.json +37 -1
  67. package/translations/ko.json +37 -1
  68. package/translations/ms.json +37 -1
  69. package/translations/zh.json +37 -1
@@ -11,3 +11,18 @@ export declare function sessionActions(entry: {
11
11
  setVisibility: boolean;
12
12
  leave: boolean;
13
13
  };
14
+ /**
15
+ * What a picked set of rows can have done to it at once - each row by the same hints as its own menu: delete the
16
+ * ones I started, leave the ones I am only in, hide any (2026-10-25, the user: 「멀티셀렉트로 한번에 지울 수 있게」).
17
+ */
18
+ export declare function bulkActions(entries: {
19
+ id: string;
20
+ participant?: boolean;
21
+ hidden?: boolean;
22
+ mine?: boolean;
23
+ owner?: boolean;
24
+ }[]): {
25
+ remove: string[];
26
+ leave: string[];
27
+ hide: string[];
28
+ };
@@ -18,4 +18,15 @@ export function sessionActions(entry) {
18
18
  leave: !!entry.participant && !entry.owner
19
19
  };
20
20
  }
21
+ /**
22
+ * What a picked set of rows can have done to it at once - each row by the same hints as its own menu: delete the
23
+ * ones I started, leave the ones I am only in, hide any (2026-10-25, the user: 「멀티셀렉트로 한번에 지울 수 있게」).
24
+ */
25
+ export function bulkActions(entries) {
26
+ return {
27
+ remove: entries.filter(entry => sessionActions(entry).remove).map(entry => entry.id),
28
+ leave: entries.filter(entry => !sessionActions(entry).remove && sessionActions(entry).leave).map(entry => entry.id),
29
+ hide: entries.filter(entry => sessionActions(entry).hide).map(entry => entry.id)
30
+ };
31
+ }
21
32
  //# sourceMappingURL=assistant-session-actions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-session-actions.js","sourceRoot":"","sources":["../../client/utils/assistant-session-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,KAAmF;IAChH,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,WAAW,KAAK,KAAK;QACnC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM;QACnB,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM;QACtB,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI;QACpB,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK;QAC5B,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,KAAK;KAC3C,CAAA;AACH,CAAC","sourcesContent":["/*\n * Which actions a row of the conversation list offers this viewer - pure, so the rule is tested alone.\n *\n * The same hints the server gives on each inbox entry; the doors decide again:\n * rename any participant (the name is the topic label; reversible)\n * hide/unhide anyone, for their own list only (reversible)\n * delete the creator (`mine`) (not reversible from a screen)\n * visibility the owner (`owner`) (opening shows what is already written)\n * leave a participant who is not the owner (the owner deletes or makes it private instead)\n */\nexport function sessionActions(entry: { participant?: boolean; hidden?: boolean; mine?: boolean; owner?: boolean }) {\n return {\n rename: entry.participant !== false,\n hide: !entry.hidden,\n unhide: !!entry.hidden,\n remove: !!entry.mine,\n setVisibility: !!entry.owner,\n leave: !!entry.participant && !entry.owner\n }\n}\n"]}
1
+ {"version":3,"file":"assistant-session-actions.js","sourceRoot":"","sources":["../../client/utils/assistant-session-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,KAAmF;IAChH,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,WAAW,KAAK,KAAK;QACnC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM;QACnB,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM;QACtB,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI;QACpB,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK;QAC5B,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,KAAK;KAC3C,CAAA;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAAmG;IAC7H,OAAO;QACL,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QACpF,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QACnH,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;KACjF,CAAA;AACH,CAAC","sourcesContent":["/*\n * Which actions a row of the conversation list offers this viewer - pure, so the rule is tested alone.\n *\n * The same hints the server gives on each inbox entry; the doors decide again:\n * rename any participant (the name is the topic label; reversible)\n * hide/unhide anyone, for their own list only (reversible)\n * delete the creator (`mine`) (not reversible from a screen)\n * visibility the owner (`owner`) (opening shows what is already written)\n * leave a participant who is not the owner (the owner deletes or makes it private instead)\n */\nexport function sessionActions(entry: { participant?: boolean; hidden?: boolean; mine?: boolean; owner?: boolean }) {\n return {\n rename: entry.participant !== false,\n hide: !entry.hidden,\n unhide: !!entry.hidden,\n remove: !!entry.mine,\n setVisibility: !!entry.owner,\n leave: !!entry.participant && !entry.owner\n }\n}\n\n/**\n * What a picked set of rows can have done to it at once - each row by the same hints as its own menu: delete the\n * ones I started, leave the ones I am only in, hide any (2026-10-25, the user: 「멀티셀렉트로 한번에 지울 수 있게」).\n */\nexport function bulkActions(entries: { id: string; participant?: boolean; hidden?: boolean; mine?: boolean; owner?: boolean }[]) {\n return {\n remove: entries.filter(entry => sessionActions(entry).remove).map(entry => entry.id),\n leave: entries.filter(entry => !sessionActions(entry).remove && sessionActions(entry).leave).map(entry => entry.id),\n hide: entries.filter(entry => sessionActions(entry).hide).map(entry => entry.id)\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- export { sessionActions } from './assistant-session-actions.js';
1
+ export { bulkActions, sessionActions } from './assistant-session-actions.js';
2
2
  /**
3
3
  * Managing the conversations on one anchor - list, rename, hide, delete, and who may read them.
4
4
  *
@@ -13,6 +13,7 @@ export { sessionActions } from './assistant-session-actions.js';
13
13
  * delete the creator (`mine`) (not reversible from a screen)
14
14
  * visibility the owner (`owner`) (opening shows what is already written)
15
15
  * leave a member, never the owner (in a group, leaving ends reading here)
16
+ * restore the creator, while it is kept (deleted ones are kept `deletedDays`, shared-dock.md §9-5)
16
17
  */
17
18
  /** Who reads it: everyone in the domain, the people the owner brought in, or the owner alone (ADR-0073 decision 3). */
18
19
  export type SessionVisibility = 'open' | 'group' | 'private';
@@ -33,6 +34,25 @@ export interface AssistantSessionEntry {
33
34
  /** Hidden from my own list (returned only with the hidden filter on). */
34
35
  hidden?: boolean;
35
36
  visibility?: SessionVisibility | string;
37
+ /** No activity for the archive period - out of the list until asked for or searched. */
38
+ archived?: boolean;
39
+ /** Why the list suggests clearing it (mine only): never asked anything, or idle for 30 days. */
40
+ cleanupReason?: 'empty' | 'inactive' | string;
41
+ /** Whole days since the last activity. */
42
+ idleDays?: number;
43
+ }
44
+ /** A conversation I deleted that is still kept - it can be brought back until `purgesAt`. */
45
+ export interface DeletedSessionEntry {
46
+ id: string;
47
+ name?: string;
48
+ kind?: string;
49
+ deletedAt: string;
50
+ purgesAt?: string;
51
+ }
52
+ /** How long conversations are kept; `null` when that keeping is off. */
53
+ export interface SessionKeeping {
54
+ deletedDays: number | null;
55
+ archiveDays: number | null;
36
56
  }
37
57
  /** Legacy single filter - kept for callers written before the filter set. */
38
58
  export type AssistantSessionFilter = 'all' | 'mine' | 'hidden';
@@ -44,6 +64,10 @@ export interface AssistantSessionFilters {
44
64
  visibility?: 'all' | SessionVisibility;
45
65
  includeHidden?: boolean;
46
66
  unreadOnly?: boolean;
67
+ /** Also the archived ones. */
68
+ includeArchived?: boolean;
69
+ /** Only my own the list suggests clearing - hidden and archived ones included. */
70
+ cleanupOnly?: boolean;
47
71
  }
48
72
  export interface AssistantSessionQuery {
49
73
  anchorType: string;
@@ -60,6 +84,11 @@ export interface AssistantSessionPage {
60
84
  total: number;
61
85
  /** How many I hid - so a hidden conversation is never forgotten. */
62
86
  hiddenCount: number;
87
+ /** How many are archived - the same, for the ones left idle. */
88
+ archivedCount: number;
89
+ /** How many of mine the list suggests clearing. */
90
+ cleanupCount: number;
91
+ keeping: SessionKeeping;
63
92
  }
64
93
  export interface AssistantSessionAdmin {
65
94
  inbox(query: AssistantSessionQuery): Promise<AssistantSessionPage>;
@@ -68,6 +97,8 @@ export interface AssistantSessionAdmin {
68
97
  remove(sessionId: string): Promise<boolean>;
69
98
  setVisibility(sessionId: string, visibility: SessionVisibility): Promise<boolean>;
70
99
  leave(sessionId: string): Promise<boolean>;
100
+ deleted(anchorType: string, anchorId: string): Promise<DeletedSessionEntry[]>;
101
+ restore(sessionId: string): Promise<boolean>;
71
102
  }
72
103
  /** The page size the server allows at most (`chatSessionInbox` clamps to 200). */
73
104
  export declare const SESSION_PAGE_MAX = 200;
@@ -1,7 +1,7 @@
1
1
  import { client } from '@operato/graphql';
2
2
  import { i18next } from '@operato/i18n';
3
3
  import gql from 'graphql-tag';
4
- export { sessionActions } from './assistant-session-actions.js';
4
+ export { bulkActions, sessionActions } from './assistant-session-actions.js';
5
5
  /** The page size the server allows at most (`chatSessionInbox` clamps to 200). */
6
6
  export const SESSION_PAGE_MAX = 200;
7
7
  async function mutate(mutation, variables, field) {
@@ -17,10 +17,13 @@ export const assistantSessionAdmin = {
17
17
  const mine = filters.whose ? filters.whose === 'mine' : filter === 'mine';
18
18
  const result = await client.query({
19
19
  query: gql `
20
- query ($t: String!, $i: String!, $h: Boolean, $q: String, $m: Boolean, $l: Int, $o: Int, $k: String, $p: Boolean, $v: String, $u: Boolean) {
20
+ query ($t: String!, $i: String!, $h: Boolean, $q: String, $m: Boolean, $l: Int, $o: Int, $k: String, $p: Boolean, $v: String, $u: Boolean, $a: Boolean, $c: Boolean) {
21
21
  hiddenSessionCount(anchorType: $t, anchorId: $i)
22
- chatSessionInboxTotal(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u)
23
- chatSessionInbox(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, limit: $l, offset: $o) {
22
+ archivedSessionCount(anchorType: $t, anchorId: $i)
23
+ cleanupSessionCount(anchorType: $t, anchorId: $i)
24
+ aiSessionKeeping { deletedDays archiveDays }
25
+ chatSessionInboxTotal(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, includeArchived: $a, cleanupOnly: $c)
26
+ chatSessionInbox(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, includeArchived: $a, cleanupOnly: $c, limit: $l, offset: $o) {
24
27
  id
25
28
  name
26
29
  kind
@@ -33,6 +36,9 @@ export const assistantSessionAdmin = {
33
36
  owner
34
37
  hidden
35
38
  visibility
39
+ archived
40
+ cleanupReason
41
+ idleDays
36
42
  }
37
43
  }
38
44
  `,
@@ -47,6 +53,8 @@ export const assistantSessionAdmin = {
47
53
  p: filters.whose === 'participant' || null,
48
54
  v: filters.visibility && filters.visibility !== 'all' ? filters.visibility : null,
49
55
  u: filters.unreadOnly || null,
56
+ a: filters.includeArchived || null,
57
+ c: filters.cleanupOnly || null,
50
58
  l: Math.min(SESSION_PAGE_MAX, Math.max(1, limit)),
51
59
  o: Math.max(0, offset)
52
60
  },
@@ -62,7 +70,13 @@ export const assistantSessionAdmin = {
62
70
  /* With the hidden filter the server returns hidden ones alongside the rest, marked - the total counts both. */
63
71
  entries,
64
72
  total: result.data?.chatSessionInboxTotal ?? entries.length,
65
- hiddenCount: result.data?.hiddenSessionCount ?? 0
73
+ hiddenCount: result.data?.hiddenSessionCount ?? 0,
74
+ archivedCount: result.data?.archivedSessionCount ?? 0,
75
+ cleanupCount: result.data?.cleanupSessionCount ?? 0,
76
+ keeping: {
77
+ deletedDays: result.data?.aiSessionKeeping?.deletedDays ?? null,
78
+ archiveDays: result.data?.aiSessionKeeping?.archiveDays ?? null
79
+ }
66
80
  };
67
81
  },
68
82
  rename(sessionId, name) {
@@ -79,6 +93,23 @@ export const assistantSessionAdmin = {
79
93
  },
80
94
  leave(sessionId) {
81
95
  return mutate(gql `mutation ($id: String!) { leaveAISession(sessionId: $id) }`, { id: sessionId }, 'leaveAISession');
96
+ },
97
+ async deleted(anchorType, anchorId) {
98
+ const result = await client.query({
99
+ query: gql `
100
+ query ($t: String!, $i: String!) {
101
+ deletedAISessions(anchorType: $t, anchorId: $i) { id name kind deletedAt purgesAt }
102
+ }
103
+ `,
104
+ variables: { t: anchorType, i: anchorId },
105
+ fetchPolicy: 'no-cache'
106
+ });
107
+ if (result.errors?.length)
108
+ throw new Error(result.errors[0].message);
109
+ return result.data?.deletedAISessions ?? [];
110
+ },
111
+ restore(sessionId) {
112
+ return mutate(gql `mutation ($id: String!) { restoreAISession(sessionId: $id) }`, { id: sessionId }, 'restoreAISession');
82
113
  }
83
114
  };
84
115
  //# sourceMappingURL=assistant-session-admin.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-session-admin.js","sourceRoot":"","sources":["../../client/utils/assistant-session-admin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AACvC,OAAO,GAAG,MAAM,aAAa,CAAA;AAE7B,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAgF/D,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAA;AAEnC,KAAK,UAAU,MAAM,CAAC,QAAa,EAAE,SAAkC,EAAE,KAAa;IACpF,MAAM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,EAAE,eAAe,CAAC,CAAA;IACvJ,CAAC;IAED,MAAM,CAAC,SAAS;QACd,OAAO,MAAM,CAAC,GAAG,CAAA,6DAA6D,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,iBAAiB,CAAC,CAAA;IACvH,CAAC;IAED,aAAa,CAAC,SAAS,EAAE,UAAU;QACjC,OAAO,MAAM,CACX,GAAG,CAAA,+FAA+F,EAClG,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,EAChC,sBAAsB,CACvB,CAAA;IACH,CAAC;IAED,KAAK,CAAC,SAAS;QACb,OAAO,MAAM,CAAC,GAAG,CAAA,4DAA4D,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,gBAAgB,CAAC,CAAA;IACrH,CAAC;CACF,CAAA","sourcesContent":["import { client } from '@operato/graphql'\nimport { i18next } from '@operato/i18n'\nimport gql from 'graphql-tag'\n\nexport { sessionActions } from './assistant-session-actions.js'\n\n/**\n * Managing the conversations on one anchor - list, rename, hide, delete, and who may read them.\n *\n * These were written once, inside operato-twin's dock (things-factory `b3d1081f4c`, `b44c986c07`,\n * 2026-07-30), and every other dock (plant, figure, warehouse, ecs) had only the tabs. They are the\n * framework's doors (`chatSessionInbox` · `renameAISession` · `hideAISession` · `deleteAISession` ·\n * `setSessionVisibility`), so the screen for them belongs here too - one list every dock opens.\n *\n * Who may do what is the server's to decide; the entry carries hints only:\n * rename any participant (the name is the topic label; reversible)\n * hide/unhide anyone, for their own list only (reversible)\n * delete the creator (`mine`) (not reversible from a screen)\n * visibility the owner (`owner`) (opening shows what is already written)\n * leave a member, never the owner (in a group, leaving ends reading here)\n */\n\n/** Who reads it: everyone in the domain, the people the owner brought in, or the owner alone (ADR-0073 decision 3). */\nexport type SessionVisibility = 'open' | 'group' | 'private'\n\n/** One row of `chatSessionInbox`, as the list draws it. */\nexport interface AssistantSessionEntry {\n id: string\n name?: string\n kind?: string\n lastMessageAt?: string\n lastMessagePreview?: string\n previewRedacted?: boolean\n unread?: boolean\n participant?: boolean\n /** I created it - only then may I delete it. */\n mine?: boolean\n /** I own it - only then may I change who reads it. */\n owner?: boolean\n /** Hidden from my own list (returned only with the hidden filter on). */\n hidden?: boolean\n visibility?: SessionVisibility | string\n}\n\n/** Legacy single filter - kept for callers written before the filter set. */\nexport type AssistantSessionFilter = 'all' | 'mine' | 'hidden'\n\n/** What the manager narrows by (design/ai/shared-dock.md §2-6). Defaults: this kind, everyone's, any visibility, hidden out. */\nexport interface AssistantSessionFilters {\n /** A kind (mode) to list; empty lists every kind on the anchor. */\n kind?: string\n whose?: 'all' | 'mine' | 'participant'\n visibility?: 'all' | SessionVisibility\n includeHidden?: boolean\n unreadOnly?: boolean\n}\n\nexport interface AssistantSessionQuery {\n anchorType: string\n anchorId: string\n search?: string\n filter?: AssistantSessionFilter\n filters?: AssistantSessionFilters\n limit?: number\n offset?: number\n}\n\nexport interface AssistantSessionPage {\n entries: AssistantSessionEntry[]\n /** How many pass the filter - so \"load more\" knows whether the end of the list is the end of the data. */\n total: number\n /** How many I hid - so a hidden conversation is never forgotten. */\n hiddenCount: number\n}\n\nexport interface AssistantSessionAdmin {\n inbox(query: AssistantSessionQuery): Promise<AssistantSessionPage>\n rename(sessionId: string, name: string): Promise<boolean>\n hide(sessionId: string, hidden: boolean): Promise<boolean>\n remove(sessionId: string): Promise<boolean>\n setVisibility(sessionId: string, visibility: SessionVisibility): Promise<boolean>\n leave(sessionId: string): Promise<boolean>\n}\n\n/** The page size the server allows at most (`chatSessionInbox` clamps to 200). */\nexport const SESSION_PAGE_MAX = 200\n\nasync function mutate(mutation: any, variables: Record<string, unknown>, field: string): Promise<boolean> {\n const result = await client.mutate({ mutation, variables })\n if (result.errors?.length) throw new Error(result.errors[0].message)\n return result.data?.[field] === true\n}\n\n/** The framework's session doors, as they are. */\nexport const assistantSessionAdmin: AssistantSessionAdmin = {\n async inbox({ anchorType, anchorId, search, filter = 'all', filters = {}, limit = 50, offset = 0 }) {\n const hidden = filters.includeHidden ?? filter === 'hidden'\n const mine = filters.whose ? filters.whose === 'mine' : filter === 'mine'\n const result = await client.query({\n query: gql`\n query ($t: String!, $i: String!, $h: Boolean, $q: String, $m: Boolean, $l: Int, $o: Int, $k: String, $p: Boolean, $v: String, $u: Boolean) {\n hiddenSessionCount(anchorType: $t, anchorId: $i)\n chatSessionInboxTotal(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u)\n chatSessionInbox(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, limit: $l, offset: $o) {\n id\n name\n kind\n lastMessageAt\n lastMessagePreview\n previewRedacted\n unread\n participant\n mine\n owner\n hidden\n visibility\n }\n }\n `,\n variables: {\n t: anchorType,\n i: anchorId,\n /* Hidden ones only when asked - elsewhere they stay out of the list. */\n h: hidden,\n q: search?.trim() || null,\n m: mine,\n k: filters.kind || null,\n p: filters.whose === 'participant' || null,\n v: filters.visibility && filters.visibility !== 'all' ? filters.visibility : null,\n u: filters.unreadOnly || null,\n l: Math.min(SESSION_PAGE_MAX, Math.max(1, limit)),\n o: Math.max(0, offset)\n },\n fetchPolicy: 'no-cache'\n })\n\n if (result.errors?.length) throw new Error(result.errors[0].message)\n const entries = result.data?.chatSessionInbox\n if (!Array.isArray(entries)) {\n throw new Error(i18next.t('ai-assistant.text.sessions-unreadable', { defaultValue: 'could not load the conversation list.' }))\n }\n\n return {\n /* With the hidden filter the server returns hidden ones alongside the rest, marked - the total counts both. */\n entries,\n total: result.data?.chatSessionInboxTotal ?? entries.length,\n hiddenCount: result.data?.hiddenSessionCount ?? 0\n }\n },\n\n rename(sessionId, name) {\n return mutate(gql`mutation ($id: String!, $n: String!) { renameAISession(sessionId: $id, name: $n) }`, { id: sessionId, n: name }, 'renameAISession')\n },\n\n hide(sessionId, hidden) {\n return mutate(gql`mutation ($id: String!, $h: Boolean) { hideAISession(sessionId: $id, hidden: $h) }`, { id: sessionId, h: hidden }, 'hideAISession')\n },\n\n remove(sessionId) {\n return mutate(gql`mutation ($id: String!) { deleteAISession(sessionId: $id) }`, { id: sessionId }, 'deleteAISession')\n },\n\n setVisibility(sessionId, visibility) {\n return mutate(\n gql`mutation ($id: String!, $v: String!) { setSessionVisibility(sessionId: $id, visibility: $v) }`,\n { id: sessionId, v: visibility },\n 'setSessionVisibility'\n )\n },\n\n leave(sessionId) {\n return mutate(gql`mutation ($id: String!) { leaveAISession(sessionId: $id) }`, { id: sessionId }, 'leaveAISession')\n }\n}\n"]}
1
+ {"version":3,"file":"assistant-session-admin.js","sourceRoot":"","sources":["../../client/utils/assistant-session-admin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AACvC,OAAO,GAAG,MAAM,aAAa,CAAA;AAE7B,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAiH5E,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAA;AAEnC,KAAK,UAAU,MAAM,CAAC,QAAa,EAAE,SAAkC,EAAE,KAAa;IACpF,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAA;IAC3D,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;IACpE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,IAAI,CAAA;AACtC,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,qBAAqB,GAA0B;IAC1D,KAAK,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,MAA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C,CAAA;IACvJ,CAAC;IAED,MAAM,CAAC,SAAS;QACd,OAAO,MAAM,CAAC,GAAG,CAAA,6DAA6D,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,iBAAiB,CAAC,CAAA;IACvH,CAAC;IAED,aAAa,CAAC,SAAS,EAAE,UAAU;QACjC,OAAO,MAAM,CACX,GAAG,CAAA,+FAA+F,EAClG,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,EAChC,sBAAsB,CACvB,CAAA;IACH,CAAC;IAED,KAAK,CAAC,SAAS;QACb,OAAO,MAAM,CAAC,GAAG,CAAA,4DAA4D,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,gBAAgB,CAAC,CAAA;IACrH,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ;QAChC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC;YAChC,KAAK,EAAE,GAAG,CAAA;;;;OAIT;YACD,SAAS,EAAE,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE;YACzC,WAAW,EAAE,UAAU;SACxB,CAAC,CAAA;QACF,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;QACpE,OAAO,MAAM,CAAC,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAA;IAC7C,CAAC;IAED,OAAO,CAAC,SAAS;QACf,OAAO,MAAM,CAAC,GAAG,CAAA,8DAA8D,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,kBAAkB,CAAC,CAAA;IACzH,CAAC;CACF,CAAA","sourcesContent":["import { client } from '@operato/graphql'\nimport { i18next } from '@operato/i18n'\nimport gql from 'graphql-tag'\n\nexport { bulkActions, sessionActions } from './assistant-session-actions.js'\n\n/**\n * Managing the conversations on one anchor - list, rename, hide, delete, and who may read them.\n *\n * These were written once, inside operato-twin's dock (things-factory `b3d1081f4c`, `b44c986c07`,\n * 2026-07-30), and every other dock (plant, figure, warehouse, ecs) had only the tabs. They are the\n * framework's doors (`chatSessionInbox` · `renameAISession` · `hideAISession` · `deleteAISession` ·\n * `setSessionVisibility`), so the screen for them belongs here too - one list every dock opens.\n *\n * Who may do what is the server's to decide; the entry carries hints only:\n * rename any participant (the name is the topic label; reversible)\n * hide/unhide anyone, for their own list only (reversible)\n * delete the creator (`mine`) (not reversible from a screen)\n * visibility the owner (`owner`) (opening shows what is already written)\n * leave a member, never the owner (in a group, leaving ends reading here)\n * restore the creator, while it is kept (deleted ones are kept `deletedDays`, shared-dock.md §9-5)\n */\n\n/** Who reads it: everyone in the domain, the people the owner brought in, or the owner alone (ADR-0073 decision 3). */\nexport type SessionVisibility = 'open' | 'group' | 'private'\n\n/** One row of `chatSessionInbox`, as the list draws it. */\nexport interface AssistantSessionEntry {\n id: string\n name?: string\n kind?: string\n lastMessageAt?: string\n lastMessagePreview?: string\n previewRedacted?: boolean\n unread?: boolean\n participant?: boolean\n /** I created it - only then may I delete it. */\n mine?: boolean\n /** I own it - only then may I change who reads it. */\n owner?: boolean\n /** Hidden from my own list (returned only with the hidden filter on). */\n hidden?: boolean\n visibility?: SessionVisibility | string\n /** No activity for the archive period - out of the list until asked for or searched. */\n archived?: boolean\n /** Why the list suggests clearing it (mine only): never asked anything, or idle for 30 days. */\n cleanupReason?: 'empty' | 'inactive' | string\n /** Whole days since the last activity. */\n idleDays?: number\n}\n\n/** A conversation I deleted that is still kept - it can be brought back until `purgesAt`. */\nexport interface DeletedSessionEntry {\n id: string\n name?: string\n kind?: string\n deletedAt: string\n purgesAt?: string\n}\n\n/** How long conversations are kept; `null` when that keeping is off. */\nexport interface SessionKeeping {\n deletedDays: number | null\n archiveDays: number | null\n}\n\n/** Legacy single filter - kept for callers written before the filter set. */\nexport type AssistantSessionFilter = 'all' | 'mine' | 'hidden'\n\n/** What the manager narrows by (design/ai/shared-dock.md §2-6). Defaults: this kind, everyone's, any visibility, hidden out. */\nexport interface AssistantSessionFilters {\n /** A kind (mode) to list; empty lists every kind on the anchor. */\n kind?: string\n whose?: 'all' | 'mine' | 'participant'\n visibility?: 'all' | SessionVisibility\n includeHidden?: boolean\n unreadOnly?: boolean\n /** Also the archived ones. */\n includeArchived?: boolean\n /** Only my own the list suggests clearing - hidden and archived ones included. */\n cleanupOnly?: boolean\n}\n\nexport interface AssistantSessionQuery {\n anchorType: string\n anchorId: string\n search?: string\n filter?: AssistantSessionFilter\n filters?: AssistantSessionFilters\n limit?: number\n offset?: number\n}\n\nexport interface AssistantSessionPage {\n entries: AssistantSessionEntry[]\n /** How many pass the filter - so \"load more\" knows whether the end of the list is the end of the data. */\n total: number\n /** How many I hid - so a hidden conversation is never forgotten. */\n hiddenCount: number\n /** How many are archived - the same, for the ones left idle. */\n archivedCount: number\n /** How many of mine the list suggests clearing. */\n cleanupCount: number\n keeping: SessionKeeping\n}\n\nexport interface AssistantSessionAdmin {\n inbox(query: AssistantSessionQuery): Promise<AssistantSessionPage>\n rename(sessionId: string, name: string): Promise<boolean>\n hide(sessionId: string, hidden: boolean): Promise<boolean>\n remove(sessionId: string): Promise<boolean>\n setVisibility(sessionId: string, visibility: SessionVisibility): Promise<boolean>\n leave(sessionId: string): Promise<boolean>\n deleted(anchorType: string, anchorId: string): Promise<DeletedSessionEntry[]>\n restore(sessionId: string): Promise<boolean>\n}\n\n/** The page size the server allows at most (`chatSessionInbox` clamps to 200). */\nexport const SESSION_PAGE_MAX = 200\n\nasync function mutate(mutation: any, variables: Record<string, unknown>, field: string): Promise<boolean> {\n const result = await client.mutate({ mutation, variables })\n if (result.errors?.length) throw new Error(result.errors[0].message)\n return result.data?.[field] === true\n}\n\n/** The framework's session doors, as they are. */\nexport const assistantSessionAdmin: AssistantSessionAdmin = {\n async inbox({ anchorType, anchorId, search, filter = 'all', filters = {}, limit = 50, offset = 0 }) {\n const hidden = filters.includeHidden ?? filter === 'hidden'\n const mine = filters.whose ? filters.whose === 'mine' : filter === 'mine'\n const result = await client.query({\n query: gql`\n query ($t: String!, $i: String!, $h: Boolean, $q: String, $m: Boolean, $l: Int, $o: Int, $k: String, $p: Boolean, $v: String, $u: Boolean, $a: Boolean, $c: Boolean) {\n hiddenSessionCount(anchorType: $t, anchorId: $i)\n archivedSessionCount(anchorType: $t, anchorId: $i)\n cleanupSessionCount(anchorType: $t, anchorId: $i)\n aiSessionKeeping { deletedDays archiveDays }\n chatSessionInboxTotal(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, includeArchived: $a, cleanupOnly: $c)\n chatSessionInbox(anchorType: $t, anchorId: $i, showHidden: $h, search: $q, mineOnly: $m, kind: $k, participantOnly: $p, visibility: $v, unreadOnly: $u, includeArchived: $a, cleanupOnly: $c, limit: $l, offset: $o) {\n id\n name\n kind\n lastMessageAt\n lastMessagePreview\n previewRedacted\n unread\n participant\n mine\n owner\n hidden\n visibility\n archived\n cleanupReason\n idleDays\n }\n }\n `,\n variables: {\n t: anchorType,\n i: anchorId,\n /* Hidden ones only when asked - elsewhere they stay out of the list. */\n h: hidden,\n q: search?.trim() || null,\n m: mine,\n k: filters.kind || null,\n p: filters.whose === 'participant' || null,\n v: filters.visibility && filters.visibility !== 'all' ? filters.visibility : null,\n u: filters.unreadOnly || null,\n a: filters.includeArchived || null,\n c: filters.cleanupOnly || null,\n l: Math.min(SESSION_PAGE_MAX, Math.max(1, limit)),\n o: Math.max(0, offset)\n },\n fetchPolicy: 'no-cache'\n })\n\n if (result.errors?.length) throw new Error(result.errors[0].message)\n const entries = result.data?.chatSessionInbox\n if (!Array.isArray(entries)) {\n throw new Error(i18next.t('ai-assistant.text.sessions-unreadable', { defaultValue: 'could not load the conversation list.' }))\n }\n\n return {\n /* With the hidden filter the server returns hidden ones alongside the rest, marked - the total counts both. */\n entries,\n total: result.data?.chatSessionInboxTotal ?? entries.length,\n hiddenCount: result.data?.hiddenSessionCount ?? 0,\n archivedCount: result.data?.archivedSessionCount ?? 0,\n cleanupCount: result.data?.cleanupSessionCount ?? 0,\n keeping: {\n deletedDays: result.data?.aiSessionKeeping?.deletedDays ?? null,\n archiveDays: result.data?.aiSessionKeeping?.archiveDays ?? null\n }\n }\n },\n\n rename(sessionId, name) {\n return mutate(gql`mutation ($id: String!, $n: String!) { renameAISession(sessionId: $id, name: $n) }`, { id: sessionId, n: name }, 'renameAISession')\n },\n\n hide(sessionId, hidden) {\n return mutate(gql`mutation ($id: String!, $h: Boolean) { hideAISession(sessionId: $id, hidden: $h) }`, { id: sessionId, h: hidden }, 'hideAISession')\n },\n\n remove(sessionId) {\n return mutate(gql`mutation ($id: String!) { deleteAISession(sessionId: $id) }`, { id: sessionId }, 'deleteAISession')\n },\n\n setVisibility(sessionId, visibility) {\n return mutate(\n gql`mutation ($id: String!, $v: String!) { setSessionVisibility(sessionId: $id, visibility: $v) }`,\n { id: sessionId, v: visibility },\n 'setSessionVisibility'\n )\n },\n\n leave(sessionId) {\n return mutate(gql`mutation ($id: String!) { leaveAISession(sessionId: $id) }`, { id: sessionId }, 'leaveAISession')\n },\n\n async deleted(anchorType, anchorId) {\n const result = await client.query({\n query: gql`\n query ($t: String!, $i: String!) {\n deletedAISessions(anchorType: $t, anchorId: $i) { id name kind deletedAt purgesAt }\n }\n `,\n variables: { t: anchorType, i: anchorId },\n fetchPolicy: 'no-cache'\n })\n if (result.errors?.length) throw new Error(result.errors[0].message)\n return result.data?.deletedAISessions ?? []\n },\n\n restore(sessionId) {\n return mutate(gql`mutation ($id: String!) { restoreAISession(sessionId: $id) }`, { id: sessionId }, 'restoreAISession')\n }\n}\n"]}
@@ -320,7 +320,7 @@ let AssistantChatResolver = class AssistantChatResolver {
320
320
  state: context.state
321
321
  })
322
322
  : undefined;
323
- const systemPrompt = subjectLine ? `${settings.systemPrompt}\n\n${subjectLine}` : settings.systemPrompt;
323
+ const systemPrompt = (0, mode_categories_js_1.turnSystemPrompt)(settings.systemPrompt, { subjectLine, page: input.page });
324
324
  const lastUserMessage = input.messages[input.messages.length - 1];
325
325
  let userMessageId;
326
326
  /*
@@ -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,iDAAoE;AACpE,mEAAgJ;AAEhJ,oEAA4D;AAC5D,sFAA8E;AAC9E,oEAA4D;AAC5D,kEAA+D;AAC/D,4EAAqE;AACrE,0EAA8D;AAC9D,oFAA2E;AAC3E,iEAA4D;AAC5D,oFAA2E;AAC3E,4FAAmF;AACnF,sEAAgF;AAChF,qDAAgD;AAChD,wGAA+F;AAC/F,sEAAgE;AAChE,oEAAiE;AACjE,kEAA0D;AAC1D,oFAAuE;AACvE,8FAA0F;AAC1F,4FAAuF;AACvF,gFAA4E;AAC5E,8EAA2G;AAC3G,kFAAkH;AAClH,4EAAwE;AACxE,8DAA+D;AAC/D,4DAAiE;AACjE,4EAA0F;AAC1F,gEAA4D;AAC5D,sEAAmE;AACnE,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,oBAAK,EAAC,EAAE,WAAW,EAAE,+EAA+E,EAAE,CAAC;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MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG;aAC3B,CAAC,CAAA;QACJ,CAAC;QAED,OAAO;YACL,KAAK;YACL,UAAU,EAAE,UAAU,IAAI,IAAI;YAC9B,QAAQ,EAAE,MAAM,CAAC,EAAE;YACnB,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE;YACxB,SAAS,EAAE,OAAO,EAAE,EAAE;YACtB,aAAa;YACb,kBAAkB;YAClB,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,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;AA1aY,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;;0DAwZ1D;gCAzaU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CA0ajC","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 { getRepository, rethrowSpoken } from '@things-factory/shell'\nimport { aiClientFor, findToolSpec, openSubjectLine, OPEN_TOOLS, registryAssistantChat, type AgentClient } 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 { offeredCardLines } from './chat-message/proposal-outcome.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 { seatTurn } from './chat-session-participant/mention-invite.js'\nimport { sendInviteNotification } 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, textCharsOf } from './chat-session/attachment-policy.js'\nimport { attachmentForModel, describeAttachment, findChatAttachment } from './chat-session/session-attachments.js'\nimport { readTurnAttachments } from './chat-session/turn-attachments.js'\nimport { getAssistantMode } from './assistant-mode/registry.js'\nimport { resolveModeSettings } from './assistant-mode/resolve.js'\nimport { modeFrontCategories, selectionAxesOf } from './assistant-mode/mode-categories.js'\nimport { usedToolNames } from './chat-message/used-tools.js'\nimport { splitNextRequest } from './assistant-mode/screen-rules.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 @Field({\n nullable: true,\n description:\n 'The AI agent the person picked for this turn, from aiAgentChoices. Omitted takes the domain default. An agent this domain cannot use is refused - the provider, the model and the key are always the server\\'s.'\n })\n agentId?: string\n\n @Field({\n nullable: true,\n description:\n 'The route of the page the dock is on (cash-transaction-list). It decides which tools the model is offered first; what a person may use is decided as without it.'\n })\n page?: string\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(() => String, {\n nullable: true,\n description:\n 'The request the person is likely to make next, as the reply named it. The input shows it and Tab writes it in. Not stored with the reply.'\n })\n suggestion?: string | null\n\n @Field({ description: 'AI client identifier (provider:model).' })\n clientId: string\n\n @Field({ nullable: true, description: 'The AI agent that answered.' })\n agentId?: 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\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 { domain, user } = context.state\n\n /*\n * The domain's agent - the one picked, or the default (design/ai/agent-settings.md §4). Asked before anything is\n * stored: a domain with no AI, or an agent it cannot use, is refused as itself.\n */\n let client: AgentClient\n try {\n client = await aiClientFor({\n domain,\n user,\n agentId: input.agentId,\n modeKind: input.mode.kind,\n sessionId: input.sessionId\n })\n } catch (error) {\n rethrowSpoken(error, context)\n }\n /* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */\n context.state.aiAgentId = client.agent.id\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 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 /*\n * 열린 대상 — 서버가 저장한 앵커에서 턴마다 한 줄(design/ai/screen-pattern.md §2-1). 화면이 보낸 hostContext 는\n * 쓰지 않는다. 대상이 바뀌면 다음 턴의 줄도 바뀌므로 옛 대상이 대화에 남지 않는다.\n */\n const subjectLine = session\n ? await openSubjectLine({\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n domain,\n state: context.state\n })\n : undefined\n const systemPrompt = subjectLine ? `${settings.systemPrompt}\\n\\n${subjectLine}` : settings.systemPrompt\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 * 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.\n */\n const invite = await seatTurn({\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 /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */\n await sendInviteNotification((context.state as any)?.notify, invite.invited, user, (session as any)?.name, undefined, requestTranslator(context))\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.content,\n ...(message.id !== userMessageId && Array.isArray((message as any).attachmentsJson) ? (message as any).attachmentsJson.map(attachmentHistoryLine) : []),\n /* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */\n ...(message.role === 'assistant' ? offeredCardLines((message as any).proposals) : [])\n ].join('\\n'),\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 /*\n * The files checked above, read once: the model reads them on this turn's question, and the tools get the same\n * files as `context.attachments` (ADR-0061, 2026-10-16 decision 2) - figure's step generator draws from the\n * picture the person sent. Never mixed into `hostContext`, which the client fills.\n */\n const turnFiles = await readTurnAttachments(\n attachmentRows,\n textCharsOf(getAssistantMode(input.mode?.kind ?? '')?.attachments),\n attachmentForModel\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 last.content = [{ type: 'text', text: last.content }, ...turnFiles.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,\n toolCategories: settings.toolCategories,\n /*\n * What goes in front when the mode's tools do not fit in one call (ADR-0061 decision 9): the open page's, the\n * anchored record's and the latest selection's, then what this conversation used. The anchor and the selection are\n * the stored ones, never the client's.\n */\n front: {\n categories: modeFrontCategories(getAssistantMode(input.mode.kind) ?? {}, {\n page: input.page,\n subjectAxis: (session as any)?.anchorType === 'subject' ? String((session as any).anchorId ?? '').split(':')[0] || undefined : undefined,\n selectionAxes: selectionAxesOf(storedRows as any)\n }),\n tools: usedToolNames(storedRows as any, [OPEN_TOOLS])\n },\n /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n /* And which stored conversation - the room a tool like the invite card acts on. The server's session, never the client's. */\n ...(session?.id ? { conversation: { id: session.id } } : {}),\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 attachments: turnFiles.forTools,\n /*\n * 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다\n * (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한\n * 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고\n * 자체를 안 보게 된다.\n */\n groundingSources: groundingSourcesFor({\n systemPrompt,\n messages: conversation as any,\n hostContext: input.hostContext\n }),\n state: context.state,\n temperature: settings.temperature,\n maxTokens: settings.maxTokens,\n requireToolOnFirstTurn: settings.requireToolOnFirstTurn\n })\n\n /*\n * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면\n * 가려진 답이 목록에는 그대로 뜬다.\n */\n /* The reply ends with the next request when one is natural; the input offers it and the stored answer does not keep it (§4-1). */\n const { reply, suggestion } = splitNextRequest(result.reply)\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: 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: reply,\n actorId: user?.id\n })\n\n await sessionRepo.update(session.id!, {\n aiClientId: client.id,\n agentId: client.agent.id,\n updater: user,\n ...activityPatch(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,\n suggestion: suggestion ?? null,\n clientId: client.id,\n agentId: client.agent.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,iDAAoE;AACpE,mEAAgJ;AAEhJ,oEAA4D;AAC5D,sFAA8E;AAC9E,oEAA4D;AAC5D,kEAA+D;AAC/D,4EAAqE;AACrE,0EAA8D;AAC9D,oFAA2E;AAC3E,iEAA4D;AAC5D,oFAA2E;AAC3E,4FAAmF;AACnF,sEAAgF;AAChF,qDAAgD;AAChD,wGAA+F;AAC/F,sEAAgE;AAChE,oEAAiE;AACjE,kEAA0D;AAC1D,oFAAuE;AACvE,8FAA0F;AAC1F,4FAAuF;AACvF,gFAA4E;AAC5E,8EAA2G;AAC3G,kFAAkH;AAClH,4EAAwE;AACxE,8DAA+D;AAC/D,4DAAiE;AACjE,4EAA4G;AAC5G,gEAA4D;AAC5D,sEAAmE;AACnE,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,iB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GAAE,CAAA;;6CAA1B,kBAAkB;;0DAwZ1D;gCAzaU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CA0ajC","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 { getRepository, rethrowSpoken } from '@things-factory/shell'\nimport { aiClientFor, findToolSpec, openSubjectLine, OPEN_TOOLS, registryAssistantChat, type AgentClient } 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 { offeredCardLines } from './chat-message/proposal-outcome.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 { seatTurn } from './chat-session-participant/mention-invite.js'\nimport { sendInviteNotification } 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, textCharsOf } from './chat-session/attachment-policy.js'\nimport { attachmentForModel, describeAttachment, findChatAttachment } from './chat-session/session-attachments.js'\nimport { readTurnAttachments } from './chat-session/turn-attachments.js'\nimport { getAssistantMode } from './assistant-mode/registry.js'\nimport { resolveModeSettings } from './assistant-mode/resolve.js'\nimport { modeFrontCategories, selectionAxesOf, turnSystemPrompt } from './assistant-mode/mode-categories.js'\nimport { usedToolNames } from './chat-message/used-tools.js'\nimport { splitNextRequest } from './assistant-mode/screen-rules.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 @Field({\n nullable: true,\n description:\n 'The AI agent the person picked for this turn, from aiAgentChoices. Omitted takes the domain default. An agent this domain cannot use is refused - the provider, the model and the key are always the server\\'s.'\n })\n agentId?: string\n\n @Field({\n nullable: true,\n description:\n 'The route of the page the dock is on (cash-transaction-list). It decides which tools the model is offered first; what a person may use is decided as without it.'\n })\n page?: string\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(() => String, {\n nullable: true,\n description:\n 'The request the person is likely to make next, as the reply named it. The input shows it and Tab writes it in. Not stored with the reply.'\n })\n suggestion?: string | null\n\n @Field({ description: 'AI client identifier (provider:model).' })\n clientId: string\n\n @Field({ nullable: true, description: 'The AI agent that answered.' })\n agentId?: 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\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 { domain, user } = context.state\n\n /*\n * The domain's agent - the one picked, or the default (design/ai/agent-settings.md §4). Asked before anything is\n * stored: a domain with no AI, or an agent it cannot use, is refused as itself.\n */\n let client: AgentClient\n try {\n client = await aiClientFor({\n domain,\n user,\n agentId: input.agentId,\n modeKind: input.mode.kind,\n sessionId: input.sessionId\n })\n } catch (error) {\n rethrowSpoken(error, context)\n }\n /* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */\n context.state.aiAgentId = client.agent.id\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 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 /*\n * 열린 대상 — 서버가 저장한 앵커에서 턴마다 한 줄(design/ai/screen-pattern.md §2-1). 화면이 보낸 hostContext 는\n * 쓰지 않는다. 대상이 바뀌면 다음 턴의 줄도 바뀌므로 옛 대상이 대화에 남지 않는다.\n */\n const subjectLine = session\n ? await openSubjectLine({\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n domain,\n state: context.state\n })\n : undefined\n const systemPrompt = turnSystemPrompt(settings.systemPrompt, { subjectLine, page: input.page })\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 * 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.\n */\n const invite = await seatTurn({\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 /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */\n await sendInviteNotification((context.state as any)?.notify, invite.invited, user, (session as any)?.name, undefined, requestTranslator(context))\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.content,\n ...(message.id !== userMessageId && Array.isArray((message as any).attachmentsJson) ? (message as any).attachmentsJson.map(attachmentHistoryLine) : []),\n /* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */\n ...(message.role === 'assistant' ? offeredCardLines((message as any).proposals) : [])\n ].join('\\n'),\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 /*\n * The files checked above, read once: the model reads them on this turn's question, and the tools get the same\n * files as `context.attachments` (ADR-0061, 2026-10-16 decision 2) - figure's step generator draws from the\n * picture the person sent. Never mixed into `hostContext`, which the client fills.\n */\n const turnFiles = await readTurnAttachments(\n attachmentRows,\n textCharsOf(getAssistantMode(input.mode?.kind ?? '')?.attachments),\n attachmentForModel\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 last.content = [{ type: 'text', text: last.content }, ...turnFiles.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,\n toolCategories: settings.toolCategories,\n /*\n * What goes in front when the mode's tools do not fit in one call (ADR-0061 decision 9): the open page's, the\n * anchored record's and the latest selection's, then what this conversation used. The anchor and the selection are\n * the stored ones, never the client's.\n */\n front: {\n categories: modeFrontCategories(getAssistantMode(input.mode.kind) ?? {}, {\n page: input.page,\n subjectAxis: (session as any)?.anchorType === 'subject' ? String((session as any).anchorId ?? '').split(':')[0] || undefined : undefined,\n selectionAxes: selectionAxesOf(storedRows as any)\n }),\n tools: usedToolNames(storedRows as any, [OPEN_TOOLS])\n },\n /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n /* And which stored conversation - the room a tool like the invite card acts on. The server's session, never the client's. */\n ...(session?.id ? { conversation: { id: session.id } } : {}),\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 attachments: turnFiles.forTools,\n /*\n * 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다\n * (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한\n * 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고\n * 자체를 안 보게 된다.\n */\n groundingSources: groundingSourcesFor({\n systemPrompt,\n messages: conversation as any,\n hostContext: input.hostContext\n }),\n state: context.state,\n temperature: settings.temperature,\n maxTokens: settings.maxTokens,\n requireToolOnFirstTurn: settings.requireToolOnFirstTurn\n })\n\n /*\n * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면\n * 가려진 답이 목록에는 그대로 뜬다.\n */\n /* The reply ends with the next request when one is natural; the input offers it and the stored answer does not keep it (§4-1). */\n const { reply, suggestion } = splitNextRequest(result.reply)\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: 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: reply,\n actorId: user?.id\n })\n\n await sessionRepo.update(session.id!, {\n aiClientId: client.id,\n agentId: client.agent.id,\n updater: user,\n ...activityPatch(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,\n suggestion: suggestion ?? null,\n clientId: client.id,\n agentId: client.agent.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"]}
@@ -5,7 +5,7 @@
5
5
  */
6
6
  export { registerAssistantMode, getAssistantMode, listAssistantModes, assistantModeForSubject, getAssistantModeWarnings, clearAssistantModes } from './registry.js';
7
7
  export { resolveModeSettings, assistantModeView } from './resolve.js';
8
- export { registerConversationCategory, conversationCategoriesOf, type ConversationCategory } from './mode-categories.js';
8
+ export { registerConversationCategory, conversationCategoriesOf, turnSystemPrompt, type ConversationCategory } from './mode-categories.js';
9
9
  export { ABSENCE_RULE, FINISH_RULE, NEXT_REQUEST_RULE, SELECTION_RULE, SPEAKER_RULE, conversationPrompt, isPersonRequest, splitNextRequest } from './screen-rules.js';
10
10
  export type { AssistantModeSpec, AssistantModeSlash, AssistantModeWarning, UnattendedLimits } from './types.js';
11
11
  export type { AssistantModeRef, ModeSettings, AssistantModeView, AssistantModeSlashView, Translate } from './resolve.js';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.splitNextRequest = exports.isPersonRequest = exports.conversationPrompt = exports.SPEAKER_RULE = exports.SELECTION_RULE = exports.NEXT_REQUEST_RULE = exports.FINISH_RULE = exports.ABSENCE_RULE = exports.conversationCategoriesOf = exports.registerConversationCategory = exports.assistantModeView = exports.resolveModeSettings = exports.clearAssistantModes = exports.getAssistantModeWarnings = exports.assistantModeForSubject = exports.listAssistantModes = exports.getAssistantMode = exports.registerAssistantMode = void 0;
3
+ exports.splitNextRequest = exports.isPersonRequest = exports.conversationPrompt = exports.SPEAKER_RULE = exports.SELECTION_RULE = exports.NEXT_REQUEST_RULE = exports.FINISH_RULE = exports.ABSENCE_RULE = exports.turnSystemPrompt = exports.conversationCategoriesOf = exports.registerConversationCategory = exports.assistantModeView = exports.resolveModeSettings = exports.clearAssistantModes = exports.getAssistantModeWarnings = exports.assistantModeForSubject = exports.listAssistantModes = exports.getAssistantMode = exports.registerAssistantMode = void 0;
4
4
  /**
5
5
  * Modes — what each conversation is, declared by the app server that owns the screen.
6
6
  *
@@ -20,6 +20,7 @@ Object.defineProperty(exports, "assistantModeView", { enumerable: true, get: fun
20
20
  var mode_categories_js_1 = require("./mode-categories.js");
21
21
  Object.defineProperty(exports, "registerConversationCategory", { enumerable: true, get: function () { return mode_categories_js_1.registerConversationCategory; } });
22
22
  Object.defineProperty(exports, "conversationCategoriesOf", { enumerable: true, get: function () { return mode_categories_js_1.conversationCategoriesOf; } });
23
+ Object.defineProperty(exports, "turnSystemPrompt", { enumerable: true, get: function () { return mode_categories_js_1.turnSystemPrompt; } });
23
24
  var screen_rules_js_1 = require("./screen-rules.js");
24
25
  Object.defineProperty(exports, "ABSENCE_RULE", { enumerable: true, get: function () { return screen_rules_js_1.ABSENCE_RULE; } });
25
26
  Object.defineProperty(exports, "FINISH_RULE", { enumerable: true, get: function () { return screen_rules_js_1.FINISH_RULE; } });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/index.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,6CAOsB;AANpB,oHAAA,qBAAqB,OAAA;AACrB,+GAAA,gBAAgB,OAAA;AAChB,iHAAA,kBAAkB,OAAA;AAClB,sHAAA,uBAAuB,OAAA;AACvB,uHAAA,wBAAwB,OAAA;AACxB,kHAAA,mBAAmB,OAAA;AAErB,2CAAqE;AAA5D,iHAAA,mBAAmB,OAAA;AAAE,+GAAA,iBAAiB,OAAA;AAC/C,mHAAmH;AACnH,2DAAwH;AAA/G,kIAAA,4BAA4B,OAAA;AAAE,8HAAA,wBAAwB,OAAA;AAC/D,qDAAqK;AAA5J,+GAAA,YAAY,OAAA;AAAE,8GAAA,WAAW,OAAA;AAAE,oHAAA,iBAAiB,OAAA;AAAE,iHAAA,cAAc,OAAA;AAAE,+GAAA,YAAY,OAAA;AAAE,qHAAA,kBAAkB,OAAA;AAAE,kHAAA,eAAe,OAAA;AAAE,mHAAA,gBAAgB,OAAA","sourcesContent":["/**\n * Modes — what each conversation is, declared by the app server that owns the screen.\n *\n * Design: ADR-0061 decision 7 (`operato-application/adr/ADR-0061.md`) and the AI standard's A2.\n */\nexport {\n registerAssistantMode,\n getAssistantMode,\n listAssistantModes,\n assistantModeForSubject,\n getAssistantModeWarnings,\n clearAssistantModes\n} from './registry.js'\nexport { resolveModeSettings, assistantModeView } from './resolve.js'\n/* A category another package opens in every conversation, in front on the pages it names (ADR-0160 decision 9). */\nexport { registerConversationCategory, conversationCategoriesOf, type ConversationCategory } from './mode-categories.js'\nexport { ABSENCE_RULE, FINISH_RULE, NEXT_REQUEST_RULE, SELECTION_RULE, SPEAKER_RULE, conversationPrompt, isPersonRequest, splitNextRequest } from './screen-rules.js'\nexport type { AssistantModeSpec, AssistantModeSlash, AssistantModeWarning, UnattendedLimits } from './types.js'\nexport type { AssistantModeRef, ModeSettings, AssistantModeView, AssistantModeSlashView, Translate } from './resolve.js'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/index.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,6CAOsB;AANpB,oHAAA,qBAAqB,OAAA;AACrB,+GAAA,gBAAgB,OAAA;AAChB,iHAAA,kBAAkB,OAAA;AAClB,sHAAA,uBAAuB,OAAA;AACvB,uHAAA,wBAAwB,OAAA;AACxB,kHAAA,mBAAmB,OAAA;AAErB,2CAAqE;AAA5D,iHAAA,mBAAmB,OAAA;AAAE,+GAAA,iBAAiB,OAAA;AAC/C,mHAAmH;AACnH,2DAA0I;AAAjI,kIAAA,4BAA4B,OAAA;AAAE,8HAAA,wBAAwB,OAAA;AAAE,sHAAA,gBAAgB,OAAA;AACjF,qDAAqK;AAA5J,+GAAA,YAAY,OAAA;AAAE,8GAAA,WAAW,OAAA;AAAE,oHAAA,iBAAiB,OAAA;AAAE,iHAAA,cAAc,OAAA;AAAE,+GAAA,YAAY,OAAA;AAAE,qHAAA,kBAAkB,OAAA;AAAE,kHAAA,eAAe,OAAA;AAAE,mHAAA,gBAAgB,OAAA","sourcesContent":["/**\n * Modes — what each conversation is, declared by the app server that owns the screen.\n *\n * Design: ADR-0061 decision 7 (`operato-application/adr/ADR-0061.md`) and the AI standard's A2.\n */\nexport {\n registerAssistantMode,\n getAssistantMode,\n listAssistantModes,\n assistantModeForSubject,\n getAssistantModeWarnings,\n clearAssistantModes\n} from './registry.js'\nexport { resolveModeSettings, assistantModeView } from './resolve.js'\n/* A category another package opens in every conversation, in front on the pages it names (ADR-0160 decision 9). */\nexport { registerConversationCategory, conversationCategoriesOf, turnSystemPrompt, type ConversationCategory } from './mode-categories.js'\nexport { ABSENCE_RULE, FINISH_RULE, NEXT_REQUEST_RULE, SELECTION_RULE, SPEAKER_RULE, conversationPrompt, isPersonRequest, splitNextRequest } from './screen-rules.js'\nexport type { AssistantModeSpec, AssistantModeSlash, AssistantModeWarning, UnattendedLimits } from './types.js'\nexport type { AssistantModeRef, ModeSettings, AssistantModeView, AssistantModeSlashView, Translate } from './resolve.js'\n"]}
@@ -7,10 +7,25 @@ export interface ConversationCategory {
7
7
  name: string;
8
8
  /** The application routes whose conversations put it in front (`my-dashboard`). */
9
9
  frontPages?: string[];
10
+ /**
11
+ * The axes of the records whose selection or anchor puts it in front (`dashboard-card`) - a card picked to change is
12
+ * changed by this category's tools, wherever the dock is open.
13
+ */
14
+ frontAxes?: string[];
15
+ /**
16
+ * What a turn asked from one of its front pages must end in - said in that turn's system prompt only. On 나의 대시보드
17
+ * a request to see a figure is a card; asked 「이번 달 지출 합계」 there, the model answered 「0원」 in words (2026-10-25).
18
+ */
19
+ pageRule?: string;
10
20
  }
11
21
  export declare function registerConversationCategory(category: ConversationCategory): void;
12
22
  export declare function conversationCategoriesOf(): ConversationCategory[];
13
23
  export declare function clearConversationCategories(): void;
24
+ /** The system prompt of one turn - the mode's, the open record's line, and the rules of the page it is asked from. */
25
+ export declare function turnSystemPrompt(modePrompt: string, screen?: {
26
+ page?: string;
27
+ subjectLine?: string;
28
+ }): string;
14
29
  /**
15
30
  * The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
16
31
  * takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
@@ -4,6 +4,7 @@ exports.SELECTION_KEYS_LINE = void 0;
4
4
  exports.registerConversationCategory = registerConversationCategory;
5
5
  exports.conversationCategoriesOf = conversationCategoriesOf;
6
6
  exports.clearConversationCategories = clearConversationCategories;
7
+ exports.turnSystemPrompt = turnSystemPrompt;
7
8
  exports.modeToolCategories = modeToolCategories;
8
9
  exports.unattendedToolCategories = unattendedToolCategories;
9
10
  exports.selectionAxesOf = selectionAxesOf;
@@ -24,6 +25,11 @@ function conversationCategoriesOf() {
24
25
  function clearConversationCategories() {
25
26
  conversationCategories.clear();
26
27
  }
28
+ /** The system prompt of one turn - the mode's, the open record's line, and the rules of the page it is asked from. */
29
+ function turnSystemPrompt(modePrompt, screen = {}) {
30
+ const pageRules = screen.page ? conversationCategoriesOf().filter(one => one.pageRule && (one.frontPages ?? []).includes(screen.page)).map(one => one.pageRule) : [];
31
+ return [modePrompt, screen.subjectLine, ...pageRules].filter(Boolean).join('\n\n');
32
+ }
27
33
  /**
28
34
  * The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
29
35
  * takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
@@ -109,7 +115,7 @@ function modeFrontCategories(mode, screen = {}) {
109
115
  ...keys.filter(key => (mode.readTargets ?? []).includes(key)).map(key => `data-read:${key}`),
110
116
  ...keys.filter(key => (mode.entryTargets ?? []).includes(key)).map(key => `data-entry:${key}`),
111
117
  ...conversationCategoriesOf()
112
- .filter(one => !!screen.page && (one.frontPages ?? []).includes(screen.page))
118
+ .filter(one => (!!screen.page && (one.frontPages ?? []).includes(screen.page)) || (one.frontAxes ?? []).some(axis => axis === screen.subjectAxis || !!screen.selectionAxes?.includes(axis)))
113
119
  .map(one => one.name)
114
120
  ])
115
121
  ];