@things-factory/ai-assistant 10.1.168 → 10.1.170
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-server/service/assistant-chat-resolver.js +7 -3
- package/dist-server/service/assistant-chat-resolver.js.map +1 -1
- package/dist-server/service/assistant-mode/mode-categories.d.ts +12 -0
- package/dist-server/service/assistant-mode/mode-categories.js +19 -0
- package/dist-server/service/assistant-mode/mode-categories.js.map +1 -0
- package/dist-server/service/assistant-mode/registry.js +3 -1
- package/dist-server/service/assistant-mode/registry.js.map +1 -1
- package/dist-server/service/assistant-mode/resolve.d.ts +2 -12
- package/dist-server/service/assistant-mode/resolve.js +4 -16
- package/dist-server/service/assistant-mode/resolve.js.map +1 -1
- package/dist-server/service/chat-message/proposal-outcome.d.ts +7 -0
- package/dist-server/service/chat-message/proposal-outcome.js +25 -0
- package/dist-server/service/chat-message/proposal-outcome.js.map +1 -1
- package/dist-server/service/data-read/list-read.js +4 -2
- package/dist-server/service/data-read/list-read.js.map +1 -1
- package/dist-server/service/data-read/read-target.d.ts +14 -3
- package/dist-server/service/data-read/read-target.js +43 -6
- package/dist-server/service/data-read/read-target.js.map +1 -1
- package/dist-server/service/data-read/read-tools.d.ts +9 -9
- package/dist-server/service/data-read/read-tools.js +14 -3
- package/dist-server/service/data-read/read-tools.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/server/service/assistant-chat-resolver.ts +7 -4
- package/server/service/assistant-mode/mode-categories.ts +15 -0
- package/server/service/assistant-mode/registry.test.ts +10 -0
- package/server/service/assistant-mode/registry.ts +3 -1
- package/server/service/assistant-mode/resolve.ts +2 -14
- package/server/service/chat-message/proposal-outcome.test.ts +13 -1
- package/server/service/chat-message/proposal-outcome.ts +24 -0
- package/server/service/data-read/data-read.test.ts +62 -0
- package/server/service/data-read/list-read.ts +4 -2
- package/server/service/data-read/read-target.ts +49 -8
- package/server/service/data-read/read-tools.ts +15 -3
|
@@ -35,6 +35,7 @@ const chat_session_js_1 = require("./chat-session/chat-session.js");
|
|
|
35
35
|
const station_session_guard_js_1 = require("./chat-session/station-session-guard.js");
|
|
36
36
|
const chat_message_js_1 = require("./chat-message/chat-message.js");
|
|
37
37
|
const llm_history_js_1 = require("./chat-message/llm-history.js");
|
|
38
|
+
const proposal_outcome_js_1 = require("./chat-message/proposal-outcome.js");
|
|
38
39
|
const history_summary_js_1 = require("./chat-message/history-summary.js");
|
|
39
40
|
const fold_session_history_js_1 = require("./chat-message/fold-session-history.js");
|
|
40
41
|
const grounding_sources_js_1 = require("./grounding-sources.js");
|
|
@@ -440,9 +441,12 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
440
441
|
* A file sent in an earlier turn is not sent again - one line names it, and the model opens it
|
|
441
442
|
* with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
|
|
442
443
|
*/
|
|
443
|
-
content:
|
|
444
|
-
|
|
445
|
-
|
|
444
|
+
content: [
|
|
445
|
+
message.content,
|
|
446
|
+
...(message.id !== userMessageId && Array.isArray(message.attachmentsJson) ? message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine) : []),
|
|
447
|
+
/* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */
|
|
448
|
+
...(message.role === 'assistant' ? (0, proposal_outcome_js_1.offeredCardLines)(message.proposals) : [])
|
|
449
|
+
].join('\n'),
|
|
446
450
|
senderId: message.creator?.id,
|
|
447
451
|
senderName: message.creator?.name,
|
|
448
452
|
addressee: message.addressee
|
|
@@ -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,mEAAoI;AAEpI,oEAA4D;AAC5D,sFAA8E;AAC9E,oE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B,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;AA9ZY,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;;0DA4Y1D;gCA7ZU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CA8ZjC","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, 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 { splitByCap } from './chat-message/history-summary.js'\nimport { foldSessionHistory } from './chat-message/fold-session-history.js'\nimport { groundingSourcesFor } from './grounding-sources.js'\nimport { publishChatMessage } from './chat-message/chat-message-publish.js'\nimport { publishSessionActivity } from './chat-session/session-activity-publish.js'\nimport { activityPatch, autoSessionName } from './chat-session/session-inbox.js'\nimport { toolAccessFor } from './tool-access.js'\nimport { ChatSessionParticipant } from './chat-session-participant/chat-session-participant.js'\nimport { doorsForAnswer } from './chat-message/message-doors.js'\nimport { judgeSessionKind } from './chat-session/session-kind.js'\nimport { readerGate } from './chat-message/reader-gate.js'\nimport { inviteMentionedUsers } from './chat-session-participant/mention-invite.js'\nimport { buildInviteNotification } from './chat-session-participant/invite-notification.js'\nimport { isSessionParticipant } from './chat-session-participant/participant-lookup.js'\nimport { assertMayWriteSession } from './chat-session/session-write-gate.js'\nimport { attachmentHistoryLine, refuseAttachments, 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 { 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\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 */\n const invite = await inviteMentionedUsers({\n content: lastUserMessage.content,\n sessionId: session.id!,\n domainId: domain.id,\n inviter: user,\n participants: getRepository(ChatSessionParticipant),\n visibility: (session as any).visibility\n })\n if (invite.invited.length > 0) {\n const payload = buildInviteNotification(invite.invited, undefined, user, (session as any)?.name)\n try {\n if (payload) await (context.state as any)?.notify?.(payload)\n } catch {\n /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다. */\n }\n }\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: saved } as any)\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: lastUserMessage.content,\n actorId: user?.id\n })\n }\n\n /*\n * 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.\n *\n * 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드\n * 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —\n * 모델에게는 「N 개 생략」을 적어 보내면서.\n */\n const readRows = session\n ? await messageRepo.find({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'ASC' },\n relations: ['creator']\n })\n : []\n /*\n * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도\n * 안 지난 사람이 \"아까 그 수 다시 말해 줘\" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은\n * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런\n * 말이 없었다고 답하고, 그것은 거짓말이다.\n */\n const storedRows = await readerGate(context)(readRows)\n const capped = splitByCap(\n storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })),\n LLM_HISTORY_MAX_TURNS\n )\n const historyFolded =\n capped.dropped.length > 0\n ? { omitted: capped.dropped.length, summarized: Boolean((session as any)?.lastSummary) }\n : undefined\n\n const conversation = session\n ? buildLlmHistory(\n /*\n * The model reads who spoke and who they spoke to. The entity carries the speaker as a\n * relation and the addressee as a column; the history wants them as plain fields, and\n * without this mapping every line arrived unattributed — a room of people read as one\n * voice (ADR-0070 A15 decision ②).\n */\n storedRows.map(message => ({\n id: message.id,\n role: message.role,\n /*\n * A file sent in an earlier turn is not sent again - one line names it, and the model opens it\n * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).\n */\n content:\n message.id !== userMessageId && (message as any).attachmentsJson?.length\n ? [message.content, ...(message as any).attachmentsJson.map(attachmentHistoryLine)].join('\\n')\n : message.content,\n senderId: (message as any).creator?.id,\n senderName: (message as any).creator?.name,\n addressee: (message as any).addressee\n })),\n {\n maxTurns: LLM_HISTORY_MAX_TURNS,\n truncateAfterMessageId: input.truncateAfterMessageId,\n /* The message just stored is this turn's question — truncation must never drop it. */\n keepMessageIds: userMessageId ? [userMessageId] : undefined,\n summary: (session as any).lastSummary\n ? { text: (session as any).lastSummary, upToMessageId: (session as any).summaryUpToMessageId }\n : undefined\n }\n )\n : input.messages.map(message => ({ role: message.role as any, content: message.content }))\n\n /*\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 /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n toolAccess: toolAccessFor(context),\n /* The stop notice is a sentence a person reads — the server writes it in their language (ADR-0054). */\n t,\n hostContext: input.hostContext,\n 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,mEAAoI;AAEpI,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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QAAQ,EAAE,qBAAqB;gBAC/B,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;AAhaY,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;;0DA8Y1D;gCA/ZU,qBAAqB;IADjC,IAAA,uBAAQ,GAAE;GACE,qBAAqB,CAgajC","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, 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 { inviteMentionedUsers } from './chat-session-participant/mention-invite.js'\nimport { buildInviteNotification } from './chat-session-participant/invite-notification.js'\nimport { isSessionParticipant } from './chat-session-participant/participant-lookup.js'\nimport { assertMayWriteSession } from './chat-session/session-write-gate.js'\nimport { attachmentHistoryLine, refuseAttachments, 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 { 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\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 */\n const invite = await inviteMentionedUsers({\n content: lastUserMessage.content,\n sessionId: session.id!,\n domainId: domain.id,\n inviter: user,\n participants: getRepository(ChatSessionParticipant),\n visibility: (session as any).visibility\n })\n if (invite.invited.length > 0) {\n const payload = buildInviteNotification(invite.invited, undefined, user, (session as any)?.name)\n try {\n if (payload) await (context.state as any)?.notify?.(payload)\n } catch {\n /* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다. */\n }\n }\n\n publishChatMessage({ domainId: domain.id, sessionId: session.id, message: saved } as any)\n publishSessionActivity({\n domainId: domain.id,\n sessionId: session.id!,\n kind: 'message',\n anchorType: (session as any).anchorType,\n anchorId: (session as any).anchorId,\n preview: lastUserMessage.content,\n actorId: user?.id\n })\n }\n\n /*\n * 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.\n *\n * 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드\n * 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —\n * 모델에게는 「N 개 생략」을 적어 보내면서.\n */\n const readRows = session\n ? await messageRepo.find({\n where: { session: { id: session.id } as any },\n order: { createdAt: 'ASC' },\n relations: ['creator']\n })\n : []\n /*\n * 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도\n * 안 지난 사람이 \"아까 그 수 다시 말해 줘\" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은\n * 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런\n * 말이 없었다고 답하고, 그것은 거짓말이다.\n */\n const storedRows = await readerGate(context)(readRows)\n const capped = splitByCap(\n storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })),\n LLM_HISTORY_MAX_TURNS\n )\n const historyFolded =\n capped.dropped.length > 0\n ? { omitted: capped.dropped.length, summarized: Boolean((session as any)?.lastSummary) }\n : undefined\n\n const conversation = session\n ? buildLlmHistory(\n /*\n * The model reads who spoke and who they spoke to. The entity carries the speaker as a\n * relation and the addressee as a column; the history wants them as plain fields, and\n * without this mapping every line arrived unattributed — a room of people read as one\n * voice (ADR-0070 A15 decision ②).\n */\n storedRows.map(message => ({\n id: message.id,\n role: message.role,\n /*\n * A file sent in an earlier turn is not sent again - one line names it, and the model opens it\n * with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).\n */\n content: [\n message.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 /* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */\n mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },\n toolAccess: toolAccessFor(context),\n /* The stop notice is a sentence a person reads — the server writes it in their language (ADR-0054). */\n t,\n hostContext: input.hostContext,\n 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"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
|
|
3
|
+
* takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
|
|
4
|
+
*/
|
|
5
|
+
export declare function modeToolCategories(mode: {
|
|
6
|
+
toolCategories?: string[];
|
|
7
|
+
attachments?: {
|
|
8
|
+
kinds?: string[];
|
|
9
|
+
};
|
|
10
|
+
entryTargets?: string[];
|
|
11
|
+
readTargets?: string[];
|
|
12
|
+
}): string[] | undefined;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.modeToolCategories = modeToolCategories;
|
|
4
|
+
/* Pure - read by the resolver and by the boot report, so the report and the conversation open the same tools. */
|
|
5
|
+
/**
|
|
6
|
+
* The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
|
|
7
|
+
* takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
|
|
8
|
+
*/
|
|
9
|
+
function modeToolCategories(mode) {
|
|
10
|
+
const extra = [
|
|
11
|
+
/* Every conversation may put a large result on the AI 작업판 (design/ai/workspace.md). */
|
|
12
|
+
'assistant-workspace',
|
|
13
|
+
...(mode.attachments?.kinds?.length ? ['chat-attachments'] : []),
|
|
14
|
+
...(mode.entryTargets ?? []).map(key => `data-entry:${key}`),
|
|
15
|
+
...(mode.readTargets ?? []).map(key => `data-read:${key}`)
|
|
16
|
+
];
|
|
17
|
+
return [...new Set([...(mode.toolCategories ?? []), ...extra])];
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=mode-categories.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mode-categories.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/mode-categories.ts"],"names":[],"mappings":";;AAKA,gDASC;AAdD,iHAAiH;AACjH;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,IAAwH;IACzJ,MAAM,KAAK,GAAG;QACZ,uFAAuF;QACvF,qBAAqB;QACrB,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAChE,GAAG,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,cAAc,GAAG,EAAE,CAAC;QAC5D,GAAG,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,aAAa,GAAG,EAAE,CAAC;KAC3D,CAAA;IACD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;AACjE,CAAC","sourcesContent":["/* Pure - read by the resolver and by the boot report, so the report and the conversation open the same tools. */\n/**\n * The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it\n * takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).\n */\nexport function modeToolCategories(mode: { toolCategories?: string[]; attachments?: { kinds?: string[] }; entryTargets?: string[]; readTargets?: string[] }): string[] | undefined {\n const extra = [\n /* Every conversation may put a large result on the AI 작업판 (design/ai/workspace.md). */\n 'assistant-workspace',\n ...(mode.attachments?.kinds?.length ? ['chat-attachments'] : []),\n ...(mode.entryTargets ?? []).map(key => `data-entry:${key}`),\n ...(mode.readTargets ?? []).map(key => `data-read:${key}`)\n ]\n return [...new Set([...(mode.toolCategories ?? []), ...extra])]\n}\n"]}
|
|
@@ -21,6 +21,7 @@ exports.clearAssistantModes = clearAssistantModes;
|
|
|
21
21
|
*/
|
|
22
22
|
const entry_target_js_1 = require("../data-entry/entry-target.js");
|
|
23
23
|
const ai_client_base_1 = require("@things-factory/ai-client-base");
|
|
24
|
+
const mode_categories_1 = require("./mode-categories");
|
|
24
25
|
const modes = new Map();
|
|
25
26
|
const KIND = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
|
|
26
27
|
function registerAssistantMode(spec) {
|
|
@@ -82,7 +83,8 @@ function getAssistantModeWarnings() {
|
|
|
82
83
|
}
|
|
83
84
|
}
|
|
84
85
|
for (const mode of modes.values()) {
|
|
85
|
-
|
|
86
|
+
/* The tools the conversation opens - its read and entry targets' too, as the resolver opens them. */
|
|
87
|
+
const exposed = new Set((0, ai_client_base_1.getToolSpecsFor)((0, mode_categories_1.modeToolCategories)(mode) ?? []).map(spec => spec.name));
|
|
86
88
|
for (const slash of mode.slashTemplates ?? []) {
|
|
87
89
|
for (const tool of slash.tools ?? []) {
|
|
88
90
|
if (exposed.has(tool))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/registry.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/registry.ts"],"names":[],"mappings":";;AAuBA,sDAuBC;AAED,4CAEC;AAED,gDAEC;AAOD,4DAiDC;AAGD,0DAEC;AAGD,kDAEC;AAxHD;;;;;;;;;;;;GAYG;AACH,mEAA6D;AAC7D,mEAAgE;AAChE,uDAAsD;AAItD,MAAM,KAAK,GAAG,IAAI,GAAG,EAA6B,CAAA;AAElD,MAAM,IAAI,GAAG,oCAAoC,CAAA;AAEjD,SAAgB,qBAAqB,CAAC,IAAuB;IAC3D,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,kCAAkC,IAAI,EAAE,IAAI,2DAA2D;YACrG,8FAA8F,CACjG,CAAA;IACH,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CACb,uCAAuC,IAAI,CAAC,IAAI,mDAAmD;YACjG,4EAA4E,CAC/E,CAAA;IACH,CAAC;IAED,IAAI,KAAK,CAAC,GAAG,CAA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CAAC,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,kEAAkE;iBAC/G,CAAC,CAAA;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,uHAAuH;AACvH,SAAgB,uBAAuB,CAAC,OAAe;IACrD,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAA;AAClF,CAAC;AAED,iBAAiB;AACjB,SAAgB,mBAAmB;IACjC,KAAK,CAAC,KAAK,EAAE,CAAA;AACf,CAAC","sourcesContent":["/**\n * The mode registry — one place that knows what each conversation is.\n *\n * Registration refuses what cannot be true later: a kind that is not `<app>.<surface>` (the door\n * looks a mode up by that name), an empty persona (the field this whole change exists to take off\n * the wire), and a second declaration of a kind that is already declared — two declarations of one\n * conversation disagree, and the one that wins would be whichever module booted last.\n *\n * What it does not refuse is a `/` sentence naming a tool the mode does not expose. That check\n * reads the tool registry, which fills up as modules boot, so it runs when asked rather than at\n * registration: `getAssistantModeWarnings()` is the answer as of now, and the boot report reads it\n * after every module is in.\n */\nimport { entryTargetOf } from '../data-entry/entry-target.js'\nimport { getToolSpecsFor } from '@things-factory/ai-client-base'\nimport { modeToolCategories } from './mode-categories'\n\nimport type { AssistantModeSpec, AssistantModeWarning } from './types'\n\nconst modes = new Map<string, AssistantModeSpec>()\n\nconst KIND = /^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$/\n\nexport function registerAssistantMode(spec: AssistantModeSpec): void {\n if (!KIND.test(String(spec?.kind ?? ''))) {\n throw new Error(\n `[ai-assistant/assistant-mode] '${spec?.kind}' is not a mode kind. Use <app>.<surface> in lowercase — ` +\n \"'twin.space', 'plant.station', 'figure.modeller'. The client names the conversation by this.\"\n )\n }\n\n if (!String(spec.systemPrompt ?? '').trim()) {\n throw new Error(\n `[ai-assistant/assistant-mode] mode '${spec.kind}' has no systemPrompt. Who the assistant is on a ` +\n 'surface belongs to the server that owns the surface (ADR-0061 decision 7).'\n )\n }\n\n if (modes.has(spec.kind)) {\n throw new Error(\n `[ai-assistant/assistant-mode] mode '${spec.kind}' is already registered. Two declarations of one ` +\n 'conversation disagree, and which one wins would depend on boot order. Give the second one its own kind.'\n )\n }\n\n modes.set(spec.kind, spec)\n}\n\nexport function getAssistantMode(kind: string): AssistantModeSpec | undefined {\n return modes.get(kind)\n}\n\nexport function listAssistantModes(): ReadonlyArray<AssistantModeSpec> {\n return Array.from(modes.values())\n}\n\n/**\n * The promises a mode makes that its tools cannot keep, as of now.\n *\n * Read after boot: a mode may register before the category its slash sentences use.\n */\nexport function getAssistantModeWarnings(): ReadonlyArray<AssistantModeWarning> {\n const out: AssistantModeWarning[] = []\n\n /*\n * 한 화면에 대화 하나 — design/ai/screen-pattern.md §3. 같은 subject 를 두 대화가 적으면 화면은 어느 쪽을\n * 열지 모르고, 선택기로 사람에게 넘기면 원칙 3 을 어긴다. 성격이 다른 물음은 그 대화가 도구를 더 연다.\n */\n const owners = new Map<string, string[]>()\n for (const mode of modes.values()) {\n for (const subject of mode.subjects ?? []) owners.set(subject, [...(owners.get(subject) ?? []), mode.kind])\n }\n for (const [subject, kinds] of owners) {\n if (kinds.length < 2) continue\n out.push({\n code: 'assistant-mode-subject-claimed-twice',\n params: { kind: kinds[0], subject, kinds },\n message: `subject '${subject}' has more than one conversation (${kinds.join(', ')}) — a screen has one conversation; open more tools in one of them`\n })\n }\n\n for (const mode of modes.values()) {\n /* A record the mode says it enters, which no app registered - the tool never appears and the person is told nothing. */\n for (const key of mode.entryTargets ?? []) {\n if (entryTargetOf(key)) continue\n out.push({\n code: 'assistant-mode-entry-target-unknown',\n params: { kind: mode.kind, target: key },\n message: `mode '${mode.kind}' enters '${key}', which no application registered with registerEntryTarget`\n })\n }\n }\n\n for (const mode of modes.values()) {\n /* The tools the conversation opens - its read and entry targets' too, as the resolver opens them. */\n const exposed = new Set(getToolSpecsFor(modeToolCategories(mode) ?? []).map(spec => spec.name))\n for (const slash of mode.slashTemplates ?? []) {\n for (const tool of slash.tools ?? []) {\n if (exposed.has(tool)) continue\n out.push({\n code: 'assistant-mode-slash-outside-tools',\n params: { kind: mode.kind, slash: slash.name, tool },\n message:\n `mode '${mode.kind}' offers '/${slash.name}', which needs '${tool}' — not in its tool categories ` +\n `[${(mode.toolCategories ?? []).join(', ')}]. The person presses it and the model answers without doing it.`\n })\n }\n }\n }\n return out\n}\n\n/** The conversation a screen showing this kind of subject opens — one per subject (design/ai/screen-pattern.md §3). */\nexport function assistantModeForSubject(subject: string): AssistantModeSpec | undefined {\n return [...modes.values()].find(mode => (mode.subjects ?? []).includes(subject))\n}\n\n/** Test only. */\nexport function clearAssistantModes(): void {\n modes.clear()\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AttachmentPolicy } from '../chat-session/attachment-policy.js';
|
|
2
|
+
import { modeToolCategories } from './mode-categories';
|
|
2
3
|
export type Translate = (key: string, params?: Record<string, any>) => string;
|
|
3
4
|
export interface AssistantModeRef {
|
|
4
5
|
/** Which conversation this is — a registered `<app>.<surface>`. */
|
|
@@ -13,18 +14,7 @@ export interface ModeSettings {
|
|
|
13
14
|
temperature?: number;
|
|
14
15
|
maxTokens?: number;
|
|
15
16
|
}
|
|
16
|
-
|
|
17
|
-
* The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
|
|
18
|
-
* takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
|
|
19
|
-
*/
|
|
20
|
-
export declare function modeToolCategories(mode: {
|
|
21
|
-
toolCategories?: string[];
|
|
22
|
-
attachments?: {
|
|
23
|
-
kinds?: string[];
|
|
24
|
-
};
|
|
25
|
-
entryTargets?: string[];
|
|
26
|
-
readTargets?: string[];
|
|
27
|
-
}): string[] | undefined;
|
|
17
|
+
export { modeToolCategories };
|
|
28
18
|
/** The conversation's settings, from the server's declaration. */
|
|
29
19
|
export declare function resolveModeSettings(ref: AssistantModeRef, t: Translate): ModeSettings;
|
|
30
20
|
export interface AssistantModeSlashView {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.modeToolCategories =
|
|
3
|
+
exports.modeToolCategories = void 0;
|
|
4
4
|
exports.resolveModeSettings = resolveModeSettings;
|
|
5
5
|
exports.assistantModeView = assistantModeView;
|
|
6
6
|
/**
|
|
@@ -11,6 +11,8 @@ exports.assistantModeView = assistantModeView;
|
|
|
11
11
|
*/
|
|
12
12
|
const registry_1 = require("./registry");
|
|
13
13
|
const screen_rules_1 = require("./screen-rules");
|
|
14
|
+
const mode_categories_1 = require("./mode-categories");
|
|
15
|
+
Object.defineProperty(exports, "modeToolCategories", { enumerable: true, get: function () { return mode_categories_1.modeToolCategories; } });
|
|
14
16
|
/**
|
|
15
17
|
* A kind nobody registered. The sentence is the person's (ADR-0054); the code and the kind are for
|
|
16
18
|
* whoever reads the log — a screen naming a conversation the server does not have is a mismatched
|
|
@@ -25,20 +27,6 @@ function unknownModeError(kind, t) {
|
|
|
25
27
|
error.params = { kind };
|
|
26
28
|
return error;
|
|
27
29
|
}
|
|
28
|
-
/**
|
|
29
|
-
* The categories a mode opens: its own, the AI 작업판 (design/ai/workspace.md), the attachment reader when it
|
|
30
|
-
* takes files (design/ai/shared-dock.md §9-4), and one propose tool per record it may enter (design/ai/data-entry.md).
|
|
31
|
-
*/
|
|
32
|
-
function modeToolCategories(mode) {
|
|
33
|
-
const extra = [
|
|
34
|
-
/* Every conversation may put a large result on the AI 작업판 (design/ai/workspace.md). */
|
|
35
|
-
'assistant-workspace',
|
|
36
|
-
...(mode.attachments?.kinds?.length ? ['chat-attachments'] : []),
|
|
37
|
-
...(mode.entryTargets ?? []).map(key => `data-entry:${key}`),
|
|
38
|
-
...(mode.readTargets ?? []).map(key => `data-read:${key}`)
|
|
39
|
-
];
|
|
40
|
-
return [...new Set([...(mode.toolCategories ?? []), ...extra])];
|
|
41
|
-
}
|
|
42
30
|
/** The conversation's settings, from the server's declaration. */
|
|
43
31
|
function resolveModeSettings(ref, t) {
|
|
44
32
|
const kind = String(ref?.kind ?? '');
|
|
@@ -49,7 +37,7 @@ function resolveModeSettings(ref, t) {
|
|
|
49
37
|
/* The app's persona, with the rules every conversation follows (design/ai/screen-pattern.md §4). */
|
|
50
38
|
systemPrompt: (0, screen_rules_1.conversationPrompt)(mode.systemPrompt),
|
|
51
39
|
/* A mode that takes attachments can open the files sent in earlier turns (design/ai/shared-dock.md §9-4). */
|
|
52
|
-
toolCategories: modeToolCategories(mode),
|
|
40
|
+
toolCategories: (0, mode_categories_1.modeToolCategories)(mode),
|
|
53
41
|
requireToolOnFirstTurn: mode.requireToolOnFirstTurn,
|
|
54
42
|
temperature: mode.temperature,
|
|
55
43
|
maxTokens: mode.maxTokens
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/resolve.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/resolve.ts"],"names":[],"mappings":";;;AAiDA,kDAeC;AAyBD,8CAuBC;AA/GD;;;;;GAKG;AACH,yCAA6C;AAC7C,iDAAmD;AACnD,uDAAsD;AAqC7C,mGArCA,oCAAkB,OAqCA;AAzB3B;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,IAAY,EAAE,CAAY;IAClD,MAAM,KAAK,GAAQ,IAAI,KAAK,CAC1B,CAAC,CAAC,gCAAgC,EAAE;QAClC,YAAY,EAAE,2FAA2F;QACzG,IAAI,EAAE,IAAI,IAAI,GAAG;KAClB,CAAC,CACH,CAAA;IACD,KAAK,CAAC,IAAI,GAAG,w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AAW,CAAC;SAC/B,CAAC,CAAC;QACH,cAAc,EAAE,IAAI,CAAC,cAAc,IAAI,EAAE;QACzC,eAAe,EAAE,IAAI,CAAC,eAAe,IAAI,EAAE;QAC3C,WAAW,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,SAAS;QACrE,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;QAC5G,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACxC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;YACxB,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SACzC,CAAC,CAAC;QACH,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,SAAS;QACxE,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,SAAS;QACxE,WAAW,EAAE,IAAI,CAAC,WAAW;KAC9B,CAAA;AACH,CAAC","sourcesContent":["import type { AttachmentPolicy } from '../chat-session/attachment-policy.js'\n/**\n * What the door and the screen each take from a mode.\n *\n * Both start from the same declaration, so a screen cannot show `/` sentences for a conversation\n * the server would answer differently.\n */\nimport { getAssistantMode } from './registry'\nimport { conversationPrompt } from './screen-rules'\nimport { modeToolCategories } from './mode-categories'\nimport type { AssistantModeSlash } from './types'\n\nexport type Translate = (key: string, params?: Record<string, any>) => string\n\nexport interface AssistantModeRef {\n /** Which conversation this is — a registered `<app>.<surface>`. */\n kind: string\n /** What it is about. Part of the conversation's lifetime; the tools read it, not the settings. */\n target?: string\n}\n\n/**\n * A kind nobody registered. The sentence is the person's (ADR-0054); the code and the kind are for\n * whoever reads the log — a screen naming a conversation the server does not have is a mismatched\n * deployment, not something the person did.\n */\nfunction unknownModeError(kind: string, t: Translate): Error {\n const error: any = new Error(\n t('ai-assistant.text.unknown-mode', {\n defaultValue: 'this screen asked for a conversation this server does not have ({kind}). reload the page.',\n kind: kind || '—'\n })\n )\n error.code = 'unknown-assistant-mode'\n error.params = { kind }\n return error\n}\n\nexport interface ModeSettings {\n systemPrompt: string\n toolCategories?: string[]\n requireToolOnFirstTurn?: boolean\n temperature?: number\n maxTokens?: number\n}\n\nexport { modeToolCategories }\n\n/** The conversation's settings, from the server's declaration. */\nexport function resolveModeSettings(ref: AssistantModeRef, t: Translate): ModeSettings {\n const kind = String(ref?.kind ?? '')\n const mode = kind ? getAssistantMode(kind) : undefined\n\n if (!mode) throw unknownModeError(kind, t)\n\n return {\n /* The app's persona, with the rules every conversation follows (design/ai/screen-pattern.md §4). */\n systemPrompt: conversationPrompt(mode.systemPrompt),\n /* A mode that takes attachments can open the files sent in earlier turns (design/ai/shared-dock.md §9-4). */\n toolCategories: modeToolCategories(mode),\n requireToolOnFirstTurn: mode.requireToolOnFirstTurn,\n temperature: mode.temperature,\n maxTokens: mode.maxTokens\n }\n}\n\nexport interface AssistantModeSlashView {\n name: string\n description: string\n template: string\n}\n\nexport interface AssistantModeView {\n kind: string\n slashTemplates: AssistantModeSlashView[]\n catalogEntries: any[]\n proposalChoices: any[]\n placeholder?: string\n /** 빈 대화의 제목과 한 줄 — 이 대화가 무엇을 하는 자리인지. */\n intro?: { title: string; subtitle: string }\n /** 빈 대화의 예시 — 이 대화에서 실제로 할 수 있는 말. */\n examples?: Array<{ label: string; items: string[] }>\n footerNotice?: string\n stagedNotice?: string\n /** What the screen may attach - the same policy the server enforces. */\n attachments?: AttachmentPolicy\n}\n\n/** What the screen shows, in the words of the request's locale. */\nexport function assistantModeView(kind: string, t: Translate): AssistantModeView {\n const mode = getAssistantMode(kind)\n if (!mode) throw unknownModeError(kind, t)\n\n return {\n kind: mode.kind,\n slashTemplates: (mode.slashTemplates ?? []).map((slash: AssistantModeSlash) => ({\n name: slash.name,\n description: t(slash.descriptionKey),\n template: t(slash.templateKey)\n })),\n catalogEntries: mode.catalogEntries ?? [],\n proposalChoices: mode.proposalChoices ?? [],\n placeholder: mode.placeholderKey ? t(mode.placeholderKey) : undefined,\n intro: mode.introKeys ? { title: t(mode.introKeys.title), subtitle: t(mode.introKeys.subtitle) } : undefined,\n examples: mode.exampleKeys?.map(group => ({\n label: t(group.labelKey),\n items: group.itemKeys.map(key => t(key))\n })),\n footerNotice: mode.footerNoticeKey ? t(mode.footerNoticeKey) : undefined,\n stagedNotice: mode.stagedNoticeKey ? t(mode.stagedNoticeKey) : undefined,\n attachments: mode.attachments\n }\n}\n"]}
|
|
@@ -10,6 +10,13 @@ export interface ProposalOutcome {
|
|
|
10
10
|
}
|
|
11
11
|
export declare const PROPOSAL_OUTCOME_PREFIX = "proposal ";
|
|
12
12
|
export declare const PROPOSAL_VERDICTS: ProposalVerdict[];
|
|
13
|
+
/**
|
|
14
|
+
* The cards an answer offered, one line each, put beside that answer in the history the model reads (figure audit
|
|
15
|
+
* 2026-10-16 N7). An outcome row names a proposal by its key, and the model never saw the key -- tool results are not
|
|
16
|
+
* in the history -- so with two cards in one answer it could not tell which one the person ran. The title is the one
|
|
17
|
+
* the person read on the card, given as data. Not stored: the row keeps its proposals, this is how the model reads them.
|
|
18
|
+
*/
|
|
19
|
+
export declare function offeredCardLines(proposalsJson: string | null | undefined): string[];
|
|
13
20
|
/**
|
|
14
21
|
* `proposal <key>: <verdict> (<errorCode>) 2/3`
|
|
15
22
|
*
|
|
@@ -13,11 +13,36 @@
|
|
|
13
13
|
*/
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.PROPOSAL_REQUESTED = exports.PROPOSAL_VERDICTS = exports.PROPOSAL_OUTCOME_PREFIX = void 0;
|
|
16
|
+
exports.offeredCardLines = offeredCardLines;
|
|
16
17
|
exports.formatProposalOutcomeLine = formatProposalOutcomeLine;
|
|
17
18
|
exports.formatProposalRequestedLine = formatProposalRequestedLine;
|
|
18
19
|
exports.proposalAlreadyTaken = proposalAlreadyTaken;
|
|
20
|
+
const ai_client_base_1 = require("@things-factory/ai-client-base");
|
|
19
21
|
exports.PROPOSAL_OUTCOME_PREFIX = 'proposal ';
|
|
20
22
|
exports.PROPOSAL_VERDICTS = ['accepted', 'refused', 'unavailable', 'declined'];
|
|
23
|
+
/**
|
|
24
|
+
* The cards an answer offered, one line each, put beside that answer in the history the model reads (figure audit
|
|
25
|
+
* 2026-10-16 N7). An outcome row names a proposal by its key, and the model never saw the key -- tool results are not
|
|
26
|
+
* in the history -- so with two cards in one answer it could not tell which one the person ran. The title is the one
|
|
27
|
+
* the person read on the card, given as data. Not stored: the row keeps its proposals, this is how the model reads them.
|
|
28
|
+
*/
|
|
29
|
+
function offeredCardLines(proposalsJson) {
|
|
30
|
+
let proposals;
|
|
31
|
+
try {
|
|
32
|
+
proposals = JSON.parse(proposalsJson ?? '');
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
if (!Array.isArray(proposals))
|
|
38
|
+
return [];
|
|
39
|
+
return proposals
|
|
40
|
+
.filter((one) => one && typeof one.key === 'string' && one.key)
|
|
41
|
+
.map((one) => {
|
|
42
|
+
const title = typeof one.label === 'string' && one.label.trim() ? one.label : (one.tool ?? 'proposal');
|
|
43
|
+
return `[card offered: ${(0, ai_client_base_1.quotedName)(String(title))} - its outcome, once the person runs it, is the line "${exports.PROPOSAL_OUTCOME_PREFIX}${one.key}: ..."]`;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
21
46
|
/**
|
|
22
47
|
* `proposal <key>: <verdict> (<errorCode>) 2/3`
|
|
23
48
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proposal-outcome.js","sourceRoot":"","sources":["../../../server/service/chat-message/proposal-outcome.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;
|
|
1
|
+
{"version":3,"file":"proposal-outcome.js","sourceRoot":"","sources":["../../../server/service/chat-message/proposal-outcome.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;AA0BH,4CAcC;AAOD,8DAOC;AAeD,kEAEC;AAMD,oDAUC;AArFD,mEAA2D;AAc9C,QAAA,uBAAuB,GAAG,WAAW,CAAA;AAErC,QAAA,iBAAiB,GAAsB,CAAC,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,CAAC,CAAA;AAEtG;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,aAAwC;IACvE,IAAI,SAAkB,CAAA;IACtB,IAAI,CAAC;QACH,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC,CAAA;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAA;IACX,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC;QAAE,OAAO,EAAE,CAAA;IACxC,OAAO,SAAS;SACb,MAAM,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,GAAG,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,CAAC;SACnE,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE;QAChB,MAAM,KAAK,GAAG,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,I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AC,CAAC,IAAI,EAAE,CAAA;QAChC,IAAI,IAAI,KAAK,SAAS;YAAE,OAAO,IAAI,CAAA;QACnC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAA;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;QACxC,OAAO,yBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC,CAAA;IAC9F,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["/*\n * What the host did with a proposal, written into the conversation (ADR-0070 A12-a).\n *\n * The card used to change to \"executed\" the moment it was pressed, which is the one thing it knew\n * and the one thing that is not the answer. The host's answer comes back through a server door and\n * is stored as a `system` row, so three readers get it from the same place: the card that is open,\n * the card after a refresh, and the model on its next turn — a model that is not told its proposal\n * was refused goes on as though it had been applied.\n *\n * The line is the row's content. It is parsed back by the panel, so the shape is fixed here and the\n * panel's parser is tested against this formatter.\n */\n\nimport { quotedName } from '@things-factory/ai-client-base'\n\n/** ADR-0042's verdicts, plus the one for a person who backed out at the confirm step. */\nexport type ProposalVerdict = 'accepted' | 'refused' | 'unavailable' | 'declined'\n\nexport interface ProposalOutcome {\n verdict: ProposalVerdict\n /** The host's own reason code, carried through untouched — no mapping table (ADR-0042). */\n errorCode?: string\n /** For a proposal made of several edits: how many went in, and how many did not. */\n applied?: number\n missed?: number\n}\n\nexport const PROPOSAL_OUTCOME_PREFIX = 'proposal '\n\nexport const PROPOSAL_VERDICTS: ProposalVerdict[] = ['accepted', 'refused', 'unavailable', 'declined']\n\n/**\n * The cards an answer offered, one line each, put beside that answer in the history the model reads (figure audit\n * 2026-10-16 N7). An outcome row names a proposal by its key, and the model never saw the key -- tool results are not\n * in the history -- so with two cards in one answer it could not tell which one the person ran. The title is the one\n * the person read on the card, given as data. Not stored: the row keeps its proposals, this is how the model reads them.\n */\nexport function offeredCardLines(proposalsJson: string | null | undefined): string[] {\n let proposals: unknown\n try {\n proposals = JSON.parse(proposalsJson ?? '')\n } catch {\n return []\n }\n if (!Array.isArray(proposals)) return []\n return proposals\n .filter((one: any) => one && typeof one.key === 'string' && one.key)\n .map((one: any) => {\n const title = typeof one.label === 'string' && one.label.trim() ? one.label : (one.tool ?? 'proposal')\n return `[card offered: ${quotedName(String(title))} - its outcome, once the person runs it, is the line \"${PROPOSAL_OUTCOME_PREFIX}${one.key}: ...\"]`\n })\n}\n\n/**\n * `proposal <key>: <verdict> (<errorCode>) 2/3`\n *\n * English, like the other lines the model reads. The panel turns it into the reader's language.\n */\nexport function formatProposalOutcomeLine(key: string, outcome: ProposalOutcome): string {\n const reason = outcome.errorCode ? ` (${outcome.errorCode})` : ''\n const counted =\n typeof outcome.applied === 'number' || typeof outcome.missed === 'number'\n ? ` ${outcome.applied ?? 0}/${(outcome.applied ?? 0) + (outcome.missed ?? 0)}`\n : ''\n return `${PROPOSAL_OUTCOME_PREFIX}${key}: ${outcome.verdict}${reason}${counted}`\n}\n\n/*\n * \"Requested\" — written before the host is asked to run a proposal (ADR-0097 Q-D4 ④).\n *\n * The card used to remember that it was pressed in the page's memory only. After a refresh a\n * proposal whose outcome never came back had its button again, and pressing it asked the host to\n * apply it a second time. The request is now a row, like the outcome, so every reader sees it: the\n * card after a refresh, another window, and the model (\"requested, no answer yet\").\n *\n * It is not a verdict — nothing happened yet. It only says the host was asked.\n */\nexport const PROPOSAL_REQUESTED = 'requested'\n\n/** `proposal <key>: requested` */\nexport function formatProposalRequestedLine(key: string): string {\n return `${PROPOSAL_OUTCOME_PREFIX}${key}: ${PROPOSAL_REQUESTED}`\n}\n\n/**\n * Whether this proposal was already taken in this conversation — requested, or answered.\n * The caller passes the conversation's system lines; the answer is the rule, kept testable.\n */\nexport function proposalAlreadyTaken(key: string, systemLines: readonly (string | null | undefined)[]): boolean {\n const requested = formatProposalRequestedLine(key)\n const answered = `${PROPOSAL_OUTCOME_PREFIX}${key}: `\n return systemLines.some(line => {\n const text = (line ?? '').trim()\n if (text === requested) return true\n if (!text.startsWith(answered)) return false\n const rest = text.slice(answered.length)\n return PROPOSAL_VERDICTS.some(verdict => rest === verdict || rest.startsWith(`${verdict} `))\n })\n}\n"]}
|
|
@@ -6,6 +6,8 @@ const amountOf = (list) => list.columns.find(one => one.name === 'amount' && one
|
|
|
6
6
|
function listReadTarget(list) {
|
|
7
7
|
const search = !!list.search;
|
|
8
8
|
const amount = amountOf(list);
|
|
9
|
+
/* A bound compares the stored number - in each row's own currency when the column has one. */
|
|
10
|
+
const inCurrency = list.columns.find(one => one.name === amount)?.currency ? `, compared in each row's own ${list.columns.find(one => one.name === amount).currency} - a row in another currency is held to the same number` : '';
|
|
9
11
|
const narrowing = list.narrowing ?? {};
|
|
10
12
|
const criteria = [
|
|
11
13
|
...(list.dateField
|
|
@@ -27,8 +29,8 @@ function listReadTarget(list) {
|
|
|
27
29
|
: []),
|
|
28
30
|
...(amount
|
|
29
31
|
? [
|
|
30
|
-
{ name: 'minAmount', type: 'number', labelKey: 'ai-assistant.read.min-amount', description: `at least this ${amount}`, filter: (v) => ({ name: amount, operator: 'gte', value: v }) },
|
|
31
|
-
{ name: 'maxAmount', type: 'number', labelKey: 'ai-assistant.read.max-amount', description: `at most this ${amount}`, filter: (v) => ({ name: amount, operator: 'lte', value: v }) }
|
|
32
|
+
{ name: 'minAmount', type: 'number', labelKey: 'ai-assistant.read.min-amount', description: `at least this ${amount}${inCurrency}`, filter: (v) => ({ name: amount, operator: 'gte', value: v }) },
|
|
33
|
+
{ name: 'maxAmount', type: 'number', labelKey: 'ai-assistant.read.max-amount', description: `at most this ${amount}${inCurrency}`, filter: (v) => ({ name: amount, operator: 'lte', value: v }) }
|
|
32
34
|
]
|
|
33
35
|
: [])
|
|
34
36
|
];
|