@things-factory/ai-assistant 10.1.280 → 10.1.282
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-client/settings/ai-agent-setting-let.d.ts +2 -0
- package/dist-client/settings/ai-agent-setting-let.js +25 -6
- package/dist-client/utils/agent-choice.js +1 -1
- package/dist-server/service/ai-agent-resolver.d.ts +1 -0
- package/dist-server/service/ai-agent-resolver.js +13 -1
- package/dist-server/service/assistant-chat-resolver.js +342 -327
- package/dist-server/service/assistant-turn/mode-turn.d.ts +39 -0
- package/dist-server/service/assistant-turn/mode-turn.js +47 -0
- package/dist-server/service/testing/mode-conformance.js +5 -6
- package/dist-server/service/unattended-run/run-unattended.js +12 -13
- package/package.json +10 -10
- package/translations/en.json +3 -0
- package/translations/es.json +3 -0
- package/translations/ja.json +3 -0
- package/translations/ko.json +3 -0
- package/translations/ms.json +3 -0
- package/translations/zh.json +3 -0
|
@@ -64,7 +64,15 @@ const SAVE_MUTATION = gql `
|
|
|
64
64
|
saveAiAgents(input: $input)
|
|
65
65
|
}
|
|
66
66
|
`;
|
|
67
|
+
const PROVIDERS_QUERY = gql `
|
|
68
|
+
query AiAgentProviders {
|
|
69
|
+
aiAgentProviders
|
|
70
|
+
}
|
|
71
|
+
`;
|
|
72
|
+
/* What the server offers; claude-code only on a development server with the Claude Code CLI logged in. */
|
|
67
73
|
const PROVIDERS = ['openai', 'anthropic', 'gemini'];
|
|
74
|
+
/** A provider that answers on what the server's machine is logged in to: no key. */
|
|
75
|
+
const keyless = (provider) => provider === 'claude-code';
|
|
68
76
|
/**
|
|
69
77
|
* A domain's AI agents - the card in Settings › {domain} settings (design/ai/agent-settings.md §7-1, §7-2).
|
|
70
78
|
*
|
|
@@ -79,6 +87,7 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
79
87
|
/* The agents of this domain and the domains above (ADR-0190). */
|
|
80
88
|
this.agents = new QueryController(this, SETTINGS_QUERY, { fetchPolicy: 'network-only' });
|
|
81
89
|
this.modelList = new QueryController(this, MODELS_QUERY, { variables: () => this.modelsAsk, fetchPolicy: 'network-only' });
|
|
90
|
+
this.offered = new QueryController(this, PROVIDERS_QUERY, { fetchPolicy: 'network-only' });
|
|
82
91
|
/* A refusal is drawn beside the editor or in a prompt here, so the link does not report it again. */
|
|
83
92
|
this.saver = new MutationController(this, SAVE_MUTATION, { refetch: () => [this.agents], showsError: true });
|
|
84
93
|
}
|
|
@@ -264,6 +273,9 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
264
273
|
}
|
|
265
274
|
`
|
|
266
275
|
]; }
|
|
276
|
+
get providers() {
|
|
277
|
+
return this.offered.data?.aiAgentProviders ?? PROVIDERS;
|
|
278
|
+
}
|
|
267
279
|
get settings() {
|
|
268
280
|
return this.agents.data?.aiAgentSettings;
|
|
269
281
|
}
|
|
@@ -375,6 +387,8 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
375
387
|
`;
|
|
376
388
|
}
|
|
377
389
|
renderKey(agent) {
|
|
390
|
+
if (keyless(agent.provider))
|
|
391
|
+
return html `<span class="key">${t('key-none-needed', 'No key - this computer\'s login')}</span>`;
|
|
378
392
|
switch (agent.keyState) {
|
|
379
393
|
case 'own':
|
|
380
394
|
return html `<span class="key">${agent.keyHint}</span>`;
|
|
@@ -440,7 +454,7 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
440
454
|
const draft = this.draft;
|
|
441
455
|
const stored = this.settings.agents.find(one => one.id === draft.id);
|
|
442
456
|
const hasStoredKey = !!stored && stored.keyState === 'own' && draft.provider === stored.provider;
|
|
443
|
-
const modelLocked = !draft.apiKey.trim() && !hasStoredKey;
|
|
457
|
+
const modelLocked = !keyless(draft.provider) && !draft.apiKey.trim() && !hasStoredKey;
|
|
444
458
|
const offered = this.models.state === 'ready' ? this.models.models : [];
|
|
445
459
|
const modelGone = this.models.state === 'ready' && !!draft.model && !offered.includes(draft.model);
|
|
446
460
|
const canSave = !!draft.name.trim() && !!draft.model && !modelLocked && !modelGone && this.models.state === 'ready' && !this.saving;
|
|
@@ -453,10 +467,15 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
453
467
|
<label>
|
|
454
468
|
${t('provider', 'Provider')}
|
|
455
469
|
<select @change=${(e) => this.onProvider(e.target.value)}>
|
|
456
|
-
${
|
|
470
|
+
${[...new Set([...this.providers, draft.provider].filter(Boolean))].map(one => html `<option value=${one} ?selected=${one === draft.provider}>${providerLabel(one)}</option>`)}
|
|
457
471
|
</select>
|
|
458
472
|
</label>
|
|
459
|
-
|
|
473
|
+
${keyless(draft.provider)
|
|
474
|
+
? html `<label>
|
|
475
|
+
${t('api-key', 'API key')}
|
|
476
|
+
<span class="hint">${t('key-none-needed-hint', 'None: it answers on the Claude Code CLI logged in on the computer this server runs on. For development only.')}</span>
|
|
477
|
+
</label>`
|
|
478
|
+
: html `<label>
|
|
460
479
|
${t('api-key', 'API key')}
|
|
461
480
|
<input
|
|
462
481
|
type="password"
|
|
@@ -465,7 +484,7 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
465
484
|
.value=${draft.apiKey}
|
|
466
485
|
@input=${(e) => this.patch({ apiKey: e.target.value })}
|
|
467
486
|
@change=${() => this.loadModels()} />
|
|
468
|
-
</label
|
|
487
|
+
</label>`}
|
|
469
488
|
<label>
|
|
470
489
|
${t('model', 'Model')}
|
|
471
490
|
<span class="with-action">
|
|
@@ -540,13 +559,13 @@ let AiAgentSettingLet = class AiAgentSettingLet extends localize(i18next)(LitEle
|
|
|
540
559
|
return;
|
|
541
560
|
const stored = this.settings?.agents.find(one => one.id === draft.id && !one.inherited);
|
|
542
561
|
const useStored = !draft.apiKey.trim() && stored?.keyState === 'own' && stored.provider === draft.provider;
|
|
543
|
-
if (!draft.apiKey.trim() && !useStored) {
|
|
562
|
+
if (!keyless(draft.provider) && !draft.apiKey.trim() && !useStored) {
|
|
544
563
|
this.modelsAsk = undefined;
|
|
545
564
|
return;
|
|
546
565
|
}
|
|
547
566
|
const ask = {
|
|
548
567
|
provider: draft.provider,
|
|
549
|
-
...(draft.apiKey.trim() ? { apiKey: draft.apiKey.trim() } : { agentId: draft.id }),
|
|
568
|
+
...(keyless(draft.provider) ? {} : draft.apiKey.trim() ? { apiKey: draft.apiKey.trim() } : { agentId: draft.id }),
|
|
550
569
|
...(draft.baseURL.trim() && { baseURL: draft.baseURL.trim() }),
|
|
551
570
|
...(draft.organization.trim() && { organization: draft.organization.trim() })
|
|
552
571
|
};
|
|
@@ -27,7 +27,7 @@ export function rememberAgent(contextPath, agentId) {
|
|
|
27
27
|
/* A browser that blocks storage still picks - it just asks again next time. */
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
const PROVIDER_LABEL = { openai: 'OpenAI', anthropic: 'Claude', gemini: 'Gemini' };
|
|
30
|
+
const PROVIDER_LABEL = { openai: 'OpenAI', anthropic: 'Claude', gemini: 'Gemini', 'claude-code': 'Claude Code (this computer)' };
|
|
31
31
|
/** `Claude · claude-sonnet-4-6` - what the picker shows beside a name. */
|
|
32
32
|
export function agentDetail(choice) {
|
|
33
33
|
return `${PROVIDER_LABEL[choice.provider] ?? choice.provider} · ${choice.model}`;
|
|
@@ -116,6 +116,7 @@ declare class AiModelPriceInput {
|
|
|
116
116
|
export declare class AiAgentResolver {
|
|
117
117
|
aiAgentSettings(context: ResolverContext): Promise<AiAgentSettings>;
|
|
118
118
|
aiAgentChoices(context: ResolverContext): Promise<AiAgentChoice[]>;
|
|
119
|
+
aiAgentProviders(): Promise<string[]>;
|
|
119
120
|
aiProviderModels(provider: string, apiKey: string, agentId: string, baseURL: string, organization: string, context: ResolverContext): Promise<string[]>;
|
|
120
121
|
saveAiAgents(input: AiAgentsInput, context: ResolverContext): Promise<boolean>;
|
|
121
122
|
aiUsageOverview(from: Date, to: Date, bucket: string, context: ResolverContext): Promise<AiUsageOverview>;
|
|
@@ -37,7 +37,7 @@ tslib_1.__decorate([
|
|
|
37
37
|
tslib_1.__metadata("design:type", String)
|
|
38
38
|
], AiAgentView.prototype, "name", void 0);
|
|
39
39
|
tslib_1.__decorate([
|
|
40
|
-
(0, type_graphql_1.Field)({ description: 'openai, anthropic or
|
|
40
|
+
(0, type_graphql_1.Field)({ description: 'openai, anthropic, gemini, or claude-code (a development server only).' }),
|
|
41
41
|
tslib_1.__metadata("design:type", String)
|
|
42
42
|
], AiAgentView.prototype, "provider", void 0);
|
|
43
43
|
tslib_1.__decorate([
|
|
@@ -456,6 +456,9 @@ let AiAgentResolver = class AiAgentResolver {
|
|
|
456
456
|
isDefault: one.spec.id === directory.defaultAgentId
|
|
457
457
|
}));
|
|
458
458
|
}
|
|
459
|
+
async aiAgentProviders() {
|
|
460
|
+
return (0, ai_client_base_1.aiProvidersOffered)();
|
|
461
|
+
}
|
|
459
462
|
async aiProviderModels(provider, apiKey, agentId, baseURL, organization, context) {
|
|
460
463
|
let key = apiKey?.trim();
|
|
461
464
|
if (!key && agentId) {
|
|
@@ -541,6 +544,15 @@ tslib_1.__decorate([
|
|
|
541
544
|
tslib_1.__metadata("design:paramtypes", [Object]),
|
|
542
545
|
tslib_1.__metadata("design:returntype", Promise)
|
|
543
546
|
], AiAgentResolver.prototype, "aiAgentChoices", null);
|
|
547
|
+
tslib_1.__decorate([
|
|
548
|
+
(0, type_graphql_1.Query)(() => [String], {
|
|
549
|
+
description: 'The providers this server offers an agent: openai, anthropic, gemini, and claude-code where the server is a development one with the Claude Code CLI logged in (it needs no key).'
|
|
550
|
+
}),
|
|
551
|
+
(0, type_graphql_1.Directive)('@privilege(category: "setting", privilege: "query", domainOwnerGranted: true)'),
|
|
552
|
+
tslib_1.__metadata("design:type", Function),
|
|
553
|
+
tslib_1.__metadata("design:paramtypes", []),
|
|
554
|
+
tslib_1.__metadata("design:returntype", Promise)
|
|
555
|
+
], AiAgentResolver.prototype, "aiAgentProviders", null);
|
|
544
556
|
tslib_1.__decorate([
|
|
545
557
|
(0, type_graphql_1.Query)(() => [String], {
|
|
546
558
|
description: 'The conversation models a provider offers to a key - a typed key, or the stored key of one of this domain\'s agents. A model is only ever picked from this list.'
|
|
@@ -39,7 +39,7 @@ const llm_history_js_1 = require("./chat-message/llm-history.js");
|
|
|
39
39
|
const proposal_outcome_js_1 = require("./chat-message/proposal-outcome.js");
|
|
40
40
|
const history_summary_js_1 = require("./chat-message/history-summary.js");
|
|
41
41
|
const fold_session_history_js_1 = require("./chat-message/fold-session-history.js");
|
|
42
|
-
const
|
|
42
|
+
const mode_turn_js_1 = require("./assistant-turn/mode-turn.js");
|
|
43
43
|
const chat_message_publish_js_1 = require("./chat-message/chat-message-publish.js");
|
|
44
44
|
const session_activity_publish_js_1 = require("./chat-session/session-activity-publish.js");
|
|
45
45
|
const session_inbox_js_1 = require("./chat-session/session-inbox.js");
|
|
@@ -236,265 +236,33 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
236
236
|
* history is safer than a lost one.
|
|
237
237
|
*/
|
|
238
238
|
async assistantChat(input, context) {
|
|
239
|
-
const { domain, user } = context.state;
|
|
240
239
|
/*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
240
|
+
* One turn, in the order it happens (2026-11-14: the steps were one 415-line method). Each step is the code it was;
|
|
241
|
+
* the turn itself -- what the mode's settings mean for the model call -- is runModeTurn, shared with an unattended
|
|
242
|
+
* run and the conformance harness.
|
|
243
243
|
*/
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
client = await (0, ai_client_base_1.aiClientFor)({
|
|
247
|
-
domain,
|
|
248
|
-
user,
|
|
249
|
-
agentId: input.agentId,
|
|
250
|
-
modeKind: input.mode.kind,
|
|
251
|
-
sessionId: input.sessionId
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
catch (error) {
|
|
255
|
-
(0, shell_1.rethrowSpoken)(error, context);
|
|
256
|
-
}
|
|
257
|
-
/* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */
|
|
258
|
-
context.state.aiAgentId = client.agent.id;
|
|
244
|
+
const client = await agentOf(input, context);
|
|
245
|
+
const t = (0, request_translator_js_1.requestTranslator)(context);
|
|
259
246
|
/*
|
|
260
247
|
* Read the declaration before anything is stored. A kind this server does not have is a
|
|
261
248
|
* mismatched deployment, and the person should see that instead of a conversation with no
|
|
262
249
|
* persona and no tools.
|
|
263
250
|
*/
|
|
264
|
-
const
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
* built on this conversation's history, so an outsider's question would read it back to them.
|
|
276
|
-
*/
|
|
277
|
-
await (0, session_write_gate_js_1.assertMayWriteSession)({
|
|
278
|
-
session: found,
|
|
279
|
-
userId: user?.id,
|
|
280
|
-
isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, found.id, user?.id),
|
|
281
|
-
t: (key, options) => t(key, options)
|
|
282
|
-
});
|
|
283
|
-
if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {
|
|
284
|
-
throw new Error(context.t('ai-assistant.text.other-figure-history', {
|
|
285
|
-
defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'
|
|
286
|
-
}));
|
|
287
|
-
}
|
|
288
|
-
if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {
|
|
289
|
-
throw new Error(context.t('ai-assistant.text.application-vs-model-history', {
|
|
290
|
-
defaultValue: 'this conversation is about the application, not about a model. open the one you want.'
|
|
291
|
-
}));
|
|
292
|
-
}
|
|
293
|
-
/*
|
|
294
|
-
* 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이
|
|
295
|
-
* 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.
|
|
296
|
-
*/
|
|
297
|
-
const verdict = (0, session_kind_js_1.judgeSessionKind)(found.kind, input.mode.kind);
|
|
298
|
-
if (verdict.action === 'refuse') {
|
|
299
|
-
throw new Error(t('ai-assistant.text.session-kind-mismatch', {
|
|
300
|
-
...verdict.params,
|
|
301
|
-
defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'
|
|
302
|
-
}));
|
|
303
|
-
}
|
|
304
|
-
if (verdict.action === 'stamp') {
|
|
305
|
-
/* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */
|
|
306
|
-
await sessionRepo.update(found.id, { kind: verdict.kind });
|
|
307
|
-
found.kind = verdict.kind;
|
|
308
|
-
}
|
|
309
|
-
session = found;
|
|
310
|
-
}
|
|
311
|
-
(0, station_session_guard_js_1.assertStationSession)(session, input.hostContext, t);
|
|
312
|
-
/*
|
|
313
|
-
* 열린 대상 — 서버가 저장한 앵커에서 턴마다 한 줄(design/ai/screen-pattern.md §2-1). 화면이 보낸 hostContext 는
|
|
314
|
-
* 쓰지 않는다. 대상이 바뀌면 다음 턴의 줄도 바뀌므로 옛 대상이 대화에 남지 않는다.
|
|
315
|
-
*/
|
|
316
|
-
const subjectLine = session
|
|
317
|
-
? await (0, ai_client_base_1.openSubjectLine)({
|
|
318
|
-
anchorType: session.anchorType,
|
|
319
|
-
anchorId: session.anchorId,
|
|
320
|
-
domain,
|
|
321
|
-
state: context.state
|
|
322
|
-
})
|
|
323
|
-
: undefined;
|
|
324
|
-
/* What the person has in front of them besides the subject - the screen's unread notices (ADR-0199 amendment 1). */
|
|
325
|
-
const screenLines = await (0, turn_lines_js_1.turnLinesOf)({ page: input.page, state: context.state });
|
|
326
|
-
const systemPrompt = (0, mode_categories_js_1.turnSystemPrompt)(settings.systemPrompt, { subjectLine: [subjectLine, ...screenLines].filter(Boolean).join('\n\n') || undefined, page: input.page });
|
|
327
|
-
const lastUserMessage = input.messages[input.messages.length - 1];
|
|
328
|
-
let userMessageId;
|
|
329
|
-
/*
|
|
330
|
-
* Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by
|
|
331
|
-
* attachToConversation; one that is not this conversation's is refused, never read. The policy is the
|
|
332
|
-
* mode's - checked again here, since the door is the authority, not the screen.
|
|
333
|
-
*/
|
|
334
|
-
const attachmentRows = [];
|
|
335
|
-
if (input.attachmentIds?.length) {
|
|
336
|
-
if (!session)
|
|
337
|
-
throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }));
|
|
338
|
-
for (const id of input.attachmentIds) {
|
|
339
|
-
const row = await (0, session_attachments_js_1.findChatAttachment)(domain.id, session.id, id);
|
|
340
|
-
if (!row)
|
|
341
|
-
throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }));
|
|
342
|
-
attachmentRows.push(row);
|
|
343
|
-
}
|
|
344
|
-
const refusal = (0, attachment_policy_js_1.refuseAttachments)((0, registry_js_1.getAssistantMode)(input.mode.kind)?.attachments, attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) })));
|
|
345
|
-
if (refusal)
|
|
346
|
-
throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...refusal, defaultValue: refusal.code }));
|
|
347
|
-
}
|
|
348
|
-
if (session && lastUserMessage?.role === 'user') {
|
|
349
|
-
const previousLast = await messageRepo.findOne({
|
|
350
|
-
where: { session: { id: session.id } },
|
|
351
|
-
order: { createdAt: 'DESC' }
|
|
352
|
-
});
|
|
353
|
-
const saved = await messageRepo.save({
|
|
354
|
-
session: { id: session.id },
|
|
355
|
-
role: 'user',
|
|
356
|
-
content: lastUserMessage.content,
|
|
357
|
-
/*
|
|
358
|
-
* This door is the one people call to ask the assistant, so a turn stored here was for the
|
|
359
|
-
* assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never
|
|
360
|
-
* from the request — two sources for one fact can disagree.
|
|
361
|
-
*/
|
|
362
|
-
addressee: 'assistant',
|
|
363
|
-
attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(session_attachments_js_1.describeAttachment)) : undefined,
|
|
364
|
-
creator: user,
|
|
365
|
-
updater: user,
|
|
366
|
-
parentMessage: previousLast ? { id: previousLast.id } : undefined
|
|
367
|
-
});
|
|
368
|
-
userMessageId = saved.id;
|
|
369
|
-
/*
|
|
370
|
-
* Session activity is denormalised for the list: most-recent ordering and another
|
|
371
|
-
* participant's unread badge read it. Best effort — a conversation must not fail because a
|
|
372
|
-
* list sorts one position late.
|
|
373
|
-
*/
|
|
374
|
-
try {
|
|
375
|
-
const patch = (0, session_inbox_js_1.activityPatch)(lastUserMessage.content);
|
|
376
|
-
if (!session.name)
|
|
377
|
-
patch.name = (0, session_inbox_js_1.autoSessionName)(lastUserMessage.content);
|
|
378
|
-
await sessionRepo.update(session.id, patch);
|
|
379
|
-
}
|
|
380
|
-
catch {
|
|
381
|
-
/* noop */
|
|
382
|
-
}
|
|
383
|
-
/*
|
|
384
|
-
* 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을
|
|
385
|
-
* 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다. 공개 방에서 말한 사람도
|
|
386
|
-
* 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.
|
|
387
|
-
*/
|
|
388
|
-
const invite = await (0, mention_invite_js_1.seatTurn)({
|
|
389
|
-
content: lastUserMessage.content,
|
|
390
|
-
sessionId: session.id,
|
|
391
|
-
domainId: domain.id,
|
|
392
|
-
inviter: user,
|
|
393
|
-
participants: (0, shell_1.getRepository)(chat_session_participant_js_1.ChatSessionParticipant),
|
|
394
|
-
visibility: session.visibility
|
|
395
|
-
});
|
|
396
|
-
/* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */
|
|
397
|
-
await (0, invite_notification_js_1.sendInviteNotification)(context.state?.sendNotice, invite.invited, user, session?.name, undefined, (0, request_translator_js_1.requestTranslator)(context));
|
|
398
|
-
(0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: saved });
|
|
399
|
-
(0, session_activity_publish_js_1.publishSessionActivity)({
|
|
400
|
-
domainId: domain.id,
|
|
401
|
-
sessionId: session.id,
|
|
402
|
-
kind: 'message',
|
|
403
|
-
anchorType: session.anchorType,
|
|
404
|
-
anchorId: session.anchorId,
|
|
405
|
-
preview: lastUserMessage.content,
|
|
406
|
-
actorId: user?.id
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
/*
|
|
410
|
-
* 이번 턴에 상한 밖으로 밀려난 것이 있는가 — 화면이 「대화가 길어졌다」를 알릴 근거다.
|
|
411
|
-
*
|
|
412
|
-
* 이 문은 그 사실을 내지 않았다. 대화창에는 그 안내를 그리는 자리가 있고(`historyFolded`), 보드
|
|
413
|
-
* 문만 그 값을 채웠다. 그래서 앱의 대화는 앞부분이 잘려 나가도 **사람에게는 아무 말도 하지 않았다** —
|
|
414
|
-
* 모델에게는 「N 개 생략」을 적어 보내면서.
|
|
415
|
-
*/
|
|
416
|
-
const readRows = session
|
|
417
|
-
? await messageRepo.find({
|
|
418
|
-
where: { session: { id: session.id } },
|
|
419
|
-
order: { createdAt: 'ASC' },
|
|
420
|
-
relations: ['creator']
|
|
421
|
-
})
|
|
422
|
-
: [];
|
|
423
|
-
/*
|
|
424
|
-
* 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도
|
|
425
|
-
* 안 지난 사람이 "아까 그 수 다시 말해 줘" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은
|
|
426
|
-
* 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런
|
|
427
|
-
* 말이 없었다고 답하고, 그것은 거짓말이다.
|
|
428
|
-
*/
|
|
429
|
-
const storedRows = await (0, reader_gate_js_1.readerGate)(context)(readRows);
|
|
430
|
-
const capped = (0, history_summary_js_1.splitByCap)(storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })), LLM_HISTORY_MAX_TURNS);
|
|
431
|
-
const historyFolded = capped.dropped.length > 0
|
|
432
|
-
? { omitted: capped.dropped.length, summarized: Boolean(session?.lastSummary) }
|
|
433
|
-
: undefined;
|
|
434
|
-
const conversation = session
|
|
435
|
-
? (0, llm_history_js_1.buildLlmHistory)(
|
|
436
|
-
/*
|
|
437
|
-
* The model reads who spoke and who they spoke to. The entity carries the speaker as a
|
|
438
|
-
* relation and the addressee as a column; the history wants them as plain fields, and
|
|
439
|
-
* without this mapping every line arrived unattributed — a room of people read as one
|
|
440
|
-
* voice (ADR-0070 A15 decision ②).
|
|
441
|
-
*/
|
|
442
|
-
storedRows.map(message => ({
|
|
443
|
-
id: message.id,
|
|
444
|
-
role: message.role,
|
|
445
|
-
/*
|
|
446
|
-
* A file sent in an earlier turn is not sent again - one line names it, and the model opens it
|
|
447
|
-
* with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
|
|
448
|
-
*/
|
|
449
|
-
content: [
|
|
450
|
-
message.content,
|
|
451
|
-
...(message.id !== userMessageId && Array.isArray(message.attachmentsJson) ? message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine) : []),
|
|
452
|
-
/* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */
|
|
453
|
-
...(message.role === 'assistant' ? (0, proposal_outcome_js_1.offeredCardLines)(message.proposals) : [])
|
|
454
|
-
].join('\n'),
|
|
455
|
-
senderId: message.creator?.id,
|
|
456
|
-
senderName: message.creator?.name,
|
|
457
|
-
addressee: message.addressee
|
|
458
|
-
})), {
|
|
459
|
-
maxTurns: LLM_HISTORY_MAX_TURNS,
|
|
460
|
-
truncateAfterMessageId: input.truncateAfterMessageId,
|
|
461
|
-
/* The message just stored is this turn's question — truncation must never drop it. */
|
|
462
|
-
keepMessageIds: userMessageId ? [userMessageId] : undefined,
|
|
463
|
-
summary: session.lastSummary
|
|
464
|
-
? { text: session.lastSummary, upToMessageId: session.summaryUpToMessageId }
|
|
465
|
-
: undefined
|
|
466
|
-
})
|
|
467
|
-
: input.messages.map(message => ({ role: message.role, content: message.content }));
|
|
468
|
-
/*
|
|
469
|
-
* The files checked above, read once: the model reads them on this turn's question, and the tools get the same
|
|
470
|
-
* files as `context.attachments` (ADR-0061, 2026-10-16 decision 2) - figure's step generator draws from the
|
|
471
|
-
* picture the person sent. Never mixed into `hostContext`, which the client fills.
|
|
472
|
-
*/
|
|
473
|
-
const turnFiles = await (0, turn_attachments_js_1.readTurnAttachments)(attachmentRows, (0, attachment_policy_js_1.textCharsOf)((0, registry_js_1.getAssistantMode)(input.mode?.kind ?? '')?.attachments), session_attachments_js_1.attachmentForModel);
|
|
474
|
-
if (attachmentRows.length && conversation.length > 0) {
|
|
475
|
-
const last = conversation[conversation.length - 1];
|
|
476
|
-
if (last.role === 'user' && typeof last.content === 'string') {
|
|
477
|
-
last.content = [{ type: 'text', text: last.content }, ...turnFiles.parts];
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
else if (input.hostContext?.image?.data && conversation.length > 0) {
|
|
481
|
-
/* The screen-image path (figure's rendered view) - not a file of the conversation. */
|
|
482
|
-
const last = conversation[conversation.length - 1];
|
|
483
|
-
if (last.role === 'user' && typeof last.content === 'string') {
|
|
484
|
-
const raw = input.hostContext.image;
|
|
485
|
-
const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\/[a-zA-Z]+;base64,/, '') : raw.data;
|
|
486
|
-
const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData);
|
|
487
|
-
last.content = [
|
|
488
|
-
{ type: 'text', text: last.content },
|
|
489
|
-
{ type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }
|
|
490
|
-
];
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
const result = await (0, ai_client_base_1.registryAssistantChat)({
|
|
251
|
+
const turn = { input, context, t, settings: (0, resolve_js_1.resolveModeSettings)(input.mode, t) };
|
|
252
|
+
turn.session = await openSession(turn);
|
|
253
|
+
(0, station_session_guard_js_1.assertStationSession)(turn.session, input.hostContext, t);
|
|
254
|
+
const systemPrompt = await promptOf(turn);
|
|
255
|
+
const attachmentRows = await attachmentsOf(turn);
|
|
256
|
+
const userMessageId = await storeQuestion(turn, attachmentRows);
|
|
257
|
+
const { conversation, storedRows, historyFolded } = await historyOf(turn, userMessageId);
|
|
258
|
+
const turnFiles = await withTurnFiles(turn, conversation, attachmentRows);
|
|
259
|
+
const { session, settings } = turn;
|
|
260
|
+
const { domain } = context.state;
|
|
261
|
+
const result = await (0, mode_turn_js_1.runModeTurn)({
|
|
494
262
|
client,
|
|
495
263
|
messages: conversation,
|
|
496
|
-
systemPrompt,
|
|
497
|
-
|
|
264
|
+
settings: { ...settings, systemPrompt },
|
|
265
|
+
mode: input.mode,
|
|
498
266
|
/*
|
|
499
267
|
* What goes in front when the mode's tools do not fit in one call (ADR-0061 decision 9): the open page's, the
|
|
500
268
|
* anchored record's and the latest selection's, then what this conversation used. The anchor and the selection are
|
|
@@ -508,8 +276,6 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
508
276
|
}),
|
|
509
277
|
tools: (0, used_tools_js_1.usedToolNames)(storedRows, [ai_client_base_1.OPEN_TOOLS])
|
|
510
278
|
},
|
|
511
|
-
/* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */
|
|
512
|
-
mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },
|
|
513
279
|
/* And which stored conversation - the room a tool like the invite card acts on. The server's session, never the client's. */
|
|
514
280
|
...(session?.id ? { conversation: { id: session.id } } : {}),
|
|
515
281
|
toolAccess: (0, tool_access_js_1.toolAccessFor)(context),
|
|
@@ -517,83 +283,11 @@ let AssistantChatResolver = class AssistantChatResolver {
|
|
|
517
283
|
t,
|
|
518
284
|
hostContext: input.hostContext,
|
|
519
285
|
attachments: turnFiles.forTools,
|
|
520
|
-
|
|
521
|
-
* 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다
|
|
522
|
-
* (`ai-client-base/utils/grounding`). 이 문은 그 셋을 넘기지 않아, **사람이 방금 타이핑한
|
|
523
|
-
* 식별자**를 되받아 적은 답이 「근거 없음」으로 표시됐다. 그런 경고가 몇 번 나오면 사람이 경고
|
|
524
|
-
* 자체를 안 보게 된다.
|
|
525
|
-
*/
|
|
526
|
-
groundingSources: (0, grounding_sources_js_1.groundingSourcesFor)({
|
|
527
|
-
systemPrompt,
|
|
528
|
-
messages: conversation,
|
|
529
|
-
hostContext: input.hostContext
|
|
530
|
-
}),
|
|
531
|
-
state: context.state,
|
|
532
|
-
temperature: settings.temperature,
|
|
533
|
-
maxTokens: settings.maxTokens,
|
|
534
|
-
requireToolOnFirstTurn: settings.requireToolOnFirstTurn
|
|
286
|
+
state: context.state
|
|
535
287
|
});
|
|
536
|
-
/*
|
|
537
|
-
* 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면
|
|
538
|
-
* 가려진 답이 목록에는 그대로 뜬다.
|
|
539
|
-
*/
|
|
540
288
|
/* The reply ends with the next request when one is natural; the input offers it and the stored answer does not keep it (§4-1). */
|
|
541
289
|
const { reply, suggestion } = (0, screen_rules_js_1.splitNextRequest)(result.reply);
|
|
542
|
-
const
|
|
543
|
-
let assistantMessageId;
|
|
544
|
-
if (session) {
|
|
545
|
-
const stored = await messageRepo.save({
|
|
546
|
-
session: { id: session.id },
|
|
547
|
-
role: 'assistant',
|
|
548
|
-
content: reply,
|
|
549
|
-
/*
|
|
550
|
-
* 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이
|
|
551
|
-
* 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면
|
|
552
|
-
* 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.
|
|
553
|
-
*/
|
|
554
|
-
doors: answerDoors,
|
|
555
|
-
toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,
|
|
556
|
-
proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,
|
|
557
|
-
groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,
|
|
558
|
-
creator: user,
|
|
559
|
-
updater: user,
|
|
560
|
-
parentMessage: userMessageId ? { id: userMessageId } : undefined
|
|
561
|
-
});
|
|
562
|
-
assistantMessageId = stored.id;
|
|
563
|
-
(0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: stored });
|
|
564
|
-
/* The reply is session activity too. Leaving it out shows other participants "nothing new". */
|
|
565
|
-
(0, session_activity_publish_js_1.publishSessionActivity)({
|
|
566
|
-
domainId: domain.id,
|
|
567
|
-
sessionId: session.id,
|
|
568
|
-
kind: 'message',
|
|
569
|
-
anchorType: session.anchorType,
|
|
570
|
-
anchorId: session.anchorId,
|
|
571
|
-
preview: reply,
|
|
572
|
-
actorId: user?.id
|
|
573
|
-
});
|
|
574
|
-
await sessionRepo.update(session.id, {
|
|
575
|
-
aiClientId: client.id,
|
|
576
|
-
agentId: client.agent.id,
|
|
577
|
-
updater: user,
|
|
578
|
-
...(0, session_inbox_js_1.activityPatch)(reply, new Date(), answerDoors)
|
|
579
|
-
});
|
|
580
|
-
/*
|
|
581
|
-
* 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에
|
|
582
|
-
* 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음
|
|
583
|
-
* 턴이 「N 개 생략」으로 정직하게 알린다.
|
|
584
|
-
*
|
|
585
|
-
* 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)
|
|
586
|
-
* 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴
|
|
587
|
-
* 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.
|
|
588
|
-
*/
|
|
589
|
-
void (0, fold_session_history_js_1.foldSessionHistory)({
|
|
590
|
-
sessionId: session.id,
|
|
591
|
-
domainId: domain.id,
|
|
592
|
-
client,
|
|
593
|
-
maxTurns: LLM_HISTORY_MAX_TURNS,
|
|
594
|
-
locale: context.state?.lng
|
|
595
|
-
});
|
|
596
|
-
}
|
|
290
|
+
const assistantMessageId = await storeAnswer(turn, client, result, reply, userMessageId);
|
|
597
291
|
return {
|
|
598
292
|
reply,
|
|
599
293
|
suggestion: suggestion ?? null,
|
|
@@ -631,4 +325,325 @@ tslib_1.__decorate([
|
|
|
631
325
|
exports.AssistantChatResolver = AssistantChatResolver = tslib_1.__decorate([
|
|
632
326
|
(0, type_graphql_1.Resolver)()
|
|
633
327
|
], AssistantChatResolver);
|
|
328
|
+
/**
|
|
329
|
+
* The domain's agent - the one picked, or the default (design/ai/agent-settings.md §4). Asked before anything is
|
|
330
|
+
* stored: a domain with no AI, or an agent it cannot use, is refused as itself.
|
|
331
|
+
*/
|
|
332
|
+
async function agentOf(input, context) {
|
|
333
|
+
const { domain, user } = context.state;
|
|
334
|
+
let client;
|
|
335
|
+
try {
|
|
336
|
+
client = await (0, ai_client_base_1.aiClientFor)({
|
|
337
|
+
domain,
|
|
338
|
+
user,
|
|
339
|
+
agentId: input.agentId,
|
|
340
|
+
modeKind: input.mode.kind,
|
|
341
|
+
sessionId: input.sessionId
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
(0, shell_1.rethrowSpoken)(error, context);
|
|
346
|
+
}
|
|
347
|
+
/* A tool that asks a model of its own within this turn answers with the same agent (ToolCallContext.state). */
|
|
348
|
+
context.state.aiAgentId = client.agent.id;
|
|
349
|
+
return client;
|
|
350
|
+
}
|
|
351
|
+
/** The stored conversation this turn writes to, when it has one - this person's to write, and this kind's. */
|
|
352
|
+
async function openSession({ input, context, t }) {
|
|
353
|
+
if (!input.sessionId)
|
|
354
|
+
return undefined;
|
|
355
|
+
const { domain, user } = context.state;
|
|
356
|
+
const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
|
|
357
|
+
const found = await sessionRepo.findOneBy({ id: input.sessionId, domain: { id: domain.id } });
|
|
358
|
+
if (!found)
|
|
359
|
+
throw new Error(t('ai-assistant.text.session-not-found', { defaultValue: 'this conversation is not here any more. reload the list.' }));
|
|
360
|
+
/*
|
|
361
|
+
* A private conversation is written by its people only - and here more than anywhere: the answer is
|
|
362
|
+
* built on this conversation's history, so an outsider's question would read it back to them.
|
|
363
|
+
*/
|
|
364
|
+
await (0, session_write_gate_js_1.assertMayWriteSession)({
|
|
365
|
+
session: found,
|
|
366
|
+
userId: user?.id,
|
|
367
|
+
isParticipant: () => (0, participant_lookup_js_1.isSessionParticipant)(domain.id, found.id, user?.id),
|
|
368
|
+
t: (key, options) => t(key, options)
|
|
369
|
+
});
|
|
370
|
+
if (found.anchorType === 'figure' && input.hostContext?.figureId !== found.anchorId) {
|
|
371
|
+
throw new Error(context.t('ai-assistant.text.other-figure-history', {
|
|
372
|
+
defaultValue: 'this conversation belongs to another figure. open the conversation of the model you have open.'
|
|
373
|
+
}));
|
|
374
|
+
}
|
|
375
|
+
if (found.anchorType === 'application' && (input.hostContext?.app !== found.anchorId || input.hostContext?.figureId)) {
|
|
376
|
+
throw new Error(context.t('ai-assistant.text.application-vs-model-history', {
|
|
377
|
+
defaultValue: 'this conversation is about the application, not about a model. open the one you want.'
|
|
378
|
+
}));
|
|
379
|
+
}
|
|
380
|
+
/*
|
|
381
|
+
* 이 세션이 **이 대화의** 세션인가 — ADR-0072 결정 3. 다른 대화의 세션에 말을 붙이면 그 이력이
|
|
382
|
+
* 이 대화의 프롬프트로 들어가고, 화면은 줄이 사라져 새 대화처럼 보이므로 보낸 사람은 모른다.
|
|
383
|
+
*/
|
|
384
|
+
const verdict = (0, session_kind_js_1.judgeSessionKind)(found.kind, input.mode.kind);
|
|
385
|
+
if (verdict.action === 'refuse') {
|
|
386
|
+
throw new Error(t('ai-assistant.text.session-kind-mismatch', {
|
|
387
|
+
...verdict.params,
|
|
388
|
+
defaultValue: 'this conversation is {sessionKind}, and you are writing as {requested}. open the conversation you mean.'
|
|
389
|
+
}));
|
|
390
|
+
}
|
|
391
|
+
if (verdict.action === 'stamp') {
|
|
392
|
+
/* 칸이 서기 전에 난 세션 — 요청한 대화로 한 번 찍는다. 다음부터는 위 규칙 하나만 남는다. */
|
|
393
|
+
await sessionRepo.update(found.id, { kind: verdict.kind });
|
|
394
|
+
found.kind = verdict.kind;
|
|
395
|
+
}
|
|
396
|
+
return found;
|
|
397
|
+
}
|
|
398
|
+
/** The system prompt of this turn: the mode's, with the open subject and the screen's lines. */
|
|
399
|
+
async function promptOf({ input, context, settings, session }) {
|
|
400
|
+
const { domain } = context.state;
|
|
401
|
+
const subjectLine = session
|
|
402
|
+
? await (0, ai_client_base_1.openSubjectLine)({
|
|
403
|
+
anchorType: session.anchorType,
|
|
404
|
+
anchorId: session.anchorId,
|
|
405
|
+
domain,
|
|
406
|
+
state: context.state
|
|
407
|
+
})
|
|
408
|
+
: undefined;
|
|
409
|
+
/* What the person has in front of them besides the subject - the screen's unread notices (ADR-0199 amendment 1). */
|
|
410
|
+
const screenLines = await (0, turn_lines_js_1.turnLinesOf)({ page: input.page, state: context.state });
|
|
411
|
+
return (0, mode_categories_js_1.turnSystemPrompt)(settings.systemPrompt, { subjectLine: [subjectLine, ...screenLines].filter(Boolean).join('\n\n') || undefined, page: input.page });
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Files sent with this turn (design/ai/shared-dock.md §9). They were stored with this conversation by
|
|
415
|
+
* attachToConversation; one that is not this conversation's is refused, never read. The policy is the
|
|
416
|
+
* mode's - checked again here, since the door is the authority, not the screen.
|
|
417
|
+
*/
|
|
418
|
+
async function attachmentsOf({ input, context, t, session }) {
|
|
419
|
+
const { domain } = context.state;
|
|
420
|
+
const attachmentRows = [];
|
|
421
|
+
if (input.attachmentIds?.length) {
|
|
422
|
+
if (!session)
|
|
423
|
+
throw new Error(t('ai-assistant.text.attachments-need-session', { defaultValue: 'attachments need a saved conversation.' }));
|
|
424
|
+
for (const id of input.attachmentIds) {
|
|
425
|
+
const row = await (0, session_attachments_js_1.findChatAttachment)(domain.id, session.id, id);
|
|
426
|
+
if (!row)
|
|
427
|
+
throw new Error(t('ai-assistant.text.attachment-not-in-session', { defaultValue: 'an attachment does not belong to this conversation.' }));
|
|
428
|
+
attachmentRows.push(row);
|
|
429
|
+
}
|
|
430
|
+
const refusal = (0, attachment_policy_js_1.refuseAttachments)((0, registry_js_1.getAssistantMode)(input.mode.kind)?.attachments, attachmentRows.map(row => ({ name: row.name, type: row.mimetype, size: Number(row.size) })));
|
|
431
|
+
if (refusal)
|
|
432
|
+
throw new Error(t(`ai-assistant.text.${refusal.code}`, { ...refusal, defaultValue: refusal.code }));
|
|
433
|
+
}
|
|
434
|
+
return attachmentRows;
|
|
435
|
+
}
|
|
436
|
+
/** The person's question stored, announced and its @-mentions seated; its id. Nothing is stored without a session. */
|
|
437
|
+
async function storeQuestion({ input, context, session }, attachmentRows) {
|
|
438
|
+
const lastUserMessage = input.messages[input.messages.length - 1];
|
|
439
|
+
if (!session || lastUserMessage?.role !== 'user')
|
|
440
|
+
return undefined;
|
|
441
|
+
const { domain, user } = context.state;
|
|
442
|
+
const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
|
|
443
|
+
const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
|
|
444
|
+
const previousLast = await messageRepo.findOne({
|
|
445
|
+
where: { session: { id: session.id } },
|
|
446
|
+
order: { createdAt: 'DESC' }
|
|
447
|
+
});
|
|
448
|
+
const saved = await messageRepo.save({
|
|
449
|
+
session: { id: session.id },
|
|
450
|
+
role: 'user',
|
|
451
|
+
content: lastUserMessage.content,
|
|
452
|
+
/*
|
|
453
|
+
* This door is the one people call to ask the assistant, so a turn stored here was for the
|
|
454
|
+
* assistant (ADR-0070 A15 decision ①). The value comes from which door was called, never
|
|
455
|
+
* from the request — two sources for one fact can disagree.
|
|
456
|
+
*/
|
|
457
|
+
addressee: 'assistant',
|
|
458
|
+
attachments: attachmentRows.length ? JSON.stringify(attachmentRows.map(session_attachments_js_1.describeAttachment)) : undefined,
|
|
459
|
+
creator: user,
|
|
460
|
+
updater: user,
|
|
461
|
+
parentMessage: previousLast ? { id: previousLast.id } : undefined
|
|
462
|
+
});
|
|
463
|
+
/*
|
|
464
|
+
* Session activity is denormalised for the list: most-recent ordering and another
|
|
465
|
+
* participant's unread badge read it. Best effort — a conversation must not fail because a
|
|
466
|
+
* list sorts one position late.
|
|
467
|
+
*/
|
|
468
|
+
try {
|
|
469
|
+
const patch = (0, session_inbox_js_1.activityPatch)(lastUserMessage.content);
|
|
470
|
+
if (!session.name)
|
|
471
|
+
patch.name = (0, session_inbox_js_1.autoSessionName)(lastUserMessage.content);
|
|
472
|
+
await sessionRepo.update(session.id, patch);
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
/* noop */
|
|
476
|
+
}
|
|
477
|
+
/*
|
|
478
|
+
* 사람이 `@이름` 으로 부른 사람은 이 대화에 들어온다(ADR-0071 결정 1). 이 문은 **사람의 턴**을
|
|
479
|
+
* 저장하는 문이라 그 일을 한다 — 모델의 답이나 도구 결과는 아무도 초대하지 않는다. 공개 방에서 말한 사람도
|
|
480
|
+
* 이때 자리에 앉는다(`seatTurn`) — 참여자 줄 · 접속 표시 · 안 읽음이 실제로 말한 사람과 맞도록.
|
|
481
|
+
*/
|
|
482
|
+
const invite = await (0, mention_invite_js_1.seatTurn)({
|
|
483
|
+
content: lastUserMessage.content,
|
|
484
|
+
sessionId: session.id,
|
|
485
|
+
domainId: domain.id,
|
|
486
|
+
inviter: user,
|
|
487
|
+
participants: (0, shell_1.getRepository)(chat_session_participant_js_1.ChatSessionParticipant),
|
|
488
|
+
visibility: session.visibility
|
|
489
|
+
});
|
|
490
|
+
/* 편지가 못 갔다고 방에 들어온 사실이 취소되지는 않는다(`sendInviteNotification`). */
|
|
491
|
+
await (0, invite_notification_js_1.sendInviteNotification)(context.state?.sendNotice, invite.invited, user, session?.name, undefined, (0, request_translator_js_1.requestTranslator)(context));
|
|
492
|
+
(0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: saved });
|
|
493
|
+
(0, session_activity_publish_js_1.publishSessionActivity)({
|
|
494
|
+
domainId: domain.id,
|
|
495
|
+
sessionId: session.id,
|
|
496
|
+
kind: 'message',
|
|
497
|
+
anchorType: session.anchorType,
|
|
498
|
+
anchorId: session.anchorId,
|
|
499
|
+
preview: lastUserMessage.content,
|
|
500
|
+
actorId: user?.id
|
|
501
|
+
});
|
|
502
|
+
return saved.id;
|
|
503
|
+
}
|
|
504
|
+
/** What the model reads of this conversation: the stored turns this reader may see, capped and summarised. */
|
|
505
|
+
async function historyOf({ input, context, session }, userMessageId) {
|
|
506
|
+
const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
|
|
507
|
+
const readRows = session
|
|
508
|
+
? await messageRepo.find({
|
|
509
|
+
where: { session: { id: session.id } },
|
|
510
|
+
order: { createdAt: 'ASC' },
|
|
511
|
+
relations: ['creator']
|
|
512
|
+
})
|
|
513
|
+
: [];
|
|
514
|
+
/*
|
|
515
|
+
* 모델이 읽는 이력도 **부른 사람** 기준으로 가린다 — ADR-0073 판정 1. 가리지 않으면, 문을 한 번도
|
|
516
|
+
* 안 지난 사람이 "아까 그 수 다시 말해 줘" 한 마디로 값을 가져간다. 모델이 옮겨 적는 순간 그 값은
|
|
517
|
+
* 문 없는 새 답이 된다. 가린 자리를 지우지 않고 한 줄로 남기는 이유도 같다 — 지우면 모델이 그런
|
|
518
|
+
* 말이 없었다고 답하고, 그것은 거짓말이다.
|
|
519
|
+
*/
|
|
520
|
+
const storedRows = await (0, reader_gate_js_1.readerGate)(context)(readRows);
|
|
521
|
+
const capped = (0, history_summary_js_1.splitByCap)(storedRows.map(row => ({ id: row.id, role: row.role, content: row.content ?? '' })), LLM_HISTORY_MAX_TURNS);
|
|
522
|
+
const historyFolded = capped.dropped.length > 0
|
|
523
|
+
? { omitted: capped.dropped.length, summarized: Boolean(session?.lastSummary) }
|
|
524
|
+
: undefined;
|
|
525
|
+
const conversation = session
|
|
526
|
+
? (0, llm_history_js_1.buildLlmHistory)(
|
|
527
|
+
/*
|
|
528
|
+
* The model reads who spoke and who they spoke to. The entity carries the speaker as a
|
|
529
|
+
* relation and the addressee as a column; the history wants them as plain fields, and
|
|
530
|
+
* without this mapping every line arrived unattributed — a room of people read as one
|
|
531
|
+
* voice (ADR-0070 A15 decision ②).
|
|
532
|
+
*/
|
|
533
|
+
storedRows.map(message => ({
|
|
534
|
+
id: message.id,
|
|
535
|
+
role: message.role,
|
|
536
|
+
/*
|
|
537
|
+
* A file sent in an earlier turn is not sent again - one line names it, and the model opens it
|
|
538
|
+
* with readChatAttachment when it needs to (cost is a usage axis, ADR-0061 decision 6).
|
|
539
|
+
*/
|
|
540
|
+
content: [
|
|
541
|
+
message.content,
|
|
542
|
+
...(message.id !== userMessageId && Array.isArray(message.attachmentsJson) ? message.attachmentsJson.map(attachment_policy_js_1.attachmentHistoryLine) : []),
|
|
543
|
+
/* An answer that offered cards names them, so a later outcome row reads as about one of them (audit N7). */
|
|
544
|
+
...(message.role === 'assistant' ? (0, proposal_outcome_js_1.offeredCardLines)(message.proposals) : [])
|
|
545
|
+
].join('\n'),
|
|
546
|
+
senderId: message.creator?.id,
|
|
547
|
+
senderName: message.creator?.name,
|
|
548
|
+
addressee: message.addressee
|
|
549
|
+
})), {
|
|
550
|
+
maxTurns: LLM_HISTORY_MAX_TURNS,
|
|
551
|
+
truncateAfterMessageId: input.truncateAfterMessageId,
|
|
552
|
+
/* The message just stored is this turn's question — truncation must never drop it. */
|
|
553
|
+
keepMessageIds: userMessageId ? [userMessageId] : undefined,
|
|
554
|
+
summary: session.lastSummary
|
|
555
|
+
? { text: session.lastSummary, upToMessageId: session.summaryUpToMessageId }
|
|
556
|
+
: undefined
|
|
557
|
+
})
|
|
558
|
+
: input.messages.map(message => ({ role: message.role, content: message.content }));
|
|
559
|
+
return { conversation, storedRows, historyFolded };
|
|
560
|
+
}
|
|
561
|
+
/** The files of this turn read once, on the question; or the screen's picture. What the tools get of them. */
|
|
562
|
+
async function withTurnFiles({ input }, conversation, attachmentRows) {
|
|
563
|
+
const turnFiles = await (0, turn_attachments_js_1.readTurnAttachments)(attachmentRows, (0, attachment_policy_js_1.textCharsOf)((0, registry_js_1.getAssistantMode)(input.mode?.kind ?? '')?.attachments), session_attachments_js_1.attachmentForModel);
|
|
564
|
+
if (attachmentRows.length && conversation.length > 0) {
|
|
565
|
+
const last = conversation[conversation.length - 1];
|
|
566
|
+
if (last.role === 'user' && typeof last.content === 'string') {
|
|
567
|
+
last.content = [{ type: 'text', text: last.content }, ...turnFiles.parts];
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
else if (input.hostContext?.image?.data && conversation.length > 0) {
|
|
571
|
+
/* The screen-image path (figure's rendered view) - not a file of the conversation. */
|
|
572
|
+
const last = conversation[conversation.length - 1];
|
|
573
|
+
if (last.role === 'user' && typeof last.content === 'string') {
|
|
574
|
+
const raw = input.hostContext.image;
|
|
575
|
+
const rawData = typeof raw.data === 'string' ? raw.data.replace(/^data:image\/[a-zA-Z]+;base64,/, '') : raw.data;
|
|
576
|
+
const buf = typeof rawData === 'string' ? Buffer.from(rawData, 'base64') : Buffer.from(rawData);
|
|
577
|
+
last.content = [
|
|
578
|
+
{ type: 'text', text: last.content },
|
|
579
|
+
{ type: 'image', source: { kind: 'base64', data: buf, mediaType: raw.mediaType || 'image/png' } }
|
|
580
|
+
];
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return turnFiles;
|
|
584
|
+
}
|
|
585
|
+
/** The answer stored and announced, the conversation's activity moved on, its history folded later; the answer's id. */
|
|
586
|
+
async function storeAnswer({ context, settings, session }, client, result, reply, userMessageId) {
|
|
587
|
+
/*
|
|
588
|
+
* 이 답이 지나온 문 — ADR-0073 판정 1. 행에도, 목록 미리보기에도 같은 값이 간다. 한쪽만 적으면
|
|
589
|
+
* 가려진 답이 목록에는 그대로 뜬다.
|
|
590
|
+
*/
|
|
591
|
+
const answerDoors = (0, message_doors_js_1.doorsForAnswer)(result.loop.toolUsages ?? [], name => (0, ai_client_base_1.findToolSpec)(name, settings.toolCategories)?.doors);
|
|
592
|
+
if (!session)
|
|
593
|
+
return undefined;
|
|
594
|
+
const { domain, user } = context.state;
|
|
595
|
+
const sessionRepo = (0, shell_1.getRepository)(chat_session_js_1.ChatSession);
|
|
596
|
+
const messageRepo = (0, shell_1.getRepository)(chat_message_js_1.ChatMessage);
|
|
597
|
+
const stored = await messageRepo.save({
|
|
598
|
+
session: { id: session.id },
|
|
599
|
+
role: 'assistant',
|
|
600
|
+
content: reply,
|
|
601
|
+
/*
|
|
602
|
+
* 이 답이 지나온 문을 함께 적는다 — ADR-0073 판정 1. 방은 도메인 안에서 공개이므로, 이 문장이
|
|
603
|
+
* 실어 나르는 값을 나중에 읽는 사람이 열 수 있는지 판정할 근거가 행에 있어야 한다. 적지 않으면
|
|
604
|
+
* 빈 목록이 되고, 빈 목록은 누구나 읽는다는 뜻이다.
|
|
605
|
+
*/
|
|
606
|
+
doors: answerDoors,
|
|
607
|
+
toolUsages: result.loop.toolUsages?.length ? JSON.stringify(result.loop.toolUsages) : undefined,
|
|
608
|
+
proposals: result.loop.proposals?.length ? JSON.stringify(result.loop.proposals) : undefined,
|
|
609
|
+
groundingWarnings: result.groundingWarnings?.length ? JSON.stringify(result.groundingWarnings) : undefined,
|
|
610
|
+
creator: user,
|
|
611
|
+
updater: user,
|
|
612
|
+
parentMessage: userMessageId ? { id: userMessageId } : undefined
|
|
613
|
+
});
|
|
614
|
+
(0, chat_message_publish_js_1.publishChatMessage)({ domainId: domain.id, sessionId: session.id, message: stored });
|
|
615
|
+
/* The reply is session activity too. Leaving it out shows other participants "nothing new". */
|
|
616
|
+
(0, session_activity_publish_js_1.publishSessionActivity)({
|
|
617
|
+
domainId: domain.id,
|
|
618
|
+
sessionId: session.id,
|
|
619
|
+
kind: 'message',
|
|
620
|
+
anchorType: session.anchorType,
|
|
621
|
+
anchorId: session.anchorId,
|
|
622
|
+
preview: reply,
|
|
623
|
+
actorId: user?.id
|
|
624
|
+
});
|
|
625
|
+
await sessionRepo.update(session.id, {
|
|
626
|
+
aiClientId: client.id,
|
|
627
|
+
agentId: client.agent.id,
|
|
628
|
+
updater: user,
|
|
629
|
+
...(0, session_inbox_js_1.activityPatch)(reply, new Date(), answerDoors)
|
|
630
|
+
});
|
|
631
|
+
/*
|
|
632
|
+
* 상한 밖으로 밀려난 앞부분을 요약으로 접는다 — **답을 돌려준 뒤**에 한다(사용자 대기 시간에
|
|
633
|
+
* 요약 호출을 얹지 않는다). 기다리지 않으므로 실패해도 대화에는 영향이 없다: 요약이 없으면 다음
|
|
634
|
+
* 턴이 「N 개 생략」으로 정직하게 알린다.
|
|
635
|
+
*
|
|
636
|
+
* 이 문에는 이 호출이 없었다. 조각은 다 있었는데(상한 · 생략 알림 · `lastSummary` · 순수 규칙)
|
|
637
|
+
* 부르는 쪽이 보드 제품 하나뿐이어서, 앱의 대화는 며칠이 지나도 앞부분을 요약하지 않고 매 턴
|
|
638
|
+
* 「생략했다」고만 말했다 — 협의가 길어질수록 처음에 합의한 것이 먼저 사라진다.
|
|
639
|
+
*/
|
|
640
|
+
void (0, fold_session_history_js_1.foldSessionHistory)({
|
|
641
|
+
sessionId: session.id,
|
|
642
|
+
domainId: domain.id,
|
|
643
|
+
client,
|
|
644
|
+
maxTurns: LLM_HISTORY_MAX_TURNS,
|
|
645
|
+
locale: context.state?.lng
|
|
646
|
+
});
|
|
647
|
+
return stored.id;
|
|
648
|
+
}
|
|
634
649
|
//# sourceMappingURL=assistant-chat-resolver.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type AIClient, type AIMessage, type RegistryAssistantResult, type ToolAccessCheck, type ToolAttachment, type ToolCallRecord, type ToolFront, type UnattendedRunRef } from '@things-factory/ai-client-base';
|
|
2
|
+
/** What a mode decides of a turn - from the declaration, as the caller resolved it. */
|
|
3
|
+
export interface ModeTurnSettings {
|
|
4
|
+
systemPrompt: string;
|
|
5
|
+
toolCategories?: string[];
|
|
6
|
+
temperature?: number;
|
|
7
|
+
maxTokens?: number;
|
|
8
|
+
requireToolOnFirstTurn?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface ModeTurnInput {
|
|
11
|
+
client: AIClient;
|
|
12
|
+
/** The conversation the model reads, newest last. */
|
|
13
|
+
messages: AIMessage[];
|
|
14
|
+
settings: ModeTurnSettings;
|
|
15
|
+
mode: {
|
|
16
|
+
kind: string;
|
|
17
|
+
target?: string;
|
|
18
|
+
};
|
|
19
|
+
/** The caller's koa state - the server's domain and user. */
|
|
20
|
+
state: any;
|
|
21
|
+
toolAccess?: ToolAccessCheck;
|
|
22
|
+
front?: ToolFront;
|
|
23
|
+
/** What the screen sent: tools read it as `context.host`; never trusted for who may do what. */
|
|
24
|
+
hostContext?: any;
|
|
25
|
+
t?: (key: string, params?: Record<string, any>) => string;
|
|
26
|
+
conversation?: {
|
|
27
|
+
id: string;
|
|
28
|
+
};
|
|
29
|
+
attachments?: ToolAttachment[];
|
|
30
|
+
/** A run's limits: lookups, no wrap-up call, a stop. The conversation door's own when absent. */
|
|
31
|
+
limits?: {
|
|
32
|
+
maxIterations?: number;
|
|
33
|
+
salvageOnMaxIterations?: boolean;
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
};
|
|
36
|
+
onToolCall?: (record: ToolCallRecord) => void;
|
|
37
|
+
run?: UnattendedRunRef;
|
|
38
|
+
}
|
|
39
|
+
export declare function runModeTurn(input: ModeTurnInput): Promise<RegistryAssistantResult>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runModeTurn = runModeTurn;
|
|
4
|
+
/*
|
|
5
|
+
* One turn of a registered mode's conversation (2026-11-14).
|
|
6
|
+
*
|
|
7
|
+
* Three callers run a mode's turn: the conversation door (`assistantChat`), an unattended run, and the conformance
|
|
8
|
+
* harness an application tests its modes with. Each handed `registryAssistantChat` the mode's settings in its own
|
|
9
|
+
* words -- one gave the grounding guard the prompt and the turns as evidence, another did not -- so a turn answered
|
|
10
|
+
* by one road could be checked otherwise than the same turn by another. What a mode's settings mean for a turn is
|
|
11
|
+
* said here once; what differs between the callers is what they pass.
|
|
12
|
+
*/
|
|
13
|
+
const ai_client_base_1 = require("@things-factory/ai-client-base");
|
|
14
|
+
const grounding_sources_js_1 = require("../grounding-sources.js");
|
|
15
|
+
async function runModeTurn(input) {
|
|
16
|
+
const { settings } = input;
|
|
17
|
+
return (0, ai_client_base_1.registryAssistantChat)({
|
|
18
|
+
client: input.client,
|
|
19
|
+
messages: input.messages,
|
|
20
|
+
systemPrompt: settings.systemPrompt,
|
|
21
|
+
toolCategories: settings.toolCategories,
|
|
22
|
+
...(input.front ? { front: input.front } : {}),
|
|
23
|
+
/* 도구가 「어느 대화에서 불렸나」를 안다 — 서버의 값이다(ADR-0061 결정 3). */
|
|
24
|
+
mode: { kind: input.mode.kind, ...(input.mode.target ? { target: input.mode.target } : {}) },
|
|
25
|
+
...(input.conversation?.id ? { conversation: { id: input.conversation.id } } : {}),
|
|
26
|
+
toolAccess: input.toolAccess,
|
|
27
|
+
...(input.t ? { t: input.t } : {}),
|
|
28
|
+
hostContext: input.hostContext,
|
|
29
|
+
...(input.attachments ? { attachments: input.attachments } : {}),
|
|
30
|
+
/*
|
|
31
|
+
* 근거는 도구 결과만이 아니다 — 시스템 프롬프트 · 이 대화의 말 · 화면이 보낸 스냅숏도 근거다
|
|
32
|
+
* (`ai-client-base/utils/grounding`). 넘기지 않으면 **사람이 방금 타이핑한 식별자**를 되받아 적은 답이
|
|
33
|
+
* 「근거 없음」으로 표시된다.
|
|
34
|
+
*/
|
|
35
|
+
groundingSources: (0, grounding_sources_js_1.groundingSourcesFor)({ systemPrompt: settings.systemPrompt, messages: input.messages, hostContext: input.hostContext }),
|
|
36
|
+
state: input.state,
|
|
37
|
+
temperature: settings.temperature,
|
|
38
|
+
maxTokens: settings.maxTokens,
|
|
39
|
+
requireToolOnFirstTurn: settings.requireToolOnFirstTurn,
|
|
40
|
+
...(input.limits?.maxIterations !== undefined ? { maxIterations: input.limits.maxIterations } : {}),
|
|
41
|
+
...(input.limits?.salvageOnMaxIterations !== undefined ? { salvageOnMaxIterations: input.limits.salvageOnMaxIterations } : {}),
|
|
42
|
+
...(input.limits?.signal ? { signal: input.limits.signal } : {}),
|
|
43
|
+
...(input.onToolCall ? { onToolCall: input.onToolCall } : {}),
|
|
44
|
+
...(input.run ? { run: input.run } : {})
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=mode-turn.js.map
|
|
@@ -23,6 +23,7 @@ exports.openSubjectLineFor = openSubjectLineFor;
|
|
|
23
23
|
* · 슬래시가 가리키는 도구가 그 모드 안에 있는가
|
|
24
24
|
*/
|
|
25
25
|
const ai_client_base_1 = require("@things-factory/ai-client-base");
|
|
26
|
+
const mode_turn_js_1 = require("../assistant-turn/mode-turn.js");
|
|
26
27
|
const registry_js_1 = require("../assistant-mode/registry.js");
|
|
27
28
|
const resolve_js_1 = require("../assistant-mode/resolve.js");
|
|
28
29
|
const mode_categories_js_1 = require("../assistant-mode/mode-categories.js");
|
|
@@ -37,16 +38,14 @@ exports.keyEchoTranslate = keyEchoTranslate;
|
|
|
37
38
|
async function runRegisteredMode(kind, options = {}) {
|
|
38
39
|
const settings = (0, resolve_js_1.resolveModeSettings)({ kind }, exports.keyEchoTranslate);
|
|
39
40
|
let requiredToolOnFirstTurn = false;
|
|
40
|
-
|
|
41
|
+
/* The turn the conversation door runs (runModeTurn), with the mode's own settings - never the test's. */
|
|
42
|
+
const result = await (0, mode_turn_js_1.runModeTurn)({
|
|
41
43
|
client: options.client,
|
|
42
44
|
messages: [{ role: 'user', content: '한 턴' }],
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
settings: { ...settings, requireToolOnFirstTurn: (requiredToolOnFirstTurn = Boolean(settings.requireToolOnFirstTurn)) },
|
|
46
|
+
mode: { kind },
|
|
45
47
|
/* What the door puts in front on that screen (ADR-0061 decision 9) - a mode too large for one call is offered as a person meets it. */
|
|
46
48
|
front: { categories: (0, mode_categories_js_1.modeFrontCategories)((0, registry_js_1.getAssistantMode)(kind) ?? {}, options.screen ?? {}) },
|
|
47
|
-
requireToolOnFirstTurn: (requiredToolOnFirstTurn = Boolean(settings.requireToolOnFirstTurn)),
|
|
48
|
-
temperature: settings.temperature,
|
|
49
|
-
maxTokens: settings.maxTokens,
|
|
50
49
|
hostContext: options.hostContext,
|
|
51
50
|
/*
|
|
52
51
|
* This harness asks about **the mode** — "what does this mode open", not "does this person pass the
|
|
@@ -23,7 +23,7 @@ const shell_1 = require("@things-factory/shell");
|
|
|
23
23
|
const registry_js_1 = require("../assistant-mode/registry.js");
|
|
24
24
|
const mode_categories_js_1 = require("../assistant-mode/mode-categories.js");
|
|
25
25
|
const message_doors_js_1 = require("../chat-message/message-doors.js");
|
|
26
|
-
const
|
|
26
|
+
const mode_turn_js_1 = require("../assistant-turn/mode-turn.js");
|
|
27
27
|
const tool_access_js_1 = require("../tool-access.js");
|
|
28
28
|
const assistant_run_js_1 = require("./assistant-run.js");
|
|
29
29
|
const limits_js_1 = require("./limits.js");
|
|
@@ -149,30 +149,29 @@ async function runAssistantUnattended(input, deps = defaultDeps()) {
|
|
|
149
149
|
let result;
|
|
150
150
|
try {
|
|
151
151
|
result = await Promise.race([
|
|
152
|
-
(0,
|
|
152
|
+
(0, mode_turn_js_1.runModeTurn)({
|
|
153
153
|
client,
|
|
154
154
|
messages,
|
|
155
|
-
|
|
156
|
-
|
|
155
|
+
settings: {
|
|
156
|
+
systemPrompt,
|
|
157
|
+
toolCategories: categories,
|
|
158
|
+
temperature: mode.temperature,
|
|
159
|
+
maxTokens: mode.maxTokens,
|
|
160
|
+
requireToolOnFirstTurn: mode.requireToolOnFirstTurn
|
|
161
|
+
},
|
|
157
162
|
/* No screen and no conversation - the mode's own tools in front, the lists opened as the run needs (ADR-0061 decision 9). */
|
|
158
163
|
front: { categories: mode.toolCategories ?? [] },
|
|
159
|
-
mode:
|
|
164
|
+
mode: input.mode,
|
|
160
165
|
toolAccess: deps.toolAccess(state),
|
|
161
166
|
hostContext: input.hostContext,
|
|
162
167
|
state,
|
|
163
|
-
temperature: mode.temperature,
|
|
164
|
-
maxTokens: mode.maxTokens,
|
|
165
|
-
requireToolOnFirstTurn: mode.requireToolOnFirstTurn,
|
|
166
168
|
/* Each step is one request. A run that reaches the last step without an answer failed - no wrap-up call (§4). */
|
|
167
|
-
maxIterations: limits.maxModelCalls,
|
|
168
|
-
salvageOnMaxIterations: false,
|
|
169
|
-
signal: abort.signal,
|
|
169
|
+
limits: { maxIterations: limits.maxModelCalls, salvageOnMaxIterations: false, signal: abort.signal },
|
|
170
170
|
onToolCall: record => {
|
|
171
171
|
if (!over)
|
|
172
172
|
reads.push(record);
|
|
173
173
|
},
|
|
174
|
-
run: { id: held.id, source: run.source, subject: run.subject, scheduledAt: run.scheduledAt.toISOString() }
|
|
175
|
-
groundingSources: (0, grounding_sources_js_1.groundingSourcesFor)({ systemPrompt, messages: messages, hostContext: input.hostContext })
|
|
174
|
+
run: { id: held.id, source: run.source, subject: run.subject, scheduledAt: run.scheduledAt.toISOString() }
|
|
176
175
|
}),
|
|
177
176
|
timeout
|
|
178
177
|
]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@things-factory/ai-assistant",
|
|
3
|
-
"version": "10.1.
|
|
3
|
+
"version": "10.1.282",
|
|
4
4
|
"main": "dist-server/index.js",
|
|
5
5
|
"things-factory": true,
|
|
6
6
|
"author": "heartyoh",
|
|
@@ -37,14 +37,14 @@
|
|
|
37
37
|
"@operato/shell": "^10.29.69",
|
|
38
38
|
"@operato/styles": "^10.0.0",
|
|
39
39
|
"@operato/utils": "^10.29.76",
|
|
40
|
-
"@things-factory/ai-client-base": "^10.1.
|
|
41
|
-
"@things-factory/apptool-base": "^10.1.
|
|
42
|
-
"@things-factory/attachment-base": "^10.1.
|
|
43
|
-
"@things-factory/auth-base": "^10.1.
|
|
44
|
-
"@things-factory/env": "^10.1.
|
|
45
|
-
"@things-factory/help": "^10.1.
|
|
46
|
-
"@things-factory/setting-base": "^10.1.
|
|
47
|
-
"@things-factory/shell": "^10.1.
|
|
40
|
+
"@things-factory/ai-client-base": "^10.1.282",
|
|
41
|
+
"@things-factory/apptool-base": "^10.1.282",
|
|
42
|
+
"@things-factory/attachment-base": "^10.1.282",
|
|
43
|
+
"@things-factory/auth-base": "^10.1.282",
|
|
44
|
+
"@things-factory/env": "^10.1.281",
|
|
45
|
+
"@things-factory/help": "^10.1.282",
|
|
46
|
+
"@things-factory/setting-base": "^10.1.282",
|
|
47
|
+
"@things-factory/shell": "^10.1.282",
|
|
48
48
|
"dompurify": "^3.0.0",
|
|
49
49
|
"exceljs": "4.2.0",
|
|
50
50
|
"graphql-scalars": "^1.22.0",
|
|
@@ -74,5 +74,5 @@
|
|
|
74
74
|
"copyfiles": "^2.4.1",
|
|
75
75
|
"rimraf": "^5.0.0"
|
|
76
76
|
},
|
|
77
|
-
"gitHead": "
|
|
77
|
+
"gitHead": "6a232e670bdb52e1420b1d33cdeeb37ceb0f26b8"
|
|
78
78
|
}
|
package/translations/en.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "something went wrong while handling this. tell an administrator if it keeps happening.",
|
|
85
85
|
"ai-assistant.notice.too-long": "this stopped after {iter} lookups without an answer.",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} failed {count} times in a row, so it stopped. try saying it differently.",
|
|
87
|
+
"ai-assistant.notice.cut-short": "this answer reached its length limit and was cut off.",
|
|
87
88
|
"ai-assistant.text.no-match": "no match",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "could not read this conversation.",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "could not load the conversation list.",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "This domain's key {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "{domain} key",
|
|
343
344
|
"ai-assistant.agent.key-missing": "No key",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "No key - this computer's login",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "None: it answers on the Claude Code CLI logged in on the computer this server runs on. For development only.",
|
|
344
347
|
"ai-assistant.agent.more": "More",
|
|
345
348
|
"ai-assistant.agent.edit": "Edit",
|
|
346
349
|
"ai-assistant.agent.delete": "Delete",
|
package/translations/es.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "algo salió mal al procesar esto. avise a un administrador si sigue ocurriendo.",
|
|
85
85
|
"ai-assistant.notice.too-long": "se detuvo tras {iter} consultas sin obtener una respuesta.",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} falló {count} veces seguidas, así que se detuvo. intente decirlo de otra forma.",
|
|
87
|
+
"ai-assistant.notice.cut-short": "esta respuesta llegó a su límite de longitud y quedó cortada.",
|
|
87
88
|
"ai-assistant.text.no-match": "sin coincidencias",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "no se pudo leer esta conversación.",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "no se pudo cargar la lista de conversaciones.",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "Clave de este dominio {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "Clave de {domain}",
|
|
343
344
|
"ai-assistant.agent.key-missing": "Sin clave",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "Sin clave - el inicio de sesión de este equipo",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "No necesaria: responde con la CLI de Claude Code con sesión iniciada en el equipo donde corre este servidor. Solo para desarrollo.",
|
|
344
347
|
"ai-assistant.agent.more": "Más",
|
|
345
348
|
"ai-assistant.agent.edit": "Editar",
|
|
346
349
|
"ai-assistant.agent.delete": "Eliminar",
|
package/translations/ja.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "処理中に問題が発生しました。同じことが続く場合は管理者にお知らせください。",
|
|
85
85
|
"ai-assistant.notice.too-long": "{iter} 回の照会で答えを出せずに止まりました。",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} の呼び出しが {count} 回続けて失敗したため止まりました。言い方を変えてみてください。",
|
|
87
|
+
"ai-assistant.notice.cut-short": "答えが長さの上限に達したため、途中で切れています。",
|
|
87
88
|
"ai-assistant.text.no-match": "一致するものがありません",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "この会話を読み取れませんでした。",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "会話の一覧を読み込めませんでした。",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "この事業所のキー {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "{domain} のキー",
|
|
343
344
|
"ai-assistant.agent.key-missing": "キーなし",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "キーなし - このコンピューターのログイン",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "不要: このサーバーが動くコンピューターにログインした Claude Code CLI で答えます。開発専用です。",
|
|
344
347
|
"ai-assistant.agent.more": "その他",
|
|
345
348
|
"ai-assistant.agent.edit": "編集",
|
|
346
349
|
"ai-assistant.agent.delete": "削除",
|
package/translations/ko.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "처리 중에 문제가 생겼습니다. 같은 문제가 계속되면 관리자에게 알려 주세요.",
|
|
85
85
|
"ai-assistant.notice.too-long": "조회 {iter}번 안에 답을 만들지 못하고 멈췄습니다.",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} 호출이 연속 {count}회 실패하여 중단했습니다. 요청 내용을 구체적으로 입력하여 다시 시도해 주세요.",
|
|
87
|
+
"ai-assistant.notice.cut-short": "답이 길이 한도에 닿아 중간에 끊겼습니다.",
|
|
87
88
|
"ai-assistant.text.no-match": "맞는 것이 없습니다",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "이 대화를 읽지 못했습니다.",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "대화 목록을 불러오지 못했습니다.",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "이 사업장 키 {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "{domain} 키",
|
|
343
344
|
"ai-assistant.agent.key-missing": "키 없음",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "키 없음 - 이 컴퓨터의 로그인",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "필요 없음: 이 서버가 도는 컴퓨터에 로그인된 Claude Code CLI로 답합니다. 개발 전용입니다.",
|
|
344
347
|
"ai-assistant.agent.more": "더 보기",
|
|
345
348
|
"ai-assistant.agent.edit": "수정",
|
|
346
349
|
"ai-assistant.agent.delete": "삭제",
|
package/translations/ms.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "ada masalah semasa mengendalikan ini. beritahu pentadbir jika ia berulang.",
|
|
85
85
|
"ai-assistant.notice.too-long": "ini berhenti selepas {iter} carian tanpa jawapan.",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} gagal {count} kali berturut-turut, jadi ia berhenti. cuba nyatakan dengan cara lain.",
|
|
87
|
+
"ai-assistant.notice.cut-short": "jawapan ini mencapai had panjangnya dan terpotong.",
|
|
87
88
|
"ai-assistant.text.no-match": "tiada padanan",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "tidak dapat membaca perbualan ini.",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "tidak dapat memuatkan senarai perbualan.",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "Kunci domain ini {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "Kunci {domain}",
|
|
343
344
|
"ai-assistant.agent.key-missing": "Tiada kunci",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "Tiada kunci - log masuk komputer ini",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "Tidak perlu: ia menjawab melalui CLI Claude Code yang log masuk pada komputer pelayan ini. Untuk pembangunan sahaja.",
|
|
344
347
|
"ai-assistant.agent.more": "Lagi",
|
|
345
348
|
"ai-assistant.agent.edit": "Sunting",
|
|
346
349
|
"ai-assistant.agent.delete": "Padam",
|
package/translations/zh.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"ai-assistant.notice.provider-error": "处理时出了问题。如果一直这样,请告知管理员。",
|
|
85
85
|
"ai-assistant.notice.too-long": "查询 {iter} 次后仍未得出答案,已停止。",
|
|
86
86
|
"ai-assistant.notice.tool-kept-failing": "{tool} 连续失败 {count} 次,已停止。请换一种说法。",
|
|
87
|
+
"ai-assistant.notice.cut-short": "回答已达到长度上限,内容被截断。",
|
|
87
88
|
"ai-assistant.text.no-match": "没有匹配项",
|
|
88
89
|
"ai-assistant.text.messages-unreadable": "无法读取这个对话。",
|
|
89
90
|
"ai-assistant.text.sessions-unreadable": "无法加载对话列表。",
|
|
@@ -341,6 +342,8 @@
|
|
|
341
342
|
"ai-assistant.agent.key-this-domain": "此站点的密钥 {hint}",
|
|
342
343
|
"ai-assistant.agent.key-of": "{domain} 的密钥",
|
|
343
344
|
"ai-assistant.agent.key-missing": "无密钥",
|
|
345
|
+
"ai-assistant.agent.key-none-needed": "无密钥 - 本机登录",
|
|
346
|
+
"ai-assistant.agent.key-none-needed-hint": "无需: 使用本服务器所在计算机上已登录的 Claude Code CLI 回答。仅用于开发。",
|
|
344
347
|
"ai-assistant.agent.more": "更多",
|
|
345
348
|
"ai-assistant.agent.edit": "编辑",
|
|
346
349
|
"ai-assistant.agent.delete": "删除",
|