@things-factory/ai-assistant 10.1.29 → 10.1.32
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-mode/index.d.ts +1 -1
- package/dist-server/service/assistant-mode/index.js +1 -1
- package/dist-server/service/assistant-mode/index.js.map +1 -1
- package/dist-server/service/testing/conversation-script.d.ts +7 -0
- package/dist-server/service/testing/conversation-script.js +1 -0
- package/dist-server/service/testing/conversation-script.js.map +1 -1
- package/dist-server/service/testing/mode-conformance.js +8 -1
- package/dist-server/service/testing/mode-conformance.js.map +1 -1
- package/dist-server/service/tool-access.js +20 -7
- package/dist-server/service/tool-access.js.map +1 -1
- package/dist-server/tool-registry-boot-report.js +8 -9
- package/dist-server/tool-registry-boot-report.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
- package/server/service/assistant-mode/index.ts +1 -1
- package/server/service/testing/conversation-scenario.test.ts +2 -1
- package/server/service/testing/conversation-script.test.ts +4 -2
- package/server/service/testing/conversation-script.ts +8 -0
- package/server/service/testing/mode-conformance.test.ts +48 -0
- package/server/service/testing/mode-conformance.ts +8 -1
- package/server/service/tool-access.test.ts +67 -19
- package/server/service/tool-access.ts +24 -15
- package/server/tool-registry-boot-report.ts +8 -9
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Modes — what each conversation is, declared by the app server that owns the screen.
|
|
3
3
|
*
|
|
4
|
-
* Design: ADR-0061 decision 7 (`operato-
|
|
4
|
+
* Design: ADR-0061 decision 7 (`operato-application/adr/ADR-0061.md`) and the AI standard's A2.
|
|
5
5
|
*/
|
|
6
6
|
export { registerAssistantMode, getAssistantMode, listAssistantModes, assistantModesForSubject, getAssistantModeWarnings, clearAssistantModes } from './registry.js';
|
|
7
7
|
export { resolveModeSettings, assistantModeView } from './resolve.js';
|
|
@@ -4,7 +4,7 @@ exports.assistantModeView = exports.resolveModeSettings = exports.clearAssistant
|
|
|
4
4
|
/**
|
|
5
5
|
* Modes — what each conversation is, declared by the app server that owns the screen.
|
|
6
6
|
*
|
|
7
|
-
* Design: ADR-0061 decision 7 (`operato-
|
|
7
|
+
* Design: ADR-0061 decision 7 (`operato-application/adr/ADR-0061.md`) and the AI standard's A2.
|
|
8
8
|
*/
|
|
9
9
|
var registry_js_1 = require("./registry.js");
|
|
10
10
|
Object.defineProperty(exports, "registerAssistantMode", { enumerable: true, get: function () { return registry_js_1.registerAssistantMode; } });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/index.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,6CAOsB;AANpB,oHAAA,qBAAqB,OAAA;AACrB,+GAAA,gBAAgB,OAAA;AAChB,iHAAA,kBAAkB,OAAA;AAClB,uHAAA,wBAAwB,OAAA;AACxB,uHAAA,wBAAwB,OAAA;AACxB,kHAAA,mBAAmB,OAAA;AAErB,2CAAqE;AAA5D,iHAAA,mBAAmB,OAAA;AAAE,+GAAA,iBAAiB,OAAA","sourcesContent":["/**\n * Modes — what each conversation is, declared by the app server that owns the screen.\n *\n * Design: ADR-0061 decision 7 (`operato-
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/service/assistant-mode/index.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,6CAOsB;AANpB,oHAAA,qBAAqB,OAAA;AACrB,+GAAA,gBAAgB,OAAA;AAChB,iHAAA,kBAAkB,OAAA;AAClB,uHAAA,wBAAwB,OAAA;AACxB,uHAAA,wBAAwB,OAAA;AACxB,kHAAA,mBAAmB,OAAA;AAErB,2CAAqE;AAA5D,iHAAA,mBAAmB,OAAA;AAAE,+GAAA,iBAAiB,OAAA","sourcesContent":["/**\n * Modes — what each conversation is, declared by the app server that owns the screen.\n *\n * Design: ADR-0061 decision 7 (`operato-application/adr/ADR-0061.md`) and the AI standard's A2.\n */\nexport {\n registerAssistantMode,\n getAssistantMode,\n listAssistantModes,\n assistantModesForSubject,\n getAssistantModeWarnings,\n clearAssistantModes\n} from './registry.js'\nexport { resolveModeSettings, assistantModeView } from './resolve.js'\nexport type { AssistantModeSpec, AssistantModeSlash, AssistantModeWarning } from './types.js'\nexport type { AssistantModeRef, ModeSettings, AssistantModeView, AssistantModeSlashView, Translate } from './resolve.js'\n"]}
|
|
@@ -82,6 +82,13 @@ export interface ConversationOptions {
|
|
|
82
82
|
systemPrompt?: string;
|
|
83
83
|
/** Which registered categories this conversation may use. Omitted allows none. */
|
|
84
84
|
toolCategories?: string[];
|
|
85
|
+
/**
|
|
86
|
+
* Which doors this script's speaker may pass (ADR-0071 decision 2). A tool is offered when the
|
|
87
|
+
* caller passes every door it names, so a script that says nothing here is written as someone who
|
|
88
|
+
* passes them all — the permission axis belongs to `tool-access`, not to a conversation script.
|
|
89
|
+
* Name the doors to write the other case: a person the tool is not offered to.
|
|
90
|
+
*/
|
|
91
|
+
toolAccess?: (door: string) => Promise<boolean>;
|
|
85
92
|
/** Request state the tools receive (domain, user). */
|
|
86
93
|
state?: any;
|
|
87
94
|
/** What the surface is looking at — reaches tools as `ctx.host`, never the model. */
|
|
@@ -178,6 +178,7 @@ function conversation(options = {}) {
|
|
|
178
178
|
messages: (0, llm_history_js_1.buildLlmHistory)(rows, {}),
|
|
179
179
|
systemPrompt: options.systemPrompt ?? 'you are a test assistant',
|
|
180
180
|
toolCategories: options.toolCategories,
|
|
181
|
+
toolAccess: options.toolAccess ?? (async () => true),
|
|
181
182
|
hostContext: options.hostContext,
|
|
182
183
|
state: options.state ?? { domain: { id: 'dom-1' }, user: { id: 'u-1' } },
|
|
183
184
|
requireToolOnFirstTurn: options.requireToolOnFirstTurn
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-script.js","sourceRoot":"","sources":["../../../server/service/testing/conversation-script.ts"],"names":[],"mappings":";;AAqFA,wCA+BC;AAoCD,oCAuIC;AA/RD;;;;;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,KAAK,EAAE,EAAE;oBACxE,sBAAsB,EAAE,OAAO,CAAC,sBAAsB;iBACvD,CAAC,CAAA;gBAEF,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;gBAC1B,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAA;gBACrF,KAAK,MAAM,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,IAAI,EAAE;oBAAE,SAAS,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAA;YACzG,CAAC;YAED,OAAO;gBACL,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,OAAO;gBACP,SAAS;gBACT,IAAI;gBACJ,YAAY,EAAE,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;gBACzF,OAAO;aACR,CAAA;QACH,CAAC;KACF,CAAA;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["/*\n * A conversation with several people in it, written as a script, so a test can say what the\n * assistant should have heard and what it should have done.\n *\n * ── Why a harness (standard A15) ───────────────────────────────────────────────\n * A shared session carries two kinds of talk: people talking to each other, and people talking to\n * the assistant. Everything a person types is stored the same way, and the model reads all of it.\n * So the questions a test must be able to ask are:\n *\n * 누가 말했나 · 누구에게 한 말인가 · 그 턴에 모델을 불렀나 · 모델이 무엇을 읽었나 ·\n * 무엇을 쓸 수 있었나 · 답과 제안은 누구 것인가\n *\n * Those are hard to see from a resolver test, because the interesting part is what the model was\n * handed — and that is a string built from stored rows. The script keeps the rows, builds the same\n * history the door builds, and records every model call.\n *\n * ── What this does not do ──────────────────────────────────────────────────────\n * No database, no GraphQL, no provider. It drives the same two pieces the door drives\n * (`buildLlmHistory` and `registryAssistantChat`) with a recording client, so a failure names a\n * rule rather than a stack. Anything that only the resolver does — storing, broadcasting, session\n * activity — is out of scope here and belongs in a resolver test.\n */\nimport { registryAssistantChat } from '@things-factory/ai-client-base'\n\nimport { buildLlmHistory, type HistoryRow } from '../chat-message/llm-history.js'\nimport { formatProposalOutcomeLine, type ProposalOutcome } from '../chat-message/proposal-outcome.js'\nimport { roomMessageBody } from '../chat-message/room-message.js'\nimport { inviteMentionedUsers } from '../chat-session-participant/mention-invite.js'\n\n/** Who a turn was meant for. The room hears everything; only the assistant answers. */\nexport type Addressee = 'room' | 'assistant'\n\nexport interface ScriptedTurn {\n speaker: string\n addressee: Addressee\n content: string\n /** `mention` 이 부른 사람 — 본문에는 마커로 실린다. */\n mentions?: string[]\n /** 호스트가 카드에 답한 것 — 사람의 말이 아니라 기록이다. */\n outcome?: { proposalKey: string; outcome: ProposalOutcome }\n}\n\n/** One model call, exactly as the provider saw it. */\nexport interface RecordedCall {\n systemPrompt: string\n /** The conversation handed over, newest last. */\n messages: { role: string; content: any }[]\n /** Tool names offered this turn. */\n tools: string[]\n}\n\nexport interface ScriptResult {\n /** Every model call, in order. A room turn must not produce one. */\n calls: RecordedCall[]\n /** What the assistant answered, one per `ask`. */\n replies: string[]\n /** Proposals returned, paired with the turn that asked for them. */\n proposals: { askedBy: string; proposal: any }[]\n /** The rows as they stand, in the order they were said. */\n rows: HistoryRow[]\n /** Who is in the room now, and what each of them may do. */\n participants: ScriptParticipant[]\n /** What each `mention` did — who joined, or why nobody did. */\n invites: { by: string; invited: string[]; notSeated?: string[] }[]\n}\n\n/** A person in the room. `read` is how far they have read — the fact others see as a badge. */\nexport interface ScriptParticipant {\n userId: string\n role: 'owner' | 'member' | 'viewer'\n read?: number\n}\n\n/** A provider that answers with a fixed script and records what it was given. */\nexport interface RecordingModel {\n client: any\n calls: RecordedCall[]\n}\n\n/**\n * A model that answers each call with the next canned reply, and records what it saw.\n *\n * `toolCalls` lets a script make the model ask for a tool on a given turn — the harness then\n * exercises the dispatch path rather than only the prompt.\n */\nexport function recordingModel(\n replies: string[] = ['ok'],\n toolCalls: { name: string; arguments?: any }[][] = []\n): RecordingModel {\n const calls: RecordedCall[] = []\n let turn = 0\n let replyTurn = 0\n\n const client = {\n id: 'recording:test',\n async chatWithTools(messages: any[], tools: any[], options: any) {\n const index = turn++\n calls.push({\n systemPrompt: options?.systemPrompt ?? '',\n messages: messages.map(m => ({ role: m.role, content: m.content })),\n tools: (tools ?? []).map(t => t.name)\n })\n /* The loop asks again after a tool answers, so only the first call of a turn asks for tools. */\n const wanted = toolCalls[index] ?? []\n if (wanted.length > 0) {\n return {\n text: '',\n toolCalls: wanted.map((c, i) => ({ id: `call-${index}-${i}`, name: c.name, arguments: c.arguments ?? {} })),\n stopReason: 'tool_use'\n }\n }\n return { text: replies[Math.min(replyTurn++, replies.length - 1)] ?? 'ok', toolCalls: [], stopReason: 'end_turn' }\n }\n }\n\n return { client, calls }\n}\n\nexport interface ConversationOptions {\n /**\n * Who is in the room when the script starts, and as what.\n *\n * A conversation always has an owner — the person who started it — and `createAISession` puts\n * them there. Since ADR-0073 a mention grants nothing, so the roster no longer decides who may\n * name whom; it still decides who the room reaches and who is already seated.\n */\n participants?: ScriptParticipant[]\n /** 이 대화가 공개인가 — 기본은 공개(ADR-0073 판정 2). 'private' 이면 멘션이 사람을 앉히지 않는다. */\n visibility?: 'open' | 'private'\n /** Who the assistant is on this surface — in real use it comes from the registered mode. */\n systemPrompt?: string\n /** Which registered categories this conversation may use. Omitted allows none. */\n toolCategories?: string[]\n /** Request state the tools receive (domain, user). */\n state?: any\n /** What the surface is looking at — reaches tools as `ctx.host`, never the model. */\n hostContext?: any\n /** Passed through to the runner; a live-state surface makes the model read first. */\n requireToolOnFirstTurn?: boolean\n}\n\n/**\n * Write the conversation, then run it.\n *\n * ```ts\n * const result = await conversation({ toolCategories: ['twin-ops'] })\n * .say('alice', '3 라인이 멈춘 것 같아요')\n * .say('bob', '아까부터 그랬어')\n * .ask('alice', '왜 멈췄는지 확인해줘')\n * .run(recordingModel(['확인했습니다']))\n * ```\n */\nexport function conversation(options: ConversationOptions = {}) {\n const turns: ScriptedTurn[] = []\n\n const api = {\n /** Someone speaks to the room. Nobody calls the assistant; it reads this next time it is asked. */\n say(speaker: string, content: string) {\n turns.push({ speaker, addressee: 'room', content })\n return api\n },\n /** Someone asks the assistant. This is the turn that makes a model call. */\n ask(speaker: string, content: string) {\n turns.push({ speaker, addressee: 'assistant', content })\n return api\n },\n /**\n * Someone asks the assistant **and names a colleague** — the way a second person joins.\n *\n * The marker is what the browser puts in the text when a name is picked from `@`, and the door\n * reads it from the stored turn. Only a person already in the room may bring another in.\n */\n mention(speaker: string, userIds: string[], content: string) {\n const marked = [...userIds.map(id => `@${id}{userId:${id}}`), content].join(' ')\n turns.push({ speaker, addressee: 'assistant', content: marked, mentions: userIds })\n return api\n },\n\n /** The assistant's own answer, when a script needs one already in the history. */\n answered(content: string) {\n turns.push({ speaker: 'assistant', addressee: 'room', content })\n return api\n },\n\n /**\n * The host says what it did with a proposal — the card's state and the model's next turn both\n * read this row (ADR-0070 A12-a).\n */\n outcome(proposalKey: string, outcome: ProposalOutcome) {\n turns.push({ speaker: 'system', addressee: 'room', content: '', outcome: { proposalKey, outcome } })\n return api\n },\n\n async run(model: RecordingModel = recordingModel()): Promise<ScriptResult> {\n const rows: HistoryRow[] = []\n const replies: string[] = []\n const proposals: { askedBy: string; proposal: any }[] = []\n const invites: { by: string; invited: string[]; notSeated?: string[] }[] = []\n\n /* 참여자 저장소 — 실제 문이 쓰는 것과 같은 규칙을 지나되, 기억에만 둔다. */\n const roster: any[] = (options.participants ?? [{ userId: 'alice', role: 'owner' }]).map((person, index) => ({\n id: `participant-${index + 1}`,\n userId: person.userId,\n role: person.role,\n read: person.read\n }))\n const participants = {\n find: async () => roster,\n save: async (row: any) => {\n roster.push({ id: `participant-${roster.length + 1}`, userId: row.user.id, role: row.role })\n },\n update: async (id: string, patch: any) => {\n const found = roster.find(row => row.id === id)\n if (found) Object.assign(found, patch)\n }\n }\n\n for (const turn of turns) {\n /* 호스트의 답은 사람의 말이 아니다 — 서버가 쓰는 `system` 행이다. */\n if (turn.outcome) {\n rows.push({\n id: `row-${rows.length + 1}`,\n role: 'system',\n content: formatProposalOutcomeLine(turn.outcome.proposalKey, turn.outcome.outcome)\n })\n continue\n }\n\n /* 빈 말은 저장되지 않는다 — 문이 지키는 규칙과 같은 것을 쓴다. */\n const body = roomMessageBody(turn.content)\n if (!body) continue\n\n rows.push({\n id: `row-${rows.length + 1}`,\n role: turn.speaker === 'assistant' ? 'assistant' : 'user',\n content: body,\n senderId: turn.speaker,\n senderName: turn.speaker,\n /* 사람의 말에만 대상이 있다 — 문이 찍는 값과 같은 자리다(ADR-0070 A15 결정 ①). */\n addressee: turn.speaker === 'assistant' ? undefined : turn.addressee\n })\n\n /* 멘션은 사람의 말을 저장하는 문에서만 사람을 불러들인다(ADR-0071 결정 1 ①). */\n if (turn.speaker !== 'assistant') {\n const invite = await inviteMentionedUsers({\n content: body,\n sessionId: 'script-session',\n domainId: 'script-domain',\n inviter: { id: turn.speaker },\n participants,\n visibility: options.visibility\n })\n if (invite.invited.length > 0 || invite.notSeated) {\n invites.push({ by: turn.speaker, invited: invite.invited, notSeated: invite.notSeated })\n }\n }\n\n /* Only a turn addressed to the assistant runs it. Room talk is context for the next one. */\n if (turn.addressee !== 'assistant') continue\n\n const result = await registryAssistantChat({\n client: model.client,\n messages: buildLlmHistory(rows, {}) as any,\n systemPrompt: options.systemPrompt ?? 'you are a test assistant',\n toolCategories: options.toolCategories,\n hostContext: options.hostContext,\n state: options.state ?? { domain: { id: 'dom-1' }, user: { id: 'u-1' } },\n requireToolOnFirstTurn: options.requireToolOnFirstTurn\n })\n\n replies.push(result.reply)\n rows.push({ id: `row-${rows.length + 1}`, role: 'assistant', content: result.reply })\n for (const proposal of result.loop.proposals ?? []) proposals.push({ askedBy: turn.speaker, proposal })\n }\n\n return {\n calls: model.calls,\n replies,\n proposals,\n rows,\n participants: roster.map(row => ({ userId: row.userId, role: row.role, read: row.read })),\n invites\n }\n }\n }\n\n return api\n}\n"]}
|
|
1
|
+
{"version":3,"file":"conversation-script.js","sourceRoot":"","sources":["../../../server/service/testing/conversation-script.ts"],"names":[],"mappings":";;AAqFA,wCA+BC;AA2CD,oCAwIC;AAvSD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,mEAAsE;AAEtE,mEAAiF;AACjF,6EAAqG;AACrG,qEAAiE;AACjE,qFAAoF;AAoDpF;;;;;GAKG;AACH,SAAgB,cAAc,CAC5B,UAAoB,CAAC,IAAI,CAAC,EAC1B,YAAmD,EAAE;IAErD,MAAM,KAAK,GAAmB,EAAE,CAAA;IAChC,IAAI,IAAI,GAAG,CAAC,CAAA;IACZ,IAAI,SAAS,GAAG,CAAC,CAAA;IAEjB,MAAM,MAAM,GAAG;QACb,EAAE,EAAE,gBAAgB;QACpB,KAAK,CAAC,aAAa,CAAC,QAAe,EAAE,KAAY,EAAE,OAAY;YAC7D,MAAM,KAAK,GAAG,IAAI,EAAE,CAAA;YACpB,KAAK,CAAC,IAAI,CAAC;gBACT,YAAY,EAAE,OAAO,EAAE,YAAY,IAAI,EAAE;gBACzC,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;gBACnE,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aACtC,CAAC,CAAA;YACF,gGAAgG;YAChG,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAA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A;QACH,CAAC;KACF,CAAA;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["/*\n * A conversation with several people in it, written as a script, so a test can say what the\n * assistant should have heard and what it should have done.\n *\n * ── Why a harness (standard A15) ───────────────────────────────────────────────\n * A shared session carries two kinds of talk: people talking to each other, and people talking to\n * the assistant. Everything a person types is stored the same way, and the model reads all of it.\n * So the questions a test must be able to ask are:\n *\n * 누가 말했나 · 누구에게 한 말인가 · 그 턴에 모델을 불렀나 · 모델이 무엇을 읽었나 ·\n * 무엇을 쓸 수 있었나 · 답과 제안은 누구 것인가\n *\n * Those are hard to see from a resolver test, because the interesting part is what the model was\n * handed — and that is a string built from stored rows. The script keeps the rows, builds the same\n * history the door builds, and records every model call.\n *\n * ── What this does not do ──────────────────────────────────────────────────────\n * No database, no GraphQL, no provider. It drives the same two pieces the door drives\n * (`buildLlmHistory` and `registryAssistantChat`) with a recording client, so a failure names a\n * rule rather than a stack. Anything that only the resolver does — storing, broadcasting, session\n * activity — is out of scope here and belongs in a resolver test.\n */\nimport { registryAssistantChat } from '@things-factory/ai-client-base'\n\nimport { buildLlmHistory, type HistoryRow } from '../chat-message/llm-history.js'\nimport { formatProposalOutcomeLine, type ProposalOutcome } from '../chat-message/proposal-outcome.js'\nimport { roomMessageBody } from '../chat-message/room-message.js'\nimport { inviteMentionedUsers } from '../chat-session-participant/mention-invite.js'\n\n/** Who a turn was meant for. The room hears everything; only the assistant answers. */\nexport type Addressee = 'room' | 'assistant'\n\nexport interface ScriptedTurn {\n speaker: string\n addressee: Addressee\n content: string\n /** `mention` 이 부른 사람 — 본문에는 마커로 실린다. */\n mentions?: string[]\n /** 호스트가 카드에 답한 것 — 사람의 말이 아니라 기록이다. */\n outcome?: { proposalKey: string; outcome: ProposalOutcome }\n}\n\n/** One model call, exactly as the provider saw it. */\nexport interface RecordedCall {\n systemPrompt: string\n /** The conversation handed over, newest last. */\n messages: { role: string; content: any }[]\n /** Tool names offered this turn. */\n tools: string[]\n}\n\nexport interface ScriptResult {\n /** Every model call, in order. A room turn must not produce one. */\n calls: RecordedCall[]\n /** What the assistant answered, one per `ask`. */\n replies: string[]\n /** Proposals returned, paired with the turn that asked for them. */\n proposals: { askedBy: string; proposal: any }[]\n /** The rows as they stand, in the order they were said. */\n rows: HistoryRow[]\n /** Who is in the room now, and what each of them may do. */\n participants: ScriptParticipant[]\n /** What each `mention` did — who joined, or why nobody did. */\n invites: { by: string; invited: string[]; notSeated?: string[] }[]\n}\n\n/** A person in the room. `read` is how far they have read — the fact others see as a badge. */\nexport interface ScriptParticipant {\n userId: string\n role: 'owner' | 'member' | 'viewer'\n read?: number\n}\n\n/** A provider that answers with a fixed script and records what it was given. */\nexport interface RecordingModel {\n client: any\n calls: RecordedCall[]\n}\n\n/**\n * A model that answers each call with the next canned reply, and records what it saw.\n *\n * `toolCalls` lets a script make the model ask for a tool on a given turn — the harness then\n * exercises the dispatch path rather than only the prompt.\n */\nexport function recordingModel(\n replies: string[] = ['ok'],\n toolCalls: { name: string; arguments?: any }[][] = []\n): RecordingModel {\n const calls: RecordedCall[] = []\n let turn = 0\n let replyTurn = 0\n\n const client = {\n id: 'recording:test',\n async chatWithTools(messages: any[], tools: any[], options: any) {\n const index = turn++\n calls.push({\n systemPrompt: options?.systemPrompt ?? '',\n messages: messages.map(m => ({ role: m.role, content: m.content })),\n tools: (tools ?? []).map(t => t.name)\n })\n /* The loop asks again after a tool answers, so only the first call of a turn asks for tools. */\n const wanted = toolCalls[index] ?? []\n if (wanted.length > 0) {\n return {\n text: '',\n toolCalls: wanted.map((c, i) => ({ id: `call-${index}-${i}`, name: c.name, arguments: c.arguments ?? {} })),\n stopReason: 'tool_use'\n }\n }\n return { text: replies[Math.min(replyTurn++, replies.length - 1)] ?? 'ok', toolCalls: [], stopReason: 'end_turn' }\n }\n }\n\n return { client, calls }\n}\n\nexport interface ConversationOptions {\n /**\n * Who is in the room when the script starts, and as what.\n *\n * A conversation always has an owner — the person who started it — and `createAISession` puts\n * them there. Since ADR-0073 a mention grants nothing, so the roster no longer decides who may\n * name whom; it still decides who the room reaches and who is already seated.\n */\n participants?: ScriptParticipant[]\n /** 이 대화가 공개인가 — 기본은 공개(ADR-0073 판정 2). 'private' 이면 멘션이 사람을 앉히지 않는다. */\n visibility?: 'open' | 'private'\n /** Who the assistant is on this surface — in real use it comes from the registered mode. */\n systemPrompt?: string\n /** Which registered categories this conversation may use. Omitted allows none. */\n toolCategories?: string[]\n /**\n * Which doors this script's speaker may pass (ADR-0071 decision 2). A tool is offered when the\n * caller passes every door it names, so a script that says nothing here is written as someone who\n * passes them all — the permission axis belongs to `tool-access`, not to a conversation script.\n * Name the doors to write the other case: a person the tool is not offered to.\n */\n toolAccess?: (door: string) => Promise<boolean>\n /** Request state the tools receive (domain, user). */\n state?: any\n /** What the surface is looking at — reaches tools as `ctx.host`, never the model. */\n hostContext?: any\n /** Passed through to the runner; a live-state surface makes the model read first. */\n requireToolOnFirstTurn?: boolean\n}\n\n/**\n * Write the conversation, then run it.\n *\n * ```ts\n * const result = await conversation({ toolCategories: ['twin-ops'] })\n * .say('alice', '3 라인이 멈춘 것 같아요')\n * .say('bob', '아까부터 그랬어')\n * .ask('alice', '왜 멈췄는지 확인해줘')\n * .run(recordingModel(['확인했습니다']))\n * ```\n */\nexport function conversation(options: ConversationOptions = {}) {\n const turns: ScriptedTurn[] = []\n\n const api = {\n /** Someone speaks to the room. Nobody calls the assistant; it reads this next time it is asked. */\n say(speaker: string, content: string) {\n turns.push({ speaker, addressee: 'room', content })\n return api\n },\n /** Someone asks the assistant. This is the turn that makes a model call. */\n ask(speaker: string, content: string) {\n turns.push({ speaker, addressee: 'assistant', content })\n return api\n },\n /**\n * Someone asks the assistant **and names a colleague** — the way a second person joins.\n *\n * The marker is what the browser puts in the text when a name is picked from `@`, and the door\n * reads it from the stored turn. Only a person already in the room may bring another in.\n */\n mention(speaker: string, userIds: string[], content: string) {\n const marked = [...userIds.map(id => `@${id}{userId:${id}}`), content].join(' ')\n turns.push({ speaker, addressee: 'assistant', content: marked, mentions: userIds })\n return api\n },\n\n /** The assistant's own answer, when a script needs one already in the history. */\n answered(content: string) {\n turns.push({ speaker: 'assistant', addressee: 'room', content })\n return api\n },\n\n /**\n * The host says what it did with a proposal — the card's state and the model's next turn both\n * read this row (ADR-0070 A12-a).\n */\n outcome(proposalKey: string, outcome: ProposalOutcome) {\n turns.push({ speaker: 'system', addressee: 'room', content: '', outcome: { proposalKey, outcome } })\n return api\n },\n\n async run(model: RecordingModel = recordingModel()): Promise<ScriptResult> {\n const rows: HistoryRow[] = []\n const replies: string[] = []\n const proposals: { askedBy: string; proposal: any }[] = []\n const invites: { by: string; invited: string[]; notSeated?: string[] }[] = []\n\n /* 참여자 저장소 — 실제 문이 쓰는 것과 같은 규칙을 지나되, 기억에만 둔다. */\n const roster: any[] = (options.participants ?? [{ userId: 'alice', role: 'owner' }]).map((person, index) => ({\n id: `participant-${index + 1}`,\n userId: person.userId,\n role: person.role,\n read: person.read\n }))\n const participants = {\n find: async () => roster,\n save: async (row: any) => {\n roster.push({ id: `participant-${roster.length + 1}`, userId: row.user.id, role: row.role })\n },\n update: async (id: string, patch: any) => {\n const found = roster.find(row => row.id === id)\n if (found) Object.assign(found, patch)\n }\n }\n\n for (const turn of turns) {\n /* 호스트의 답은 사람의 말이 아니다 — 서버가 쓰는 `system` 행이다. */\n if (turn.outcome) {\n rows.push({\n id: `row-${rows.length + 1}`,\n role: 'system',\n content: formatProposalOutcomeLine(turn.outcome.proposalKey, turn.outcome.outcome)\n })\n continue\n }\n\n /* 빈 말은 저장되지 않는다 — 문이 지키는 규칙과 같은 것을 쓴다. */\n const body = roomMessageBody(turn.content)\n if (!body) continue\n\n rows.push({\n id: `row-${rows.length + 1}`,\n role: turn.speaker === 'assistant' ? 'assistant' : 'user',\n content: body,\n senderId: turn.speaker,\n senderName: turn.speaker,\n /* 사람의 말에만 대상이 있다 — 문이 찍는 값과 같은 자리다(ADR-0070 A15 결정 ①). */\n addressee: turn.speaker === 'assistant' ? undefined : turn.addressee\n })\n\n /* 멘션은 사람의 말을 저장하는 문에서만 사람을 불러들인다(ADR-0071 결정 1 ①). */\n if (turn.speaker !== 'assistant') {\n const invite = await inviteMentionedUsers({\n content: body,\n sessionId: 'script-session',\n domainId: 'script-domain',\n inviter: { id: turn.speaker },\n participants,\n visibility: options.visibility\n })\n if (invite.invited.length > 0 || invite.notSeated) {\n invites.push({ by: turn.speaker, invited: invite.invited, notSeated: invite.notSeated })\n }\n }\n\n /* Only a turn addressed to the assistant runs it. Room talk is context for the next one. */\n if (turn.addressee !== 'assistant') continue\n\n const result = await registryAssistantChat({\n client: model.client,\n messages: buildLlmHistory(rows, {}) as any,\n systemPrompt: options.systemPrompt ?? 'you are a test assistant',\n toolCategories: options.toolCategories,\n toolAccess: options.toolAccess ?? (async () => true),\n hostContext: options.hostContext,\n state: options.state ?? { domain: { id: 'dom-1' }, user: { id: 'u-1' } },\n requireToolOnFirstTurn: options.requireToolOnFirstTurn\n })\n\n replies.push(result.reply)\n rows.push({ id: `row-${rows.length + 1}`, role: 'assistant', content: result.reply })\n for (const proposal of result.loop.proposals ?? []) proposals.push({ askedBy: turn.speaker, proposal })\n }\n\n return {\n calls: model.calls,\n replies,\n proposals,\n rows,\n participants: roster.map(row => ({ userId: row.userId, role: row.role, read: row.read })),\n invites\n }\n }\n }\n\n return api\n}\n"]}
|
|
@@ -43,7 +43,14 @@ async function runRegisteredMode(kind, options = {}) {
|
|
|
43
43
|
temperature: settings.temperature,
|
|
44
44
|
maxTokens: settings.maxTokens,
|
|
45
45
|
hostContext: options.hostContext,
|
|
46
|
-
|
|
46
|
+
/*
|
|
47
|
+
* 이 하네스가 묻는 것은 **모드**다 — 「이 모드가 무엇을 여는가」이지 「이 사람이 문을 지나는가」가
|
|
48
|
+
* 아니다. 관문이 `doors` 로 옮겨간 뒤(ADR-0071 결정 2) 검사를 안 넘기면 문을 적은 도구가 전부
|
|
49
|
+
* 닫히고, 그러면 앱의 적합성 시험에서 **실제 자료를 읽는 도구만** 조용히 사라진다. 그래서 기본은
|
|
50
|
+
* 모든 문을 지나는 사람이고, 다른 쪽을 보고 싶은 앱은 `toolAccess` 를 적어 그 경우를 쓴다.
|
|
51
|
+
* 권한 축은 자기 시험이 따로 본다(`tool-access.test.ts` · `tool-scope.test.ts`).
|
|
52
|
+
*/
|
|
53
|
+
toolAccess: options.toolAccess ?? (async () => true),
|
|
47
54
|
state: options.state ?? { domain: { id: 'dom-1' }, user: { id: 'u-1' } }
|
|
48
55
|
});
|
|
49
56
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mode-conformance.js","sourceRoot":"","sources":["../../../server/service/testing/mode-conformance.ts"],"names":[],"mappings":";;;AAqCA,
|
|
1
|
+
{"version":3,"file":"mode-conformance.js","sourceRoot":"","sources":["../../../server/service/testing/mode-conformance.ts"],"names":[],"mappings":";;;AAqCA,8CAkCC;AAcD,kCAUC;AAGD,wCAuBC;AAGD,4DAIC;AAhID;;;;;;;;;;;;;GAaG;AACH,mEAAsE;AAEtE,+DAA0F;AAC1F,6DAAqG;AAYrG,yDAAyD;AAClD,MAAM,gBAAgB,GAAc,GAAG,CAAC,EAAE,CAAC,GAAG,CAAA;AAAxC,QAAA,gBAAgB,oBAAwB;AAErD;;;;GAIG;AACI,KAAK,UAAU,iBAAiB,CACrC,IAAY,EACZ,UAA6F,EAAS;IAEtG,MAAM,QAAQ,GAAG,IAAA,gCAAmB,EAAC,EAAE,IAAI,EAAE,EAAE,wBAAgB,CAAC,CAAA;IAChE,IAAI,uBAAuB,GAAG,KAAK,CAAA;IAEnC,MAAM,MAAM,GAAG,MAAM,IAAA,sCAAqB,EAAC;QACzC,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAQ;QACnD,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,cAAc,EAAE,QAAQ,CAA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O,CAAA;AAChB,CAAC;AAED,gDAAgD;AAChD,SAAgB,wBAAwB,CAAC,IAAY;IACnD,OAAO,IAAA,sCAAwB,GAAE;SAC9B,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,IAAI,CAAC;SAC/C,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;AACrF,CAAC","sourcesContent":["/*\n * 등록된 모드가 **선언한 대로 도는가** — 글자가 아니라 문을 지나서 본다.\n *\n * 모드 선언은 소스에 적힌 값이고, 사람이 만나는 것은 그 값이 문을 지나 만들어 낸 것이다. 그 둘이\n * 어긋나는 자리가 오늘 하루에만 여럿 나왔다: 범주에 없는 도구를 프롬프트가 부르라고 했고, 키는 있는데\n * 번역이 없었고, 부품에 규칙이 있는데 부르는 쪽이 없었다. 전부 「선언은 맞는데 돌지 않는」 모양이다.\n *\n * 그래서 앱의 시험이 이것으로 **자기 모드를 실제로 돌려 본다**:\n * · 그 이름으로 모드가 서는가\n * · 그 모드가 여는 도구가 무엇인가 — 모델에게 실제로 건네지는 목록\n * · 첫 턴 도구 호출을 강제하는가\n * · 화면에 낼 말이 **키가 아니라 문장**으로 나오는가\n * · 슬래시가 가리키는 도구가 그 모드 안에 있는가\n */\nimport { registryAssistantChat } from '@things-factory/ai-client-base'\n\nimport { getAssistantMode, getAssistantModeWarnings } from '../assistant-mode/registry.js'\nimport { assistantModeView, resolveModeSettings, type Translate } from '../assistant-mode/resolve.js'\n\nexport interface ModeRunResult {\n /** 이 모드가 모델에게 실제로 건넨 도구 이름. */\n offeredTools: string[]\n /** 모델이 받은 시스템 프롬프트 — 서버의 것인지 확인할 수 있다. */\n systemPrompt: string\n /** 첫 턴에 도구를 강제했는가. */\n requiredToolOnFirstTurn: boolean\n reply: string\n}\n\n/** 시험용 번역기 — 키를 그대로 돌려준다. 문장이 나와야 할 자리에 키가 나오면 눈에 띈다. */\nexport const keyEchoTranslate: Translate = key => key\n\n/**\n * 등록된 모드로 한 턴을 돌린다 — 프롬프트도 도구도 **등록에서** 나온다.\n *\n * 시험이 자기 값을 넘기면 그 시험은 선언을 안 본 것이다. 그래서 여기서는 `kind` 만 받는다.\n */\nexport async function runRegisteredMode(\n kind: string,\n options: { client: any; hostContext?: any; state?: any; toolAccess?: any; reply?: string } = {} as any\n): Promise<ModeRunResult> {\n const settings = resolveModeSettings({ kind }, keyEchoTranslate)\n let requiredToolOnFirstTurn = false\n\n const result = await registryAssistantChat({\n client: options.client,\n messages: [{ role: 'user', content: '한 턴' }] as any,\n systemPrompt: settings.systemPrompt,\n toolCategories: settings.toolCategories,\n requireToolOnFirstTurn: (requiredToolOnFirstTurn = Boolean(settings.requireToolOnFirstTurn)),\n model: settings.model,\n temperature: settings.temperature,\n maxTokens: settings.maxTokens,\n hostContext: options.hostContext,\n /*\n * 이 하네스가 묻는 것은 **모드**다 — 「이 모드가 무엇을 여는가」이지 「이 사람이 문을 지나는가」가\n * 아니다. 관문이 `doors` 로 옮겨간 뒤(ADR-0071 결정 2) 검사를 안 넘기면 문을 적은 도구가 전부\n * 닫히고, 그러면 앱의 적합성 시험에서 **실제 자료를 읽는 도구만** 조용히 사라진다. 그래서 기본은\n * 모든 문을 지나는 사람이고, 다른 쪽을 보고 싶은 앱은 `toolAccess` 를 적어 그 경우를 쓴다.\n * 권한 축은 자기 시험이 따로 본다(`tool-access.test.ts` · `tool-scope.test.ts`).\n */\n toolAccess: options.toolAccess ?? (async () => true),\n state: options.state ?? { domain: { id: 'dom-1' }, user: { id: 'u-1' } }\n })\n\n return {\n offeredTools: [...result.offeredTools],\n systemPrompt: settings.systemPrompt,\n requiredToolOnFirstTurn,\n reply: result.reply\n }\n}\n\nexport interface ModeWording {\n placeholder?: string\n /** 빈 대화의 제목과 한 줄 — 없으면 공용 대화창이 보드 제품의 글을 낸다. */\n intro?: { title: string; subtitle: string }\n /** 빈 대화의 예시 — 이 대화가 실제로 할 수 있는 말. */\n examples?: Array<{ label: string; items: string[] }>\n slash: { name: string; description: string; template: string }[]\n footerNotice?: string\n stagedNotice?: string\n}\n\n/** 화면에 낼 말 — 주어진 사전으로 옮긴 결과. 키가 그대로 남으면 사전에 없는 것이다. */\nexport function modeWording(kind: string, dictionary: Record<string, string>): ModeWording {\n const view = assistantModeView(kind, key => dictionary[key] ?? key)\n return {\n placeholder: view.placeholder,\n intro: view.intro,\n examples: view.examples,\n slash: view.slashTemplates,\n footerNotice: view.footerNotice,\n stagedNotice: view.stagedNotice\n }\n}\n\n/** 사전에 없어서 키가 그대로 화면에 나갈 말들. 비어 있어야 한다. */\nexport function missingWording(kind: string, dictionary: Record<string, string>): string[] {\n const missing: string[] = []\n const spec = getAssistantMode(kind)\n if (!spec) return [`mode:${kind}`]\n\n for (const key of [spec.placeholderKey, spec.footerNoticeKey, spec.stagedNoticeKey]) {\n if (key && !(key in dictionary)) missing.push(key)\n }\n /* 빈 대화의 말도 사전에 있어야 한다 — 없으면 화면에 키가 그대로 찍힌다. */\n for (const key of [spec.introKeys?.title, spec.introKeys?.subtitle]) {\n if (key && !(key in dictionary)) missing.push(key)\n }\n for (const group of spec.exampleKeys ?? []) {\n for (const key of [group.labelKey, ...group.itemKeys]) {\n if (!(key in dictionary)) missing.push(key)\n }\n }\n for (const slash of spec.slashTemplates ?? []) {\n for (const key of [slash.descriptionKey, slash.templateKey]) {\n if (!(key in dictionary)) missing.push(key)\n }\n }\n return missing\n}\n\n/** 이 모드가 자기 도구로 못 하는 일을 제안하는가 — 부팅 보고와 같은 답. */\nexport function modePromisesItCannotKeep(kind: string): string[] {\n return getAssistantModeWarnings()\n .filter(warning => warning.params.kind === kind)\n .map(warning => `${warning.code}:${warning.params.slash}→${warning.params.tool}`)\n}\n"]}
|
|
@@ -5,19 +5,32 @@ exports.toolAccessFor = toolAccessFor;
|
|
|
5
5
|
* Who may use a registered tool — the request's answer to `ToolAccessCheck`.
|
|
6
6
|
*
|
|
7
7
|
* `ai-client-base` decides *which* tools a conversation may use but does not know auth, so the
|
|
8
|
-
* conversation doors hand it this. A tool
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* Asking anything looser here would make the tool a second,
|
|
8
|
+
* conversation doors hand it this. A tool names the GraphQL doors it reaches (ADR-0071 decision 2);
|
|
9
|
+
* this resolves each one against AUTH's field table (`privilegeOfField`, ADR-0072 decision 5) and
|
|
10
|
+
* asks `checkPermission` exactly what `@privilege` on that field asks — the same user, domain,
|
|
11
|
+
* address safety and prohibited list. Asking anything looser here would make the tool a second,
|
|
12
|
+
* softer way into that door.
|
|
13
|
+
*
|
|
14
|
+
* **The declaration is the door's, and it is read, not copied.** Until 2026-09-18 a tool carried its
|
|
15
|
+
* own `{ category, privilege }` and this asked that copy. A copy drifts from the door it mirrors and
|
|
16
|
+
* the looser of the two wins; the table removed the need for one.
|
|
17
|
+
*
|
|
18
|
+
* The three answers of the table are read exactly as the reader's gate reads them (`door-access.ts`)
|
|
19
|
+
* — an unknown field closes, a field with no declaration opens as far as that field opens.
|
|
12
20
|
*/
|
|
13
21
|
const auth_base_1 = require("@things-factory/auth-base");
|
|
22
|
+
const door_access_js_1 = require("./chat-message/door-access.js");
|
|
14
23
|
function toolAccessFor(context) {
|
|
15
24
|
const { domain, user, unsafeIP, prohibitedPrivileges } = context?.state ?? {};
|
|
16
|
-
|
|
17
|
-
|
|
25
|
+
const passes = (0, door_access_js_1.doorCheck)({
|
|
26
|
+
lookup: auth_base_1.privilegeOfField,
|
|
27
|
+
permits: gate => (0, auth_base_1.checkPermission)(gate, user, domain, unsafeIP, prohibitedPrivileges)
|
|
28
|
+
});
|
|
29
|
+
return async (door) => {
|
|
30
|
+
/* No caller, no answer — a request without a user or domain passes no door. */
|
|
18
31
|
if (!user || !domain)
|
|
19
32
|
return false;
|
|
20
|
-
return
|
|
33
|
+
return await passes(door);
|
|
21
34
|
};
|
|
22
35
|
}
|
|
23
36
|
//# sourceMappingURL=tool-access.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-access.js","sourceRoot":"","sources":["../../server/service/tool-access.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"tool-access.js","sourceRoot":"","sources":["../../server/service/tool-access.ts"],"names":[],"mappings":";;AAsBA,sCAaC;AAnCD;;;;;;;;;;;;;;;;GAgBG;AACH,yDAA6E;AAG7E,kEAAyD;AAEzD,SAAgB,aAAa,CAAC,OAAoC;IAChE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,oBAAoB,EAAE,GAAG,OAAO,EAAE,KAAK,IAAI,EAAE,CAAA;IAE7E,MAAM,MAAM,GAAG,IAAA,0BAAS,EAAC;QACvB,MAAM,EAAE,4BAAgB;QACxB,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,IAAA,2BAAe,EAAC,IAAW,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,CAAC;KAC5F,CAAC,CAAA;IAEF,OAAO,KAAK,EAAE,IAAY,EAAE,EAAE;QAC5B,+EAA+E;QAC/E,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAA;QAClC,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,CAAA;IAC3B,CAAC,CAAA;AACH,CAAC","sourcesContent":["/*\n * Who may use a registered tool — the request's answer to `ToolAccessCheck`.\n *\n * `ai-client-base` decides *which* tools a conversation may use but does not know auth, so the\n * conversation doors hand it this. A tool names the GraphQL doors it reaches (ADR-0071 decision 2);\n * this resolves each one against AUTH's field table (`privilegeOfField`, ADR-0072 decision 5) and\n * asks `checkPermission` exactly what `@privilege` on that field asks — the same user, domain,\n * address safety and prohibited list. Asking anything looser here would make the tool a second,\n * softer way into that door.\n *\n * **The declaration is the door's, and it is read, not copied.** Until 2026-09-18 a tool carried its\n * own `{ category, privilege }` and this asked that copy. A copy drifts from the door it mirrors and\n * the looser of the two wins; the table removed the need for one.\n *\n * The three answers of the table are read exactly as the reader's gate reads them (`door-access.ts`)\n * — an unknown field closes, a field with no declaration opens as far as that field opens.\n */\nimport { checkPermission, privilegeOfField } from '@things-factory/auth-base'\nimport type { ToolAccessCheck } from '@things-factory/ai-client-base'\n\nimport { doorCheck } from './chat-message/door-access.js'\n\nexport function toolAccessFor(context: { state?: any } | undefined): ToolAccessCheck {\n const { domain, user, unsafeIP, prohibitedPrivileges } = context?.state ?? {}\n\n const passes = doorCheck({\n lookup: privilegeOfField,\n permits: gate => checkPermission(gate as any, user, domain, unsafeIP, prohibitedPrivileges)\n })\n\n return async (door: string) => {\n /* No caller, no answer — a request without a user or domain passes no door. */\n if (!user || !domain) return false\n return await passes(door)\n }\n}\n"]}
|
|
@@ -3,16 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.formatToolRegistryWarnings = formatToolRegistryWarnings;
|
|
4
4
|
exports.formatAssistantModeWarnings = formatAssistantModeWarnings;
|
|
5
5
|
/*
|
|
6
|
-
* At boot, say what registered but is not yet what the contracts require — tools
|
|
7
|
-
* (
|
|
6
|
+
* At boot, say what registered but is not yet what the contracts require — tools that named no doors
|
|
7
|
+
* (ADR-0071 decision 2) and modes offering `/` sentences their tools cannot answer (ADR-0058
|
|
8
|
+
* decision 3).
|
|
8
9
|
*
|
|
9
10
|
* One window, because it is one question: what state is this deployment's AI in (standard A7-a).
|
|
10
11
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* empty across the apps, registration becomes a refusal and this report goes away.
|
|
12
|
+
* A tool that names no doors still registers; refusing at registration would stop a whole app from
|
|
13
|
+
* booting over one omission. It is the **gate** that refuses it, tool by tool — such a tool is
|
|
14
|
+
* offered to no conversation (`resolveToolScope`). So this list is not a soft warning about
|
|
15
|
+
* something that still works: it names the tools that are not working, and why.
|
|
16
16
|
*/
|
|
17
17
|
const env_1 = require("@things-factory/env");
|
|
18
18
|
const ai_client_base_1 = require("@things-factory/ai-client-base");
|
|
@@ -24,8 +24,7 @@ function formatToolRegistryWarnings(warnings) {
|
|
|
24
24
|
for (const warning of warnings) {
|
|
25
25
|
const tools = byCode.get(warning.code) ?? [];
|
|
26
26
|
/* 문 이름이 있으면 함께 적는다 — 「어느 문이 아직 선언이 없나」가 다음에 할 일이다. */
|
|
27
|
-
|
|
28
|
-
tools.push(`${warning.params.category}/${warning.params.tool}(${warning.params.kind})${doors}`);
|
|
27
|
+
tools.push(`${warning.params.category}/${warning.params.tool}(${warning.params.kind})`);
|
|
29
28
|
byCode.set(warning.code, tools);
|
|
30
29
|
}
|
|
31
30
|
return [...byCode].map(([code, tools]) => `[ai-assistant] ${code} ×${tools.length}: ${tools.join(', ')}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-registry-boot-report.js","sourceRoot":"","sources":["../server/tool-registry-boot-report.ts"],"names":[],"mappings":";;AAmBA,
|
|
1
|
+
{"version":3,"file":"tool-registry-boot-report.js","sourceRoot":"","sources":["../server/tool-registry-boot-report.ts"],"names":[],"mappings":";;AAmBA,gEASC;AAGD,kEAQC;AAvCD;;;;;;;;;;;GAWG;AACH,6CAA4C;AAC5C,mEAAkG;AAElG,gEAAuG;AACvG,6EAAqG;AAErG,qGAAqG;AACrG,SAAgB,0BAA0B,CAAC,QAA4C;IACrF,MAAM,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAA;IAC1C,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,CAAA;QAC5C,sDAAsD;QACtD,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,IAAI,OAAO,CAAC,MAAM,CA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K,MAAM,IAAI,IAAI,2BAA2B,CAAC,IAAA,mCAAwB,GAAE,CAAC;QAAE,YAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC7F;;;OAGG;IACH,KAAK,MAAM,IAAI,IAAI,IAAA,0DAA6B,EAAC,IAAA,oDAAuB,GAAE,CAAC;QAAE,YAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAChG,CAAC,CAAC,CAAA","sourcesContent":["/*\n * At boot, say what registered but is not yet what the contracts require — tools that named no doors\n * (ADR-0071 decision 2) and modes offering `/` sentences their tools cannot answer (ADR-0058\n * decision 3).\n *\n * One window, because it is one question: what state is this deployment's AI in (standard A7-a).\n *\n * A tool that names no doors still registers; refusing at registration would stop a whole app from\n * booting over one omission. It is the **gate** that refuses it, tool by tool — such a tool is\n * offered to no conversation (`resolveToolScope`). So this list is not a soft warning about\n * something that still works: it names the tools that are not working, and why.\n */\nimport { logger } from '@things-factory/env'\nimport { getToolRegistryWarnings, type ToolRegistryWarning } from '@things-factory/ai-client-base'\n\nimport { getAssistantModeWarnings, type AssistantModeWarning } from './service/assistant-mode/index.js'\nimport { doorDeclarationWarnings, formatDoorDeclarationWarnings } from './door-declaration-report.js'\n\n/** One line per code: the code, how many, and which tools. Empty when there is nothing to report. */\nexport function formatToolRegistryWarnings(warnings: ReadonlyArray<ToolRegistryWarning>): string[] {\n const byCode = new Map<string, string[]>()\n for (const warning of warnings) {\n const tools = byCode.get(warning.code) ?? []\n /* 문 이름이 있으면 함께 적는다 — 「어느 문이 아직 선언이 없나」가 다음에 할 일이다. */\n tools.push(`${warning.params.category}/${warning.params.tool}(${warning.params.kind})`)\n byCode.set(warning.code, tools)\n }\n return [...byCode].map(([code, tools]) => `[ai-assistant] ${code} ×${tools.length}: ${tools.join(', ')}`)\n}\n\n/** One line per code: the code, how many, and which modes promised what. */\nexport function formatAssistantModeWarnings(warnings: ReadonlyArray<AssistantModeWarning>): string[] {\n const byCode = new Map<string, string[]>()\n for (const warning of warnings) {\n const offers = byCode.get(warning.code) ?? []\n offers.push(`${warning.params.kind}:/${warning.params.slash}→${warning.params.tool}`)\n byCode.set(warning.code, offers)\n }\n return [...byCode].map(([code, offers]) => `[ai-assistant] ${code} ×${offers.length}: ${offers.join(', ')}`)\n}\n\n/*\n * After every module has registered: a mode may declare its slash sentences before the package\n * that registers the tools they need, so this cannot be checked when the mode registers.\n */\nprocess.on('bootstrap-module-start' as any, () => {\n for (const line of formatToolRegistryWarnings(getToolRegistryWarnings())) logger.warn(line)\n for (const line of formatAssistantModeWarnings(getAssistantModeWarnings())) logger.warn(line)\n /*\n * 이 자리에서만 물을 수 있는 것 — 적어 둔 문이 스키마에 있나. AUTH 의 필드 표는 스키마를 지은 뒤에\n * 차고, 이 훅은 그 뒤에 돈다(`builtSchema` 를 함께 받는다).\n */\n for (const line of formatDoorDeclarationWarnings(doorDeclarationWarnings())) logger.warn(line)\n})\n"]}
|