@things-factory/ai-assistant 10.1.314 → 10.1.319

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist-client/utils/entry-proposal.d.ts +4 -1
  2. package/dist-client/utils/entry-proposal.js +5 -2
  3. package/dist-client/utils/entry-workspace.js +3 -3
  4. package/dist-server/index.d.ts +1 -0
  5. package/dist-server/index.js +4 -0
  6. package/dist-server/service/chat-session/attachment-tools.js +2 -0
  7. package/dist-server/service/chat-session/chat-session.d.ts +6 -0
  8. package/dist-server/service/chat-session/chat-session.js +9 -1
  9. package/dist-server/service/data-entry/entry-apply.js +3 -4
  10. package/dist-server/service/data-entry/entry-target.d.ts +24 -1
  11. package/dist-server/service/data-entry/entry-target.js +49 -8
  12. package/dist-server/service/data-entry/entry-tools.d.ts +4 -3
  13. package/dist-server/service/data-entry/entry-tools.js +50 -11
  14. package/dist-server/service/data-entry/entry-update.d.ts +1 -0
  15. package/dist-server/service/data-entry/entry-update.js +2 -0
  16. package/dist-server/service/data-read/read-tools.js +11 -6
  17. package/dist-server/service/database-error.d.ts +5 -0
  18. package/dist-server/service/database-error.js +27 -0
  19. package/dist-server/service/index.d.ts +2 -0
  20. package/dist-server/service/index.js +7 -1
  21. package/dist-server/service/mcp/mcp-audit.d.ts +7 -0
  22. package/dist-server/service/mcp/mcp-audit.js +44 -0
  23. package/dist-server/service/mcp/mcp-call.d.ts +60 -0
  24. package/dist-server/service/mcp/mcp-call.js +136 -0
  25. package/dist-server/service/mcp/mcp-conversation.d.ts +30 -0
  26. package/dist-server/service/mcp/mcp-conversation.js +203 -0
  27. package/dist-server/service/mcp/mcp-held-proposal.d.ts +19 -0
  28. package/dist-server/service/mcp/mcp-held-proposal.js +134 -0
  29. package/dist-server/service/mcp/mcp-route.d.ts +7 -0
  30. package/dist-server/service/mcp/mcp-route.js +50 -0
  31. package/dist-server/service/mcp/mcp-scope.d.ts +59 -0
  32. package/dist-server/service/mcp/mcp-scope.js +169 -0
  33. package/dist-server/service/mcp/mcp-server.d.ts +43 -0
  34. package/dist-server/service/mcp/mcp-server.js +163 -0
  35. package/dist-server/service/mcp/mcp-settings.d.ts +33 -0
  36. package/dist-server/service/mcp/mcp-settings.js +25 -0
  37. package/dist-server/service/people/invite-tools.js +3 -0
  38. package/dist-server/service/request-translator.d.ts +6 -0
  39. package/dist-server/service/request-translator.js +14 -0
  40. package/dist-server/service/workspace/workspace-blocks.d.ts +2 -0
  41. package/dist-server/service/workspace/workspace-blocks.js +3 -1
  42. package/dist-server/service/workspace/workspace-tools.js +3 -1
  43. package/package.json +7 -7
  44. package/translations/en.json +10 -1
  45. package/translations/es.json +10 -1
  46. package/translations/ja.json +10 -1
  47. package/translations/ko.json +10 -1
  48. package/translations/ms.json +10 -1
  49. package/translations/zh.json +10 -1
@@ -0,0 +1,60 @@
1
+ import { type ToolAccessCheck, type ToolSpec, type ToolTranslate } from '@things-factory/ai-client-base';
2
+ /** What MCP's `tools/call` answers. */
3
+ export interface McpToolResult {
4
+ content: ({
5
+ type: 'text';
6
+ text: string;
7
+ } | {
8
+ type: 'image';
9
+ data: string;
10
+ mimeType: string;
11
+ })[];
12
+ isError?: boolean;
13
+ }
14
+ /** A proposal handed in from outside, as its card - kept in the person's conversation for the connection. */
15
+ export interface McpKept {
16
+ /** This server's origin as the client reached it - the address handed back is a full one. */
17
+ origin?: string;
18
+ sessionId: string;
19
+ tool: string;
20
+ category: string;
21
+ doors: string[];
22
+ card: Record<string, any>;
23
+ state: any;
24
+ t: ToolTranslate;
25
+ }
26
+ /** Where a proposal handed in from outside goes (ADR-0237 decision 11). */
27
+ export interface McpOutside {
28
+ /** The person's conversation for this connection - made the first time, the same one after. */
29
+ conversationOf(state: any, t: ToolTranslate): Promise<{
30
+ id: string;
31
+ name: string;
32
+ }>;
33
+ /** Keeps the card as a message of that conversation and tells the person; where they find it, and the earlier cards of the same work it replaced. */
34
+ keep(kept: McpKept): Promise<{
35
+ address: string;
36
+ replaced: string[];
37
+ }>;
38
+ }
39
+ export interface McpCall {
40
+ spec: ToolSpec;
41
+ category: string;
42
+ args: unknown;
43
+ state: any;
44
+ t: ToolTranslate;
45
+ access: ToolAccessCheck;
46
+ /** The client the person connected - written on the record. */
47
+ client?: string;
48
+ /** Where a kept proposal goes; a tool that keeps one is not offered without it. */
49
+ outside?: McpOutside;
50
+ origin?: string;
51
+ }
52
+ /**
53
+ * A proposal that could not be kept - the conversation or its message could not be written. The call is recorded as a
54
+ * failure and the client gets a JSON-RPC error: it is never told a card was handed in that is not there.
55
+ */
56
+ export declare class McpKeepFailed extends Error {
57
+ readonly code = "mcp-keep-failed";
58
+ constructor();
59
+ }
60
+ export declare function callMcpTool({ spec, category, args, state, t, access, client, outside, origin }: McpCall): Promise<McpToolResult>;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.McpKeepFailed = void 0;
4
+ exports.callMcpTool = callMcpTool;
5
+ /*
6
+ * One tool call from outside, run where every call runs (ADR-0237 decisions 3 · 4).
7
+ *
8
+ * The context is the unattended run's shape - nobody's screen, nobody's conversation: the request's state and
9
+ * translator, the gate the list was built with, an empty `host` and no attachments. `conversation`, `run`, `progress`
10
+ * and `mode` are left out; a tool that needed them is not offered here. The call goes through `runRegisteredTool`, so
11
+ * the application's audit sees it on the road `mcp` with the client that made it.
12
+ *
13
+ * What comes back is cut as the conversation loop cuts it: pictures leave the JSON as image parts, and what only a
14
+ * card needs (`forScreen`) never goes out. A list read too long for one answer offers a card in a conversation; here
15
+ * there is no card, so it says it is a part and asks to narrow.
16
+ */
17
+ const ai_client_base_1 = require("@things-factory/ai-client-base");
18
+ const env_1 = require("@things-factory/env");
19
+ const database_error_js_1 = require("../database-error.js");
20
+ const mcp_scope_js_1 = require("./mcp-scope.js");
21
+ /**
22
+ * A proposal that could not be kept - the conversation or its message could not be written. The call is recorded as a
23
+ * failure and the client gets a JSON-RPC error: it is never told a card was handed in that is not there.
24
+ */
25
+ class McpKeepFailed extends Error {
26
+ constructor() {
27
+ super('The proposal could not be kept; nothing was handed in. Try again.');
28
+ this.code = 'mcp-keep-failed';
29
+ }
30
+ }
31
+ exports.McpKeepFailed = McpKeepFailed;
32
+ async function callMcpTool({ spec, category, args, state, t, access, client, outside, origin }) {
33
+ const keeps = !!spec.keepsProposal && !!outside;
34
+ /* No conversation is made before there is a card to keep - a refused call leaves none behind. */
35
+ const context = { state, t, access, host: {}, attachments: [], outside: { ...(client ? { client } : {}) } };
36
+ const answer = keeps ? (returned) => handIn(spec, category, returned, outside, state, t, origin) : forOutside;
37
+ let result;
38
+ try {
39
+ result = await (0, ai_client_base_1.runRegisteredTool)({ spec, category, args: (0, mcp_scope_js_1.argsForOutside)(spec, args), context, path: 'mcp', ...(client ? { client } : {}), answer });
40
+ }
41
+ catch (e) {
42
+ if (e instanceof McpKeepFailed)
43
+ throw e;
44
+ /* The loop answers a throw to the model the same way - the agent reads why; a database's own words stay in the log. */
45
+ return { content: [{ type: 'text', text: JSON.stringify({ error: ai_client_base_1.TOOL_FAILED, message: (0, database_error_js_1.databaseErrorUnspoken)(e, t) ?? String(e?.message ?? e) }) }], isError: true };
46
+ }
47
+ if (keeps && result?.handedIn === true)
48
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
49
+ const { value: given, images } = (0, ai_client_base_1.takeToolImages)(result);
50
+ const { value } = (0, ai_client_base_1.takeForScreen)(given);
51
+ const shown = value && typeof value === 'object' && value.proposed === true ? withoutCard(value) : value;
52
+ return {
53
+ content: [
54
+ { type: 'text', text: JSON.stringify(shown ?? null) },
55
+ /* `takeToolImages` hands back the bytes it read, never a link. */
56
+ ...images.flatMap(({ source }) => (source.kind === 'base64' ? [{ type: 'image', data: Buffer.from(source.data).toString('base64'), mimeType: source.mediaType }] : []))
57
+ ],
58
+ ...(shown && typeof shown === 'object' && shown.rejected === true ? { isError: true } : {})
59
+ };
60
+ }
61
+ /**
62
+ * What goes out of what a tool returned - recorded as it goes out (`runRegisteredTool`'s `answer`). A card nobody here
63
+ * can press is a refusal: the marks should have kept the tool from going out, and a card is never passed on as an
64
+ * answer. A list read's panel is kept - it is cut to a part of the list below.
65
+ */
66
+ function forOutside(result) {
67
+ if (!result || typeof result !== 'object' || result.proposed !== true || isListPart(result))
68
+ return result;
69
+ return { rejected: true, error: 'mcp-answer-for-a-screen', message: 'This answer is a card for a person in the app to press; it cannot be given here.' };
70
+ }
71
+ /** A list read that put its long result on the AI 작업 패널 - its rows and their count are in the answer. */
72
+ const isListPart = (value) => Array.isArray(value.rows) && typeof value.total === 'number';
73
+ /**
74
+ * A list read's answer that offered the panel - the card's fields gone, and the panel's sentence replaced by what is
75
+ * true here: the rows are a part of the list.
76
+ */
77
+ function withoutCard(value) {
78
+ const { proposed: _p, kind: _k, icon: _i, label: _l, message: _m, ...said } = value;
79
+ const shown = Array.isArray(said.rows) ? said.rows.length : 0;
80
+ const total = said.total ?? said.read ?? shown;
81
+ const read = said.read ?? shown;
82
+ return {
83
+ ...said,
84
+ message: `Only ${shown} of ${total} rows are here. Narrow the conditions to read the rest.` +
85
+ ` The sums and groups are of the ${read} rows read${said.complete === false ? ', not of the whole list' : ''}; every number you say comes from them.`
86
+ };
87
+ }
88
+ /**
89
+ * A kept proposal handed in: its card goes into the person's conversation for the connection as the conversation loop
90
+ * would have kept it (the tool, the values, what the card shows, a key), and the agent is told only that it was handed
91
+ * in, where the person finds it, how many rows are ready, and which earlier cards of the same work it replaced - never
92
+ * the values it sent, which now live on the card. A result that is no proposal (a refusal) goes back as it is.
93
+ */
94
+ async function handIn(spec, category, returned, outside, state, t, origin) {
95
+ const { value, forScreen } = (0, ai_client_base_1.takeForScreen)((0, ai_client_base_1.takeToolImages)(returned).value);
96
+ if (!value || typeof value !== 'object' || value.proposed !== true)
97
+ return returned;
98
+ const candidate = { tool: spec.name, ...value, ...forScreen };
99
+ const effectKey = (0, ai_client_base_1.proposalEffectKey)(candidate);
100
+ const card = { ...candidate, key: typeof candidate.key === 'string' && candidate.key ? candidate.key : effectKey, effectKey };
101
+ let conversation;
102
+ let kept;
103
+ try {
104
+ conversation = await outside.conversationOf(state, t);
105
+ kept = await outside.keep({ origin, sessionId: conversation.id, tool: spec.name, category, doors: spec.doors ?? [], card, state, t });
106
+ }
107
+ catch (error) {
108
+ env_1.logger.error('[ai-assistant] a proposal handed in from outside could not be kept', error);
109
+ throw new McpKeepFailed();
110
+ }
111
+ const counts = (value.counts ?? {});
112
+ const rows = Array.isArray(value.rows) ? value.rows : [];
113
+ const blockedRows = rows
114
+ .filter(row => (row?.issues ?? []).some((issue) => issue?.blocking))
115
+ .map(row => ({ row: row.index, issues: (row.issues ?? []).filter((issue) => issue?.blocking).map((issue) => issue.code) }));
116
+ const replaced = kept.replaced ?? [];
117
+ return {
118
+ handedIn: true,
119
+ /* Its key - a module that asks a person to approve the agent's work names the card by it (ADR-0237 amendment 1). */
120
+ proposal: card.key,
121
+ target: value.target,
122
+ ...(value.op ? { op: value.op } : {}),
123
+ rows: counts.rows ?? rows.length,
124
+ ready: counts.ready ?? rows.length - blockedRows.length,
125
+ blocked: counts.blocked ?? blockedRows.length,
126
+ ...(blockedRows.length ? { blockedRows } : {}),
127
+ /* Always said: the earlier cards of the same work this one replaced - they can no longer be pressed. */
128
+ replaced,
129
+ conversation: conversation.name,
130
+ address: kept.address,
131
+ message: 'The proposal is kept in the person\'s assistant conversation named above; nothing is written until they press its card in the app, where everything is asked again. ' +
132
+ (replaced.length ? `It replaced ${replaced.length} earlier card(s) of the same work, which can no longer be pressed. ` : '') +
133
+ (blockedRows.length ? 'Rows kept out are listed by their issue codes - fix them and hand the whole set in again; the newest card of the same work replaces the earlier one.' : 'Tell the person where to find it.')
134
+ };
135
+ }
136
+ //# sourceMappingURL=mcp-call.js.map
@@ -0,0 +1,30 @@
1
+ import type { ToolTranslate } from '@things-factory/ai-client-base';
2
+ import type { McpKept, McpOutside } from './mcp-call.js';
3
+ export interface AssistantHome {
4
+ anchorType: string;
5
+ anchorId: string;
6
+ }
7
+ /**
8
+ * The anchor an app's assistant opens at home - where a conversation made on the server for a person (an outside
9
+ * connection's) is listed. Called by the app at boot; the domain's own anchor when nobody calls it.
10
+ */
11
+ export declare function registerAssistantHome(home: (domain: {
12
+ id: string;
13
+ }) => AssistantHome): void;
14
+ export declare function assistantHomeOf(domain: {
15
+ id: string;
16
+ }): AssistantHome;
17
+ /** The person's conversation for this connection - the same one each time; made through the conversation's own door. */
18
+ export declare function outsideConversationOf(state: any, t: ToolTranslate): Promise<{
19
+ id: string;
20
+ name: string;
21
+ }>;
22
+ /**
23
+ * The card kept as a message of that conversation, as a turn keeps it (`proposals`, the doors of the tool that made it,
24
+ * the person as its writer), the conversation's activity moved on, and the person told - with where to find it.
25
+ */
26
+ export declare function keepOutsideProposal(kept: McpKept): Promise<{
27
+ address: string;
28
+ replaced: string[];
29
+ }>;
30
+ export declare const OUTSIDE_CONVERSATION: McpOutside;
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.OUTSIDE_CONVERSATION = void 0;
37
+ exports.registerAssistantHome = registerAssistantHome;
38
+ exports.assistantHomeOf = assistantHomeOf;
39
+ exports.outsideConversationOf = outsideConversationOf;
40
+ exports.keepOutsideProposal = keepOutsideProposal;
41
+ let homeOf = domain => ({ anchorType: 'domain', anchorId: domain.id });
42
+ /**
43
+ * The anchor an app's assistant opens at home - where a conversation made on the server for a person (an outside
44
+ * connection's) is listed. Called by the app at boot; the domain's own anchor when nobody calls it.
45
+ */
46
+ function registerAssistantHome(home) {
47
+ homeOf = home;
48
+ }
49
+ function assistantHomeOf(domain) {
50
+ return homeOf(domain);
51
+ }
52
+ const say = (t, key, defaultValue, params = {}) => t(`ai-assistant.text.${key}`, { ...params, defaultValue });
53
+ /** The client's name as the domain registered it; its id when there is none. */
54
+ async function clientNameOf(state) {
55
+ const clientId = state?.oauth?.clientId;
56
+ if (!clientId)
57
+ return 'client';
58
+ try {
59
+ const { Application } = await Promise.resolve().then(() => __importStar(require('@things-factory/auth-base')));
60
+ const { getRepository } = await Promise.resolve().then(() => __importStar(require('@things-factory/shell')));
61
+ const found = await getRepository(Application).findOne({ where: { appKey: clientId, domain: { id: state.domain.id } } });
62
+ return found?.name || clientId;
63
+ }
64
+ catch {
65
+ return clientId;
66
+ }
67
+ }
68
+ /** The person's conversation for this connection - the same one each time; made through the conversation's own door. */
69
+ async function outsideConversationOf(state, t) {
70
+ const { domain, user, oauth } = state ?? {};
71
+ const connectionId = oauth?.grantId;
72
+ if (!domain?.id || !user?.id || !connectionId)
73
+ throw new Error('an outside conversation needs the person, the domain and the connection');
74
+ const [{ getRepository, isUniqueViolation }, { ChatSession }, { ChatSessionParticipant }, { ChatSessionResolver }] = await Promise.all([
75
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
76
+ Promise.resolve().then(() => __importStar(require('../chat-session/chat-session.js'))),
77
+ Promise.resolve().then(() => __importStar(require('../chat-session-participant/chat-session-participant.js'))),
78
+ Promise.resolve().then(() => __importStar(require('../chat-session-resolver.js')))
79
+ ]);
80
+ const existing = async () => (await getRepository(ChatSession).findOne({ where: { domain: { id: domain.id }, connectionId } }));
81
+ const found = await existing();
82
+ if (found)
83
+ return { id: found.id, name: found.name };
84
+ const name = say(t, 'outside-agent-conversation', 'Outside agent: {client}', { client: await clientNameOf(state) });
85
+ const home = assistantHomeOf(domain);
86
+ /* The conversation's own door - its owner seat, its visibility (private, as every new one) - then the connection. */
87
+ const made = await new ChatSessionResolver().createAISession(home.anchorType, home.anchorId, name, { state: { domain, user }, t });
88
+ try {
89
+ await getRepository(ChatSession).update(made.id, { connectionId });
90
+ return { id: made.id, name: made.name ?? name };
91
+ }
92
+ catch (error) {
93
+ /*
94
+ * Another first call made it at the same time - the connection's unique index keeps one. That one is the
95
+ * conversation; the one just made is still empty and nobody has seen it, so it goes, seat and all.
96
+ */
97
+ if (!isUniqueViolation(error))
98
+ throw error;
99
+ const theirs = await existing();
100
+ if (!theirs)
101
+ throw error;
102
+ await getRepository(ChatSessionParticipant).delete({ session: { id: made.id } });
103
+ await getRepository(ChatSession).delete(made.id);
104
+ return { id: theirs.id, name: theirs.name };
105
+ }
106
+ }
107
+ /**
108
+ * The card kept as a message of that conversation, as a turn keeps it (`proposals`, the doors of the tool that made it,
109
+ * the person as its writer), the conversation's activity moved on, and the person told - with where to find it.
110
+ */
111
+ async function keepOutsideProposal(kept) {
112
+ const { state, t, sessionId, card, doors, tool } = kept;
113
+ const { domain, user } = state;
114
+ const [{ getRepository }, { ChatMessage }, { ChatSession }, { publishChatMessage }, { publishSessionActivity }, { activityPatch }, { doorsForAnswer }] = await Promise.all([
115
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
116
+ Promise.resolve().then(() => __importStar(require('../chat-message/chat-message.js'))),
117
+ Promise.resolve().then(() => __importStar(require('../chat-session/chat-session.js'))),
118
+ Promise.resolve().then(() => __importStar(require('../chat-message/chat-message-publish.js'))),
119
+ Promise.resolve().then(() => __importStar(require('../chat-session/session-activity-publish.js'))),
120
+ Promise.resolve().then(() => __importStar(require('../chat-session/session-inbox.js'))),
121
+ Promise.resolve().then(() => __importStar(require('../chat-message/message-doors.js')))
122
+ ]);
123
+ const client = await clientNameOf(state);
124
+ const replaced = await replacedBy(sessionId, card);
125
+ const rows = Number(card.counts?.rows ?? (Array.isArray(card.rows) ? card.rows.length : 0));
126
+ /* `count` picks the language's plural form where it has one (`_one`): 「1 row」, not 「1 rows」. */
127
+ const content = say(t, 'outside-agent-proposal', '{client} handed in a proposal of {count} rows. Nothing is entered until you press the card.', { client, count: rows });
128
+ /* The doors of the tool that made it (ADR-0073) - a reader who cannot pass them sees that it is here, not its values. */
129
+ const answerDoors = doorsForAnswer([{ name: tool, outcome: 'proposed' }], () => doors);
130
+ const message = await getRepository(ChatMessage).save({
131
+ session: { id: sessionId },
132
+ role: 'assistant',
133
+ content,
134
+ doors: answerDoors,
135
+ toolUsages: JSON.stringify([{ name: tool, arguments: {}, kind: 'read', outcome: 'proposed' }]),
136
+ proposals: JSON.stringify([card]),
137
+ creator: user,
138
+ updater: user
139
+ });
140
+ const session = await getRepository(ChatSession).findOne({ where: { id: sessionId } });
141
+ publishChatMessage({ domainId: domain.id, sessionId, message });
142
+ publishSessionActivity({ domainId: domain.id, sessionId, kind: 'message', anchorType: session?.anchorType, anchorId: session?.anchorId, preview: content, actorId: user.id });
143
+ await getRepository(ChatSession).update(sessionId, { updater: user, ...activityPatch(content, new Date(), answerDoors) });
144
+ const path = `assistant-workspace?session=${encodeURIComponent(sessionId)}&entry=${encodeURIComponent(String(card.key))}`;
145
+ const address = await linkOf(kept.origin, state, path);
146
+ await tellPerson(state, t, client, path);
147
+ return { address, replaced };
148
+ }
149
+ /** The earlier cards of the conversation the new card replaces - of the same work, still the newest of it, not yet pressed. */
150
+ async function replacedBy(sessionId, card) {
151
+ const [{ getRepository }, { Like, Not, IsNull }, { ChatMessage }, { workOfProposal }, { entryProposalAnswered, findEntryProposal }, { PROPOSAL_OUTCOME_PREFIX }] = await Promise.all([
152
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
153
+ Promise.resolve().then(() => __importStar(require('typeorm'))),
154
+ Promise.resolve().then(() => __importStar(require('../chat-message/chat-message.js'))),
155
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-target.js'))),
156
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-apply.js'))),
157
+ Promise.resolve().then(() => __importStar(require('../chat-message/proposal-outcome.js')))
158
+ ]);
159
+ const carrying = await getRepository(ChatMessage).find({ where: { session: { id: sessionId }, proposals: Not(IsNull()) }, order: { createdAt: 'ASC' } });
160
+ const messages = carrying.map(message => ({ id: message.id, proposals: message.proposalsJson ?? [] }));
161
+ const work = workOfProposal(card);
162
+ const keys = messages.flatMap(message => message.proposals.filter((one) => one?.kind === 'entry' && one?.key && workOfProposal(one) === work).map((one) => one.key));
163
+ const open = [];
164
+ for (const key of keys) {
165
+ if (findEntryProposal(messages, key).superseded)
166
+ continue;
167
+ const lines = await getRepository(ChatMessage).find({ select: ['content'], where: { session: { id: sessionId }, role: 'system', content: Like(`${PROPOSAL_OUTCOME_PREFIX}${key}:%`) } });
168
+ if (!entryProposalAnswered(key, lines.map(line => line.content)))
169
+ open.push(key);
170
+ }
171
+ return open;
172
+ }
173
+ /** A page of the person's domain as a full address - what the agent hands its user. */
174
+ async function linkOf(origin, state, path) {
175
+ try {
176
+ const { getContextPath } = await Promise.resolve().then(() => __importStar(require('@things-factory/shell')));
177
+ return `${String(origin ?? '').replace(/\/+$/, '')}/${getContextPath(state.domain)}${path}`;
178
+ }
179
+ catch {
180
+ return path;
181
+ }
182
+ }
183
+ /** The person told that something waits for them - kept in their inbox, live and by push (notification's `sendNotice`). */
184
+ async function tellPerson(state, t, client, address) {
185
+ if (typeof state?.sendNotice !== 'function')
186
+ return;
187
+ const title = say(t, 'outside-agent-notice-title', 'A proposal waits for you');
188
+ const body = say(t, 'outside-agent-notice-body', '{client} handed in a proposal. Open it and press the card to enter it.', { client });
189
+ try {
190
+ await state.sendNotice({
191
+ type: 'assistant-outside-proposal',
192
+ receivers: [{ id: state.user.id }],
193
+ words: () => ({ subject: title, summary: body, body, action: title, note: '' }),
194
+ address,
195
+ label: 'assistant-outside-proposal'
196
+ });
197
+ }
198
+ catch {
199
+ /* the card is kept; the notice only tells of it */
200
+ }
201
+ }
202
+ exports.OUTSIDE_CONVERSATION = { conversationOf: outsideConversationOf, keep: keepOutsideProposal };
203
+ //# sourceMappingURL=mcp-conversation.js.map
@@ -0,0 +1,19 @@
1
+ /** A card taken from the requesting connection's conversation, with where it came from and the doors of its answer. */
2
+ export interface HeldProposal {
3
+ card: Record<string, any>;
4
+ /** The doors of the message that carries it (ADR-0073) - a reader who cannot pass them is not shown its values. */
5
+ doors: string[];
6
+ sessionId: string;
7
+ }
8
+ /**
9
+ * The entry card `key` that the request's own outside connection handed in - from its conversation for the connection,
10
+ * still the newest of its work and not pressed. Nothing for a request from a screen, another connection's key, or a
11
+ * card no longer good.
12
+ */
13
+ export declare function outsideProposalOf(state: any, key: string): Promise<HeldProposal | undefined>;
14
+ /**
15
+ * Presses a held card as the request's person - the conversation's own apply, everything asked again - and writes what
16
+ * it did into the conversation it came from. Not inside a transaction: each row is its own call of the application's
17
+ * door, as a press from the dock.
18
+ */
19
+ export declare function pressHeldProposal(held: HeldProposal, context: any): Promise<import("../data-entry/entry-apply.js").EntryApplyOutcome>;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.outsideProposalOf = outsideProposalOf;
37
+ exports.pressHeldProposal = pressHeldProposal;
38
+ /*
39
+ * A proposal an outside agent handed in, pressed by someone else (ADR-0237 amendment 1, decision 15).
40
+ *
41
+ * An agent connected for an account that is no person (an application's own AI account) hands in a 수정안 - the card
42
+ * waits in that account's conversation for the connection, where no person opens it. A module that asks a person to
43
+ * approve the agent's work (inquiry's request for the handlers' decision) takes the card from there by its key and holds
44
+ * it; the person it asks presses it. Pressing is the conversation's own: the stored rows, every door, a newer card of the
45
+ * same work, whether it was answered, the target's checks - all asked again, as the one who presses. What it did is
46
+ * written back into the agent's conversation, as the dock writes a press, so the agent reads it and the card is not
47
+ * entered twice.
48
+ *
49
+ * Nothing here knows a module or an application; the entities load when a card is read or pressed.
50
+ */
51
+ const env_1 = require("@things-factory/env");
52
+ async function proposalMessagesOf(sessionId) {
53
+ const [{ getRepository }, { Not, IsNull }, { ChatMessage }] = await Promise.all([Promise.resolve().then(() => __importStar(require('@things-factory/shell'))), Promise.resolve().then(() => __importStar(require('typeorm'))), Promise.resolve().then(() => __importStar(require('../chat-message/chat-message.js')))]);
54
+ const carrying = await getRepository(ChatMessage).find({ where: { session: { id: sessionId }, proposals: Not(IsNull()) }, order: { createdAt: 'ASC' } });
55
+ return carrying.map(message => ({ id: message.id, proposals: message.proposalsJson ?? [], doors: (message.doors ?? []) }));
56
+ }
57
+ async function outcomeLinesOf(sessionId, key) {
58
+ const [{ getRepository }, { Like }, { ChatMessage }, { PROPOSAL_OUTCOME_PREFIX }] = await Promise.all([
59
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
60
+ Promise.resolve().then(() => __importStar(require('typeorm'))),
61
+ Promise.resolve().then(() => __importStar(require('../chat-message/chat-message.js'))),
62
+ Promise.resolve().then(() => __importStar(require('../chat-message/proposal-outcome.js')))
63
+ ]);
64
+ const lines = await getRepository(ChatMessage).find({ select: ['content'], where: { session: { id: sessionId }, role: 'system', content: Like(`${PROPOSAL_OUTCOME_PREFIX}${key}:%`) } });
65
+ return lines.map(line => line.content);
66
+ }
67
+ /**
68
+ * The entry card `key` that the request's own outside connection handed in - from its conversation for the connection,
69
+ * still the newest of its work and not pressed. Nothing for a request from a screen, another connection's key, or a
70
+ * card no longer good.
71
+ */
72
+ async function outsideProposalOf(state, key) {
73
+ const connectionId = state?.oauth?.grantId;
74
+ const domainId = state?.domain?.id;
75
+ const wanted = String(key ?? '').trim();
76
+ if (!connectionId || !domainId || !wanted)
77
+ return undefined;
78
+ const [{ getRepository }, { ChatSession }, { findEntryProposal, entryProposalAnswered }] = await Promise.all([
79
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
80
+ Promise.resolve().then(() => __importStar(require('../chat-session/chat-session.js'))),
81
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-apply.js')))
82
+ ]);
83
+ const session = await getRepository(ChatSession).findOne({ where: { domain: { id: domainId }, connectionId } });
84
+ if (!session)
85
+ return undefined;
86
+ const messages = await proposalMessagesOf(session.id);
87
+ const { proposal, superseded } = findEntryProposal(messages, wanted);
88
+ if (!proposal || proposal.kind !== 'entry' || superseded)
89
+ return undefined;
90
+ if (entryProposalAnswered(wanted, await outcomeLinesOf(session.id, wanted)))
91
+ return undefined;
92
+ const carrier = messages.find(message => message.proposals.some((one) => one?.key === wanted));
93
+ return { card: proposal, doors: carrier?.doors ?? [], sessionId: session.id };
94
+ }
95
+ /**
96
+ * Presses a held card as the request's person - the conversation's own apply, everything asked again - and writes what
97
+ * it did into the conversation it came from. Not inside a transaction: each row is its own call of the application's
98
+ * door, as a press from the dock.
99
+ */
100
+ async function pressHeldProposal(held, context) {
101
+ const [{ getRepository }, { ChatMessage }, { applyEntryProposal, entryProposalAnswered }, { runAsCaller }, { entryRefusalFor }, { toolAccessFor }, { formatProposalOutcomeLine }] = await Promise.all([
102
+ Promise.resolve().then(() => __importStar(require('@things-factory/shell'))),
103
+ Promise.resolve().then(() => __importStar(require('../chat-message/chat-message.js'))),
104
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-apply.js'))),
105
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-tools.js'))),
106
+ Promise.resolve().then(() => __importStar(require('../data-entry/entry-refusal.js'))),
107
+ Promise.resolve().then(() => __importStar(require('../tool-access.js'))),
108
+ Promise.resolve().then(() => __importStar(require('../chat-message/proposal-outcome.js')))
109
+ ]);
110
+ const key = String(held.card?.key ?? '');
111
+ const passes = toolAccessFor(context);
112
+ const outcome = await applyEntryProposal(key, {
113
+ messages: await proposalMessagesOf(held.sessionId),
114
+ answered: entryProposalAnswered(key, await outcomeLinesOf(held.sessionId, key)),
115
+ passesDoor: door => passes(door),
116
+ refusalFor: entryRefusalFor(context),
117
+ state: context.state,
118
+ execute: runAsCaller(context),
119
+ report: (message, error) => env_1.logger.error(message, error),
120
+ sessionId: held.sessionId
121
+ });
122
+ /* Written back only when something was tried - a refusal before any row leaves the card as it was, to be pressed again. */
123
+ if (outcome.applied || outcome.missed) {
124
+ await getRepository(ChatMessage).save({
125
+ session: { id: held.sessionId },
126
+ role: 'system',
127
+ content: formatProposalOutcomeLine(key, { verdict: outcome.verdict, ...(outcome.errorCode ? { errorCode: outcome.errorCode } : {}), applied: outcome.applied, missed: outcome.missed }),
128
+ creator: context.state.user,
129
+ updater: context.state.user
130
+ });
131
+ }
132
+ return outcome;
133
+ }
134
+ //# sourceMappingURL=mcp-held-proposal.js.map
@@ -0,0 +1,7 @@
1
+ import { MCP_PATH } from './mcp-server.js';
2
+ export { MCP_PATH };
3
+ /**
4
+ * The shell calls each module's at boot, before the body parser - a body that is not JSON is answered in JSON-RPC.
5
+ * Once per app: board-ai re-exports this package, so the shell finds it twice.
6
+ */
7
+ export declare function initMiddlewares(app: any): void;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MCP_PATH = void 0;
4
+ exports.initMiddlewares = initMiddlewares;
5
+ /*
6
+ * `/mcp` mounted (ADR-0237 decisions 5 · 9) - every application has the assistant, so every application has this door
7
+ * by depending on it. This module declares the resource and mounts the endpoint; the authorization server
8
+ * (`auth-base`) issues tokens for it, publishes its metadata, checks each token and sets the person and the domain.
9
+ */
10
+ const auth_base_1 = require("@things-factory/auth-base");
11
+ const ai_client_base_1 = require("@things-factory/ai-client-base");
12
+ const tool_access_js_1 = require("../tool-access.js");
13
+ const run_as_js_1 = require("../unattended-run/run-as.js");
14
+ const mcp_audit_js_1 = require("./mcp-audit.js");
15
+ const mcp_conversation_js_1 = require("./mcp-conversation.js");
16
+ const mcp_server_js_1 = require("./mcp-server.js");
17
+ Object.defineProperty(exports, "MCP_PATH", { enumerable: true, get: function () { return mcp_server_js_1.MCP_PATH; } });
18
+ const mcp_settings_js_1 = require("./mcp-settings.js");
19
+ /* `nameKey`: the consent page and 「연결된 클라이언트」 show it in the person's language; `name` is what the metadata publishes. */
20
+ (0, auth_base_1.registerProtectedResource)({ path: mcp_server_js_1.MCP_PATH, name: 'AI assistant tools', nameKey: 'ai-assistant.text.mcp-resource-name', scopes: [], enabledFor: mcp_settings_js_1.outsideAgentsOn });
21
+ /* Every call from outside, in the framework audit - the calls that ran here, the refused ones from the endpoint. */
22
+ (0, ai_client_base_1.registerToolCallRecorder)(mcp_audit_js_1.auditMcpCall);
23
+ const endpoint = (0, mcp_server_js_1.mcpEndpoint)({
24
+ access: state => (0, tool_access_js_1.toolAccessFor)({ state }),
25
+ /* The door a person passes to ask the assistant - the same one an unattended run's owner is judged by. */
26
+ mayAsk: state => (0, auth_base_1.checkPermission)(run_as_js_1.ASK_ASSISTANT_GATE, state.user, state.domain, state.unsafeIP, state.prohibitedPrivileges),
27
+ refused: mcp_audit_js_1.auditMcpRefusal,
28
+ /* An entry draft from outside waits in the person's conversation for the connection (ADR-0237 decision 11). */
29
+ outside: mcp_conversation_js_1.OUTSIDE_CONVERSATION,
30
+ origin: auth_base_1.issuerOf
31
+ });
32
+ /*
33
+ * A global public route: the session middleware does not run there, and the token check is the resource's own. What
34
+ * needs no token is asked first - another origin, a protocol version this does not speak.
35
+ */
36
+ process.on('bootstrap-module-global-public-route', (_app, globalPublicRouter) => {
37
+ globalPublicRouter.all(mcp_server_js_1.MCP_PATH, (0, mcp_server_js_1.mcpRequestGuard)(auth_base_1.issuerOf), (0, auth_base_1.protectedResourceMiddleware)(mcp_server_js_1.MCP_PATH), endpoint);
38
+ });
39
+ const installed = new WeakSet();
40
+ /**
41
+ * The shell calls each module's at boot, before the body parser - a body that is not JSON is answered in JSON-RPC.
42
+ * Once per app: board-ai re-exports this package, so the shell finds it twice.
43
+ */
44
+ function initMiddlewares(app) {
45
+ if (installed.has(app))
46
+ return;
47
+ installed.add(app);
48
+ app.use(mcp_server_js_1.mcpParseErrors);
49
+ }
50
+ //# sourceMappingURL=mcp-route.js.map