@things-factory/ai-assistant 10.1.281 → 10.1.283

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.
@@ -26,6 +26,8 @@ const tslib_1 = require("tslib");
26
26
  * document are not offered here — `registryAssistantChat` enforces that, and it decides what may
27
27
  * be dispatched from the same list it offers, so the two cannot drift apart.
28
28
  */
29
+ const assistant_progress_js_1 = require("./chat-message/assistant-progress.js");
30
+ const assistant_progress_subscription_js_1 = require("./chat-message/assistant-progress-subscription.js");
29
31
  const type_graphql_1 = require("type-graphql");
30
32
  const graphql_scalars_1 = require("graphql-scalars");
31
33
  require("@things-factory/auth-base");
@@ -39,7 +41,7 @@ const llm_history_js_1 = require("./chat-message/llm-history.js");
39
41
  const proposal_outcome_js_1 = require("./chat-message/proposal-outcome.js");
40
42
  const history_summary_js_1 = require("./chat-message/history-summary.js");
41
43
  const fold_session_history_js_1 = require("./chat-message/fold-session-history.js");
42
- const grounding_sources_js_1 = require("./grounding-sources.js");
44
+ const mode_turn_js_1 = require("./assistant-turn/mode-turn.js");
43
45
  const chat_message_publish_js_1 = require("./chat-message/chat-message-publish.js");
44
46
  const session_activity_publish_js_1 = require("./chat-session/session-activity-publish.js");
45
47
  const session_inbox_js_1 = require("./chat-session/session-inbox.js");
@@ -236,265 +238,33 @@ let AssistantChatResolver = class AssistantChatResolver {
236
238
  * history is safer than a lost one.
237
239
  */
238
240
  async assistantChat(input, context) {
239
- const { domain, user } = context.state;
240
241
  /*
241
- * The domain's agent - the one picked, or the default (design/ai/agent-settings.md §4). Asked before anything is
242
- * stored: a domain with no AI, or an agent it cannot use, is refused as itself.
242
+ * One turn, in the order it happens (2026-11-14: the steps were one 415-line method). Each step is the code it was;
243
+ * the turn itself -- what the mode's settings mean for the model call -- is runModeTurn, shared with an unattended
244
+ * run and the conformance harness.
243
245
  */
244
- let client;
245
- try {
246
- client = await (0, ai_client_base_1.aiClientFor)({
247
- domain,
248
- user,
249
- agentId: input.agentId,
250
- modeKind: input.mode.kind,
251
- sessionId: input.sessionId
252
- });
253
- }
254
- catch (error) {
255
- (0, shell_1.rethrowSpoken)(error, context);
256
- }
257
- /* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */
258
- context.state.aiAgentId = client.agent.id;
246
+ const client = await agentOf(input, context);
247
+ const t = (0, request_translator_js_1.requestTranslator)(context);
259
248
  /*
260
249
  * Read the declaration before anything is stored. A kind this server does not have is a
261
250
  * mismatched deployment, and the person should see that instead of a conversation with no
262
251
  * persona and no tools.
263
252
  */
264
- const t = (0, request_translator_js_1.requestTranslator)(context);
265
- const settings = (0, resolve_js_1.resolveModeSettings)(input.mode, t);
266
- const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
267
- const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
268
- let session;
269
- if (input.sessionId) {
270
- const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } });
271
- if (!found)
272
- throw new Error(t('ai-assistant.text.session-not-found', { defaultValue: 'this conversation is not here any more. reload the list.' }));
273
- /*
274
- * A private conversation is written by its people only - and here more than anywhere: the answer is
275
- * built on this conversation's history, so an outsider's question would read it back to them.
276
- */
277
- await (0, session_write_gate_js_1.assertMayWriteSession)({
278
- session: found,
279
- userId: user?.id,
280
- isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, found.id, user?.id),
281
- t: (key, options) => t(key, options)
282
- });
283
- if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {
284
- throw new Error(context.t('ai-assistant.text.other-figure-history', {
285
- defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'
286
- }));
287
- }
288
- if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {
289
- throw new Error(context.t('ai-assistant.text.application-vs-model-history', {
290
- defaultValue: 'this conversation is about the application, not about a model. open the one you want.'
291
- }));
292
- }
293
- /*
294
- * 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이
295
- * 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.
296
- */
297
- const verdict = (0, session_kind_js_1.judgeSessionKind)(found.kind, input.mode.kind);
298
- if (verdict.action === 'refuse') {
299
- throw new Error(t('ai-assistant.text.session-kind-mismatch', {
300
- ...verdict.params,
301
- defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'
302
- }));
303
- }
304
- if (verdict.action === 'stamp') {
305
- /* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */
306
- await sessionRepo.update(found.id, { kind: verdict.kind });
307
- found.kind = verdict.kind;
308
- }
309
- session = found;
310
- }
311
- (0, station_session_guard_js_1.assertStationSession)(session, input.hostContext, t);
312
- /*
313
- * 열린 대상 — 서버가 저장한 앵커에서 턴마다 한 줄(design/ai/screen-pattern.md §2-1). 화면이 보낸 hostContext 는
314
- * 쓰지 않는다. 대상이 바뀌면 다음 턴의 줄도 바뀌므로 옛 대상이 대화에 남지 않는다.
315
- */
316
- const subjectLine = session
317
- ? await (0, ai_client_base_1.openSubjectLine)({
318
- anchorType: session.anchorType,
319
- anchorId: session.anchorId,
320
- domain,
321
- state: context.state
322
- })
323
- : undefined;
324
- /* What the person has in front of them besides the subject - the screen's unread notices (ADR-0199 amendment 1). */
325
- const screenLines = await (0, turn_lines_js_1.turnLinesOf)({ page: input.page, state: context.state });
326
- const systemPrompt = (0, mode_categories_js_1.turnSystemPrompt)(settings.systemPrompt, { subjectLine: [subjectLine, ...screenLines].filter(Boolean).join('\n\n') || undefined, page: input.page });
327
- const lastUserMessage = input.messages[input.messages.length - 1];
328
- let userMessageId;
329
- /*
330
- * Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by
331
- * attachToConversation; one that is not this conversation's is refused, never read. The policy is the
332
- * mode's - checked again here, since the door is the authority, not the screen.
333
- */
334
- const attachmentRows = [];
335
- if (input.attachmentIds?.length) {
336
- if (!session)
337
- throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }));
338
- for (const id of input.attachmentIds) {
339
- const row = await (0, session_attachments_js_1.findChatAttachment)(domain.id, session.id, id);
340
- if (!row)
341
- throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }));
342
- attachmentRows.push(row);
343
- }
344
- const refusal = (0, attachment_policy_js_1.refuseAttachments)((0, registry_js_1.getAssistantMode)(input.mode.kind)?.attachments, attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) })));
345
- if (refusal)
346
- throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...refusal, defaultValue: refusal.code }));
347
- }
348
- if (session && lastUserMessage?.role === 'user') {
349
- const previousLast = await messageRepo.findOne({
350
- where: { session: { id: session.id } },
351
- order: { createdAt: 'DESC' }
352
- });
353
- const saved = await messageRepo.save({
354
- session: { id: session.id },
355
- role: 'user',
356
- content: lastUserMessage.content,
357
- /*
358
- * This door is the one people call to ask the assistant, so a turn stored here was for the
359
- * assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never
360
- * from the request — two sources for one fact can disagree.
361
- */
362
- addressee: 'assistant',
363
- attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(session_attachments_js_1.describeAttachment)) : undefined,
364
- creator: user,
365
- updater: user,
366
- parentMessage: previousLast ? { id: previousLast.id } : undefined
367
- });
368
- userMessageId = saved.id;
369
- /*
370
- * Session activity is denormalised for the list: most-recent ordering and another
371
- * participant's unread badge read it. Best effort — a conversation must not fail because a
372
- * list sorts one position late.
373
- */
374
- try {
375
- const patch = (0, session_inbox_js_1.activityPatch)(lastUserMessage.content);
376
- if (!session.name)
377
- patch.name = (0, session_inbox_js_1.autoSessionName)(lastUserMessage.content);
378
- await sessionRepo.update(session.id, patch);
379
- }
380
- catch {
381
- /* noop */
382
- }
383
- /*
384
- * 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을
385
- * 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다. 공개 방에서 말한 사람도
386
- * 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.
387
- */
388
- const invite = await (0, mention_invite_js_1.seatTurn)({
389
- content: lastUserMessage.content,
390
- sessionId: session.id,
391
- domainId: domain.id,
392
- inviter: user,
393
- participants: (0, shell_1.getRepository)(chat_session_participant_js_1.ChatSessionParticipant),
394
- visibility: session.visibility
395
- });
396
- /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */
397
- await (0, invite_notification_js_1.sendInviteNotification)(context.state?.sendNotice, invite.invited, user, session?.name, undefined, (0, request_translator_js_1.requestTranslator)(context));
398
- (0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: saved });
399
- (0, session_activity_publish_js_1.publishSessionActivity)({
400
- domainId: domain.id,
401
- sessionId: session.id,
402
- kind: 'message',
403
- anchorType: session.anchorType,
404
- anchorId: session.anchorId,
405
- preview: lastUserMessage.content,
406
- actorId: user?.id
407
- });
408
- }
409
- /*
410
- * 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.
411
- *
412
- * 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드
413
- * 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —
414
- * 모델에게는 「N 개 생략」을 적어 보내면서.
415
- */
416
- const readRows = session
417
- ? await messageRepo.find({
418
- where: { session: { id: session.id } },
419
- order: { createdAt: 'ASC' },
420
- relations: ['creator']
421
- })
422
- : [];
423
- /*
424
- * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도
425
- * 안 지난 사람이 "아까 그 수 다시 말해 줘" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은
426
- * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런
427
- * 말이 없었다고 답하고, 그것은 거짓말이다.
428
- */
429
- const storedRows = await (0, reader_gate_js_1.readerGate)(context)(readRows);
430
- const capped = (0, history_summary_js_1.splitByCap)(storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })), LLM_HISTORY_MAX_TURNS);
431
- const historyFolded = capped.dropped.length > 0
432
- ? { omitted: capped.dropped.length, summarized: Boolean(session?.lastSummary) }
433
- : undefined;
434
- const conversation = session
435
- ? (0, llm_history_js_1.buildLlmHistory)(
436
- /*
437
- * The model reads who spoke and who they spoke to. The entity carries the speaker as a
438
- * relation and the addressee as a column; the history wants them as plain fields, and
439
- * without this mapping every line arrived unattributed — a room of people read as one
440
- * voice (ADR-0070 A15 decision ②).
441
- */
442
- storedRows.map(message => ({
443
- id: message.id,
444
- role: message.role,
445
- /*
446
- * A file sent in an earlier turn is not sent again - one line names it, and the model opens it
447
- * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
448
- */
449
- content: [
450
- message.content,
451
- ...(message.id !== userMessageId && Array.isArray(message.attachmentsJson) ? message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine) : []),
452
- /* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */
453
- ...(message.role === 'assistant' ? (0, proposal_outcome_js_1.offeredCardLines)(message.proposals) : [])
454
- ].join('\n'),
455
- senderId: message.creator?.id,
456
- senderName: message.creator?.name,
457
- addressee: message.addressee
458
- })), {
459
- maxTurns: LLM_HISTORY_MAX_TURNS,
460
- truncateAfterMessageId: input.truncateAfterMessageId,
461
- /* The message just stored is this turn's question — truncation must never drop it. */
462
- keepMessageIds: userMessageId ? [userMessageId] : undefined,
463
- summary: session.lastSummary
464
- ? { text: session.lastSummary, upToMessageId: session.summaryUpToMessageId }
465
- : undefined
466
- })
467
- : input.messages.map(message => ({ role: message.role, content: message.content }));
468
- /*
469
- * The files checked above, read once: the model reads them on this turn's question, and the tools get the same
470
- * files as `context.attachments` (ADR-0061, 2026-10-16 decision 2) - figure's step generator draws from the
471
- * picture the person sent. Never mixed into `hostContext`, which the client fills.
472
- */
473
- const turnFiles = await (0, turn_attachments_js_1.readTurnAttachments)(attachmentRows, (0, attachment_policy_js_1.textCharsOf)((0, registry_js_1.getAssistantMode)(input.mode?.kind ?? '')?.attachments), session_attachments_js_1.attachmentForModel);
474
- if (attachmentRows.length && conversation.length > 0) {
475
- const last = conversation[conversation.length - 1];
476
- if (last.role === 'user' && typeof last.content === 'string') {
477
- last.content = [{ type: 'text', text: last.content }, ...turnFiles.parts];
478
- }
479
- }
480
- else if (input.hostContext?.image?.data && conversation.length > 0) {
481
- /* The screen-image path (figure's rendered view) - not a file of the conversation. */
482
- const last = conversation[conversation.length - 1];
483
- if (last.role === 'user' && typeof last.content === 'string') {
484
- const raw = input.hostContext.image;
485
- const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\/[a-zA-Z]+;base64,/, '') : raw.data;
486
- const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData);
487
- last.content = [
488
- { type: 'text', text: last.content },
489
- { type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }
490
- ];
491
- }
492
- }
493
- const result = await (0, ai_client_base_1.registryAssistantChat)({
253
+ const turn = { input, context, t, settings: (0, resolve_js_1.resolveModeSettings)(input.mode, t) };
254
+ turn.session = await openSession(turn);
255
+ (0, station_session_guard_js_1.assertStationSession)(turn.session, input.hostContext, t);
256
+ const systemPrompt = await promptOf(turn);
257
+ const attachmentRows = await attachmentsOf(turn);
258
+ const userMessageId = await storeQuestion(turn, attachmentRows);
259
+ const { conversation, storedRows, historyFolded } = await historyOf(turn, userMessageId);
260
+ const turnFiles = await withTurnFiles(turn, conversation, attachmentRows);
261
+ const { session, settings } = turn;
262
+ const { domain } = context.state;
263
+ const result = await (0, mode_turn_js_1.runModeTurn)({
494
264
  client,
495
265
  messages: conversation,
496
- systemPrompt,
497
- toolCategories: settings.toolCategories,
266
+ settings: { ...settings, systemPrompt },
267
+ mode: input.mode,
498
268
  /*
499
269
  * What goes in front when the mode's tools do not fit in one call (ADR-0061 decision 9): the open page's, the
500
270
  * anchored record's and the latest selection's, then what this conversation used. The anchor and the selection are
@@ -508,92 +278,22 @@ let AssistantChatResolver = class AssistantChatResolver {
508
278
  }),
509
279
  tools: (0, used_tools_js_1.usedToolNames)(storedRows, [ai_client_base_1.OPEN_TOOLS])
510
280
  },
511
- /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */
512
- mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },
513
281
  /* And which stored conversation - the room a tool like the invite card acts on. The server's session, never the client's. */
514
282
  ...(session?.id ? { conversation: { id: session.id } } : {}),
515
283
  toolAccess: (0, tool_access_js_1.toolAccessFor)(context),
516
284
  /* The stop notice is a sentence a person reads — the server writes it in their language (ADR-0054). */
517
285
  t,
286
+ /* A long tool call says what it is doing to the person waiting on this turn, under the key their screen made. */
287
+ ...((0, assistant_progress_js_1.progressKeyOf)(input.hostContext) && context.state.user?.id
288
+ ? { progress: (text) => (0, assistant_progress_subscription_js_1.publishAssistantProgress)({ domainId: domain.id, userId: context.state.user.id, key: (0, assistant_progress_js_1.progressKeyOf)(input.hostContext), text }) }
289
+ : {}),
518
290
  hostContext: input.hostContext,
519
291
  attachments: turnFiles.forTools,
520
- /*
521
- * 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다
522
- * (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한
523
- * 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고
524
- * 자체를 안 보게 된다.
525
- */
526
- groundingSources: (0, grounding_sources_js_1.groundingSourcesFor)({
527
- systemPrompt,
528
- messages: conversation,
529
- hostContext: input.hostContext
530
- }),
531
- state: context.state,
532
- temperature: settings.temperature,
533
- maxTokens: settings.maxTokens,
534
- requireToolOnFirstTurn: settings.requireToolOnFirstTurn
292
+ state: context.state
535
293
  });
536
- /*
537
- * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면
538
- * 가려진 답이 목록에는 그대로 뜬다.
539
- */
540
294
  /* 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). */
541
295
  const { reply, suggestion } = (0, screen_rules_js_1.splitNextRequest)(result.reply);
542
- const answerDoors = (0, message_doors_js_1.doorsForAnswer)(result.loop.toolUsages ?? [], name => (0, ai_client_base_1.findToolSpec)(name, settings.toolCategories)?.doors);
543
- let assistantMessageId;
544
- if (session) {
545
- const stored = await messageRepo.save({
546
- session: { id: session.id },
547
- role: 'assistant',
548
- content: reply,
549
- /*
550
- * 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이
551
- * 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면
552
- * 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.
553
- */
554
- doors: answerDoors,
555
- toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,
556
- proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,
557
- groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,
558
- creator: user,
559
- updater: user,
560
- parentMessage: userMessageId ? { id: userMessageId } : undefined
561
- });
562
- assistantMessageId = stored.id;
563
- (0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: stored });
564
- /* The reply is session activity too. Leaving it out shows other participants "nothing new". */
565
- (0, session_activity_publish_js_1.publishSessionActivity)({
566
- domainId: domain.id,
567
- sessionId: session.id,
568
- kind: 'message',
569
- anchorType: session.anchorType,
570
- anchorId: session.anchorId,
571
- preview: reply,
572
- actorId: user?.id
573
- });
574
- await sessionRepo.update(session.id, {
575
- aiClientId: client.id,
576
- agentId: client.agent.id,
577
- updater: user,
578
- ...(0, session_inbox_js_1.activityPatch)(reply, new Date(), answerDoors)
579
- });
580
- /*
581
- * 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에
582
- * 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음
583
- * 턴이 「N 개 생략」으로 정직하게 알린다.
584
- *
585
- * 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)
586
- * 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴
587
- * 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.
588
- */
589
- void (0, fold_session_history_js_1.foldSessionHistory)({
590
- sessionId: session.id,
591
- domainId: domain.id,
592
- client,
593
- maxTurns: LLM_HISTORY_MAX_TURNS,
594
- locale: context.state?.lng
595
- });
596
- }
296
+ const assistantMessageId = await storeAnswer(turn, client, result, reply, userMessageId);
597
297
  return {
598
298
  reply,
599
299
  suggestion: suggestion ?? null,
@@ -631,4 +331,325 @@ tslib_1.__decorate([
631
331
  exports.AssistantChatResolver = AssistantChatResolver = tslib_1.__decorate([
632
332
  (0, type_graphql_1.Resolver)()
633
333
  ], AssistantChatResolver);
334
+ /**
335
+ * The domain's agent - the one picked, or the default (design/ai/agent-settings.md §4). Asked before anything is
336
+ * stored: a domain with no AI, or an agent it cannot use, is refused as itself.
337
+ */
338
+ async function agentOf(input, context) {
339
+ const { domain, user } = context.state;
340
+ let client;
341
+ try {
342
+ client = await (0, ai_client_base_1.aiClientFor)({
343
+ domain,
344
+ user,
345
+ agentId: input.agentId,
346
+ modeKind: input.mode.kind,
347
+ sessionId: input.sessionId
348
+ });
349
+ }
350
+ catch (error) {
351
+ (0, shell_1.rethrowSpoken)(error, context);
352
+ }
353
+ /* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */
354
+ context.state.aiAgentId = client.agent.id;
355
+ return client;
356
+ }
357
+ /** The stored conversation this turn writes to, when it has one - this person's to write, and this kind's. */
358
+ async function openSession({ input, context, t }) {
359
+ if (!input.sessionId)
360
+ return undefined;
361
+ const { domain, user } = context.state;
362
+ const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
363
+ const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } });
364
+ if (!found)
365
+ throw new Error(t('ai-assistant.text.session-not-found', { defaultValue: 'this conversation is not here any more. reload the list.' }));
366
+ /*
367
+ * A private conversation is written by its people only - and here more than anywhere: the answer is
368
+ * built on this conversation's history, so an outsider's question would read it back to them.
369
+ */
370
+ await (0, session_write_gate_js_1.assertMayWriteSession)({
371
+ session: found,
372
+ userId: user?.id,
373
+ isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, found.id, user?.id),
374
+ t: (key, options) => t(key, options)
375
+ });
376
+ if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {
377
+ throw new Error(context.t('ai-assistant.text.other-figure-history', {
378
+ defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'
379
+ }));
380
+ }
381
+ if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {
382
+ throw new Error(context.t('ai-assistant.text.application-vs-model-history', {
383
+ defaultValue: 'this conversation is about the application, not about a model. open the one you want.'
384
+ }));
385
+ }
386
+ /*
387
+ * 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이
388
+ * 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.
389
+ */
390
+ const verdict = (0, session_kind_js_1.judgeSessionKind)(found.kind, input.mode.kind);
391
+ if (verdict.action === 'refuse') {
392
+ throw new Error(t('ai-assistant.text.session-kind-mismatch', {
393
+ ...verdict.params,
394
+ defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'
395
+ }));
396
+ }
397
+ if (verdict.action === 'stamp') {
398
+ /* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */
399
+ await sessionRepo.update(found.id, { kind: verdict.kind });
400
+ found.kind = verdict.kind;
401
+ }
402
+ return found;
403
+ }
404
+ /** The system prompt of this turn: the mode's, with the open subject and the screen's lines. */
405
+ async function promptOf({ input, context, settings, session }) {
406
+ const { domain } = context.state;
407
+ const subjectLine = session
408
+ ? await (0, ai_client_base_1.openSubjectLine)({
409
+ anchorType: session.anchorType,
410
+ anchorId: session.anchorId,
411
+ domain,
412
+ state: context.state
413
+ })
414
+ : undefined;
415
+ /* What the person has in front of them besides the subject - the screen's unread notices (ADR-0199 amendment 1). */
416
+ const screenLines = await (0, turn_lines_js_1.turnLinesOf)({ page: input.page, state: context.state });
417
+ return (0, mode_categories_js_1.turnSystemPrompt)(settings.systemPrompt, { subjectLine: [subjectLine, ...screenLines].filter(Boolean).join('\n\n') || undefined, page: input.page });
418
+ }
419
+ /**
420
+ * Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by
421
+ * attachToConversation; one that is not this conversation's is refused, never read. The policy is the
422
+ * mode's - checked again here, since the door is the authority, not the screen.
423
+ */
424
+ async function attachmentsOf({ input, context, t, session }) {
425
+ const { domain } = context.state;
426
+ const attachmentRows = [];
427
+ if (input.attachmentIds?.length) {
428
+ if (!session)
429
+ throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }));
430
+ for (const id of input.attachmentIds) {
431
+ const row = await (0, session_attachments_js_1.findChatAttachment)(domain.id, session.id, id);
432
+ if (!row)
433
+ throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }));
434
+ attachmentRows.push(row);
435
+ }
436
+ const refusal = (0, attachment_policy_js_1.refuseAttachments)((0, registry_js_1.getAssistantMode)(input.mode.kind)?.attachments, attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) })));
437
+ if (refusal)
438
+ throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...refusal, defaultValue: refusal.code }));
439
+ }
440
+ return attachmentRows;
441
+ }
442
+ /** The person's question stored, announced and its @-mentions seated; its id. Nothing is stored without a session. */
443
+ async function storeQuestion({ input, context, session }, attachmentRows) {
444
+ const lastUserMessage = input.messages[input.messages.length - 1];
445
+ if (!session || lastUserMessage?.role !== 'user')
446
+ return undefined;
447
+ const { domain, user } = context.state;
448
+ const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
449
+ const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
450
+ const previousLast = await messageRepo.findOne({
451
+ where: { session: { id: session.id } },
452
+ order: { createdAt: 'DESC' }
453
+ });
454
+ const saved = await messageRepo.save({
455
+ session: { id: session.id },
456
+ role: 'user',
457
+ content: lastUserMessage.content,
458
+ /*
459
+ * This door is the one people call to ask the assistant, so a turn stored here was for the
460
+ * assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never
461
+ * from the request — two sources for one fact can disagree.
462
+ */
463
+ addressee: 'assistant',
464
+ attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(session_attachments_js_1.describeAttachment)) : undefined,
465
+ creator: user,
466
+ updater: user,
467
+ parentMessage: previousLast ? { id: previousLast.id } : undefined
468
+ });
469
+ /*
470
+ * Session activity is denormalised for the list: most-recent ordering and another
471
+ * participant's unread badge read it. Best effort — a conversation must not fail because a
472
+ * list sorts one position late.
473
+ */
474
+ try {
475
+ const patch = (0, session_inbox_js_1.activityPatch)(lastUserMessage.content);
476
+ if (!session.name)
477
+ patch.name = (0, session_inbox_js_1.autoSessionName)(lastUserMessage.content);
478
+ await sessionRepo.update(session.id, patch);
479
+ }
480
+ catch {
481
+ /* noop */
482
+ }
483
+ /*
484
+ * 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을
485
+ * 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다. 공개 방에서 말한 사람도
486
+ * 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.
487
+ */
488
+ const invite = await (0, mention_invite_js_1.seatTurn)({
489
+ content: lastUserMessage.content,
490
+ sessionId: session.id,
491
+ domainId: domain.id,
492
+ inviter: user,
493
+ participants: (0, shell_1.getRepository)(chat_session_participant_js_1.ChatSessionParticipant),
494
+ visibility: session.visibility
495
+ });
496
+ /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */
497
+ await (0, invite_notification_js_1.sendInviteNotification)(context.state?.sendNotice, invite.invited, user, session?.name, undefined, (0, request_translator_js_1.requestTranslator)(context));
498
+ (0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: saved });
499
+ (0, session_activity_publish_js_1.publishSessionActivity)({
500
+ domainId: domain.id,
501
+ sessionId: session.id,
502
+ kind: 'message',
503
+ anchorType: session.anchorType,
504
+ anchorId: session.anchorId,
505
+ preview: lastUserMessage.content,
506
+ actorId: user?.id
507
+ });
508
+ return saved.id;
509
+ }
510
+ /** What the model reads of this conversation: the stored turns this reader may see, capped and summarised. */
511
+ async function historyOf({ input, context, session }, userMessageId) {
512
+ const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
513
+ const readRows = session
514
+ ? await messageRepo.find({
515
+ where: { session: { id: session.id } },
516
+ order: { createdAt: 'ASC' },
517
+ relations: ['creator']
518
+ })
519
+ : [];
520
+ /*
521
+ * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도
522
+ * 안 지난 사람이 "아까 그 수 다시 말해 줘" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은
523
+ * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런
524
+ * 말이 없었다고 답하고, 그것은 거짓말이다.
525
+ */
526
+ const storedRows = await (0, reader_gate_js_1.readerGate)(context)(readRows);
527
+ const capped = (0, history_summary_js_1.splitByCap)(storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })), LLM_HISTORY_MAX_TURNS);
528
+ const historyFolded = capped.dropped.length > 0
529
+ ? { omitted: capped.dropped.length, summarized: Boolean(session?.lastSummary) }
530
+ : undefined;
531
+ const conversation = session
532
+ ? (0, llm_history_js_1.buildLlmHistory)(
533
+ /*
534
+ * The model reads who spoke and who they spoke to. The entity carries the speaker as a
535
+ * relation and the addressee as a column; the history wants them as plain fields, and
536
+ * without this mapping every line arrived unattributed — a room of people read as one
537
+ * voice (ADR-0070 A15 decision ②).
538
+ */
539
+ storedRows.map(message => ({
540
+ id: message.id,
541
+ role: message.role,
542
+ /*
543
+ * A file sent in an earlier turn is not sent again - one line names it, and the model opens it
544
+ * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
545
+ */
546
+ content: [
547
+ message.content,
548
+ ...(message.id !== userMessageId && Array.isArray(message.attachmentsJson) ? message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine) : []),
549
+ /* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */
550
+ ...(message.role === 'assistant' ? (0, proposal_outcome_js_1.offeredCardLines)(message.proposals) : [])
551
+ ].join('\n'),
552
+ senderId: message.creator?.id,
553
+ senderName: message.creator?.name,
554
+ addressee: message.addressee
555
+ })), {
556
+ maxTurns: LLM_HISTORY_MAX_TURNS,
557
+ truncateAfterMessageId: input.truncateAfterMessageId,
558
+ /* The message just stored is this turn's question — truncation must never drop it. */
559
+ keepMessageIds: userMessageId ? [userMessageId] : undefined,
560
+ summary: session.lastSummary
561
+ ? { text: session.lastSummary, upToMessageId: session.summaryUpToMessageId }
562
+ : undefined
563
+ })
564
+ : input.messages.map(message => ({ role: message.role, content: message.content }));
565
+ return { conversation, storedRows, historyFolded };
566
+ }
567
+ /** The files of this turn read once, on the question; or the screen's picture. What the tools get of them. */
568
+ async function withTurnFiles({ input }, conversation, attachmentRows) {
569
+ const turnFiles = await (0, turn_attachments_js_1.readTurnAttachments)(attachmentRows, (0, attachment_policy_js_1.textCharsOf)((0, registry_js_1.getAssistantMode)(input.mode?.kind ?? '')?.attachments), session_attachments_js_1.attachmentForModel);
570
+ if (attachmentRows.length && conversation.length > 0) {
571
+ const last = conversation[conversation.length - 1];
572
+ if (last.role === 'user' && typeof last.content === 'string') {
573
+ last.content = [{ type: 'text', text: last.content }, ...turnFiles.parts];
574
+ }
575
+ }
576
+ else if (input.hostContext?.image?.data && conversation.length > 0) {
577
+ /* The screen-image path (figure's rendered view) - not a file of the conversation. */
578
+ const last = conversation[conversation.length - 1];
579
+ if (last.role === 'user' && typeof last.content === 'string') {
580
+ const raw = input.hostContext.image;
581
+ const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\/[a-zA-Z]+;base64,/, '') : raw.data;
582
+ const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData);
583
+ last.content = [
584
+ { type: 'text', text: last.content },
585
+ { type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }
586
+ ];
587
+ }
588
+ }
589
+ return turnFiles;
590
+ }
591
+ /** The answer stored and announced, the conversation's activity moved on, its history folded later; the answer's id. */
592
+ async function storeAnswer({ context, settings, session }, client, result, reply, userMessageId) {
593
+ /*
594
+ * 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면
595
+ * 가려진 답이 목록에는 그대로 뜬다.
596
+ */
597
+ const answerDoors = (0, message_doors_js_1.doorsForAnswer)(result.loop.toolUsages ?? [], name => (0, ai_client_base_1.findToolSpec)(name, settings.toolCategories)?.doors);
598
+ if (!session)
599
+ return undefined;
600
+ const { domain, user } = context.state;
601
+ const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
602
+ const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
603
+ const stored = await messageRepo.save({
604
+ session: { id: session.id },
605
+ role: 'assistant',
606
+ content: reply,
607
+ /*
608
+ * 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이
609
+ * 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면
610
+ * 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.
611
+ */
612
+ doors: answerDoors,
613
+ toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,
614
+ proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,
615
+ groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,
616
+ creator: user,
617
+ updater: user,
618
+ parentMessage: userMessageId ? { id: userMessageId } : undefined
619
+ });
620
+ (0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: stored });
621
+ /* The reply is session activity too. Leaving it out shows other participants "nothing new". */
622
+ (0, session_activity_publish_js_1.publishSessionActivity)({
623
+ domainId: domain.id,
624
+ sessionId: session.id,
625
+ kind: 'message',
626
+ anchorType: session.anchorType,
627
+ anchorId: session.anchorId,
628
+ preview: reply,
629
+ actorId: user?.id
630
+ });
631
+ await sessionRepo.update(session.id, {
632
+ aiClientId: client.id,
633
+ agentId: client.agent.id,
634
+ updater: user,
635
+ ...(0, session_inbox_js_1.activityPatch)(reply, new Date(), answerDoors)
636
+ });
637
+ /*
638
+ * 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에
639
+ * 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음
640
+ * 턴이 「N 개 생략」으로 정직하게 알린다.
641
+ *
642
+ * 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)
643
+ * 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴
644
+ * 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.
645
+ */
646
+ void (0, fold_session_history_js_1.foldSessionHistory)({
647
+ sessionId: session.id,
648
+ domainId: domain.id,
649
+ client,
650
+ maxTurns: LLM_HISTORY_MAX_TURNS,
651
+ locale: context.state?.lng
652
+ });
653
+ return stored.id;
654
+ }
634
655
  //# sourceMappingURL=assistant-chat-resolver.js.map