@coffer-org/server 3.4.0 → 4.0.0

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 (98) hide show
  1. package/dist/auth-api.js +4 -5
  2. package/dist/cache-clock.d.ts +8 -0
  3. package/dist/cache-clock.js +103 -0
  4. package/dist/cache-refresh.d.ts +7 -0
  5. package/dist/cache-refresh.js +322 -0
  6. package/dist/collection-io.d.ts +13 -0
  7. package/dist/collection-io.js +40 -29
  8. package/dist/compute-unit.d.ts +66 -0
  9. package/dist/compute-unit.js +369 -0
  10. package/dist/condition-where.js +1 -3
  11. package/dist/data-dir.d.ts +3 -0
  12. package/dist/data-dir.js +39 -0
  13. package/dist/entity-schema.js +5 -2
  14. package/dist/extend-table.d.ts +1 -1
  15. package/dist/extend-table.js +22 -8
  16. package/dist/file-fields.js +50 -23
  17. package/dist/global-search.js +1 -1
  18. package/dist/index.js +20 -26
  19. package/dist/mcp-contract/client.d.ts +24 -0
  20. package/dist/mcp-contract/client.js +12 -0
  21. package/dist/mcp-contract/schema.d.ts +46 -0
  22. package/dist/mcp-contract/schema.js +90 -0
  23. package/dist/mcp-contract/tools.d.ts +19 -0
  24. package/dist/mcp-contract/tools.js +160 -0
  25. package/dist/mcp-local.d.ts +1 -1
  26. package/dist/mcp-local.js +1 -1
  27. package/dist/mcp-tools.d.ts +12 -1
  28. package/dist/mcp-tools.js +41 -8
  29. package/dist/migrations.d.ts +5 -0
  30. package/dist/migrations.js +122 -0
  31. package/dist/mutate.js +77 -36
  32. package/dist/orchestrator/agent-capabilities.d.ts +2 -0
  33. package/dist/orchestrator/agent-capabilities.js +201 -0
  34. package/dist/orchestrator/allow.d.ts +16 -0
  35. package/dist/orchestrator/allow.js +65 -0
  36. package/dist/orchestrator/attachments.d.ts +2 -0
  37. package/dist/orchestrator/attachments.js +11 -0
  38. package/dist/orchestrator/config.d.ts +4 -0
  39. package/dist/orchestrator/config.js +19 -0
  40. package/dist/orchestrator/db.d.ts +17 -0
  41. package/dist/orchestrator/db.js +12 -0
  42. package/dist/orchestrator/diagnostics.d.ts +9 -0
  43. package/dist/orchestrator/diagnostics.js +13 -0
  44. package/dist/orchestrator/environment.d.ts +3 -0
  45. package/dist/orchestrator/environment.js +30 -0
  46. package/dist/orchestrator/file-inspection.d.ts +3 -0
  47. package/dist/orchestrator/file-inspection.js +61 -0
  48. package/dist/orchestrator/format.d.ts +1 -0
  49. package/dist/orchestrator/format.js +6 -0
  50. package/dist/orchestrator/index.d.ts +30 -0
  51. package/dist/orchestrator/index.js +56 -0
  52. package/dist/orchestrator/live-message.d.ts +14 -0
  53. package/dist/orchestrator/live-message.js +100 -0
  54. package/dist/orchestrator/pipeline.d.ts +11 -0
  55. package/dist/orchestrator/pipeline.js +198 -0
  56. package/dist/orchestrator/registry.d.ts +13 -0
  57. package/dist/orchestrator/registry.js +74 -0
  58. package/dist/orchestrator/starters.d.ts +19 -0
  59. package/dist/orchestrator/starters.js +81 -0
  60. package/dist/orchestrator/suggestion-capabilities.d.ts +5 -0
  61. package/dist/orchestrator/suggestion-capabilities.js +33 -0
  62. package/dist/orchestrator/system-assembly.d.ts +7 -0
  63. package/dist/orchestrator/system-assembly.js +13 -0
  64. package/dist/orchestrator/system-capabilities.d.ts +2 -0
  65. package/dist/orchestrator/system-capabilities.js +63 -0
  66. package/dist/orchestrator/types.d.ts +144 -0
  67. package/dist/orchestrator/types.js +1 -0
  68. package/dist/part-injection.d.ts +3 -4
  69. package/dist/part-injection.js +25 -368
  70. package/dist/plugin-hooks.d.ts +1 -0
  71. package/dist/plugin-i18n.js +2 -1
  72. package/dist/plugin-runtime.d.ts +2 -2
  73. package/dist/plugin-runtime.js +20 -11
  74. package/dist/plugin-updates.d.ts +2 -2
  75. package/dist/plugin-updates.js +6 -12
  76. package/dist/public-url.js +2 -1
  77. package/dist/recompute-derived.d.ts +2 -1
  78. package/dist/recompute-derived.js +111 -34
  79. package/dist/records-api.js +14 -16
  80. package/dist/registry-context.d.ts +1 -1
  81. package/dist/registry-context.js +3 -0
  82. package/dist/search-index.js +1 -1
  83. package/dist/search-indexer.d.ts +1 -1
  84. package/dist/search-indexer.js +3 -3
  85. package/dist/settings-groups.d.ts +14 -0
  86. package/dist/settings-groups.js +25 -0
  87. package/dist/settings-write.d.ts +4 -4
  88. package/dist/settings-write.js +23 -26
  89. package/dist/system-settings.d.ts +3 -0
  90. package/dist/system-settings.js +27 -0
  91. package/dist/thread-store.d.ts +3 -2
  92. package/dist/thread-store.js +6 -5
  93. package/dist/trigger-queue.d.ts +33 -0
  94. package/dist/trigger-queue.js +432 -0
  95. package/dist/uploads.js +6 -3
  96. package/dist/value-compare.d.ts +1 -0
  97. package/dist/value-compare.js +7 -0
  98. package/package.json +17 -3
@@ -0,0 +1,198 @@
1
+ import { loadAllowed, saveAllowed, isAllowed, addAllowed, makeThrottle, allowFileFor } from "./allow.js";
2
+ import { loadAgentId, loadGatePolicy } from "./config.js";
3
+ import { buildSystem } from "./system-assembly.js";
4
+ import { attachmentMaterializer } from "./attachments.js";
5
+ import { makeAttachmentCapabilities } from "./agent-capabilities.js";
6
+ import { makeSystemCapabilities } from "./system-capabilities.js";
7
+ import { makeSuggestionCapabilities } from "./suggestion-capabilities.js";
8
+ import { resolveAgent } from "./registry.js";
9
+ import { recordDiagnostic } from "./diagnostics.js";
10
+ import { getLogger } from '@coffer-org/sdk/logger';
11
+ const log = getLogger('orchestrator');
12
+ let logDb;
13
+ export function setLogDb(db) {
14
+ logDb = db;
15
+ }
16
+ const throttleByConnector = new Map();
17
+ function passThrottle(connectorId) {
18
+ let t = throttleByConnector.get(connectorId);
19
+ if (!t) {
20
+ t = makeThrottle(5, 60_000);
21
+ throttleByConnector.set(connectorId, t);
22
+ }
23
+ return t;
24
+ }
25
+ let cachedBase;
26
+ let cachedBaseAgentId;
27
+ function cachedAgentBase() {
28
+ const runtime = resolveAgent();
29
+ if (cachedBaseAgentId !== runtime.id) {
30
+ cachedBaseAgentId = runtime.id;
31
+ cachedBase = runtime.systemBase();
32
+ }
33
+ return cachedBase;
34
+ }
35
+ function openChannel(connector, chatId, ctx) {
36
+ try {
37
+ return connector.reply(chatId, ctx);
38
+ }
39
+ catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ log.error(`connector error in reply: ${message}`);
42
+ recordDiagnostic('error', 'connector.reply', message);
43
+ return null;
44
+ }
45
+ }
46
+ async function safeCall(fn, fallback, label) {
47
+ try {
48
+ return await fn();
49
+ }
50
+ catch (err) {
51
+ const message = err instanceof Error ? err.message : String(err);
52
+ log.error(`connector error in ${label}: ${message}`);
53
+ recordDiagnostic('error', `connector.${label}`, message);
54
+ return fallback;
55
+ }
56
+ }
57
+ export async function handleIncoming(connector, conversation, deps) {
58
+ const policy = deps?.policy ?? (await loadGatePolicy());
59
+ const selectedAgentId = conversation.agentId ?? policy.agentId ?? (deps?.runAgent ? undefined : await loadAgentId());
60
+ const runtime = deps?.runAgent ? undefined : resolveAgent(selectedAgentId);
61
+ const agent = deps?.runAgent ?? runtime.run.bind(runtime);
62
+ const db = deps && 'logDb' in deps ? deps.logDb : logDb;
63
+ const agentBase = deps?.agentBase ?? (() => (selectedAgentId ? runtime.systemBase() : cachedAgentBase()));
64
+ const { connectorId, chatId, sender, messages } = conversation;
65
+ const last = messages[messages.length - 1];
66
+ if (!last || last.role !== 'user')
67
+ return;
68
+ const incomingMsgId = last.msgId;
69
+ const allowFile = allowFileFor(connectorId);
70
+ if (policy.accessPassword) {
71
+ let allow = loadAllowed(allowFile);
72
+ if (!isAllowed(allow, sender.id)) {
73
+ if (last.content.trim() === policy.accessPassword) {
74
+ allow = addAllowed(allow, sender.id, Date.now());
75
+ saveAllowed(allowFile, allow);
76
+ const ch = openChannel(connector, chatId, { parentMsgId: incomingMsgId });
77
+ if (ch)
78
+ await safeCall(() => ch.finish({ text: '✅ Access granted. Send your requests.', reasoning: null, suggestions: null }), null, 'finish(enroll)');
79
+ }
80
+ else if (passThrottle(connectorId)(sender.id)) {
81
+ const ch = openChannel(connector, chatId, { parentMsgId: incomingMsgId });
82
+ if (ch)
83
+ await safeCall(() => ch.finish({
84
+ text: '🔒 Access locked. Send the password to gain access.',
85
+ reasoning: null,
86
+ suggestions: null,
87
+ }), null, 'finish(locked)');
88
+ }
89
+ return;
90
+ }
91
+ }
92
+ if (policy.triggerPrefix && !last.content.toLowerCase().startsWith(policy.triggerPrefix.toLowerCase()))
93
+ return;
94
+ const queryText = policy.triggerPrefix ? last.content.slice(policy.triggerPrefix.length).trim() : last.content.trim();
95
+ if (!queryText) {
96
+ if (conversation.prepareAttachments && !policy.triggerPrefix) {
97
+ await safeCall(() => conversation.prepareAttachments(attachmentMaterializer), messages, 'prepareAttachments');
98
+ }
99
+ return;
100
+ }
101
+ const preparedMessages = conversation.prepareAttachments
102
+ ? await safeCall(() => conversation.prepareAttachments(attachmentMaterializer), messages, 'prepareAttachments')
103
+ : messages;
104
+ const agentMessages = policy.triggerPrefix
105
+ ? preparedMessages.map((m, i) => (i === preparedMessages.length - 1 ? { ...m, content: queryText } : m))
106
+ : preparedMessages;
107
+ const base = await agentBase();
108
+ const system = buildSystem({
109
+ base,
110
+ channelSystem: conversation.channelSystem,
111
+ volatileSystem: conversation.volatileSystem,
112
+ });
113
+ db?.logTurn({
114
+ connector: connectorId,
115
+ chatId,
116
+ userId: sender.id,
117
+ role: 'user',
118
+ text: queryText,
119
+ tokensIn: null,
120
+ tokensOut: null,
121
+ ms: null,
122
+ agentId: selectedAgentId ?? null,
123
+ presetId: conversation.presetId ?? null,
124
+ });
125
+ const startedAt = Date.now();
126
+ const ch = openChannel(connector, chatId, { parentMsgId: incomingMsgId });
127
+ if (!ch)
128
+ return;
129
+ let result;
130
+ const suggestionCaps = conversation.supportsSuggestions ? makeSuggestionCapabilities() : undefined;
131
+ try {
132
+ const attachmentTools = await makeAttachmentCapabilities(agentMessages.flatMap((m) => m.attachments ?? []));
133
+ const toolProvider = {
134
+ tools: [...attachmentTools.tools, ...makeSystemCapabilities().tools, ...(suggestionCaps?.tools ?? [])],
135
+ };
136
+ result = await agent({
137
+ system,
138
+ messages: agentMessages,
139
+ toolProvider,
140
+ ...(conversation.presetId ? { presetId: conversation.presetId } : {}),
141
+ onDelta: (acc) => {
142
+ try {
143
+ ch.update(acc);
144
+ }
145
+ catch (err) {
146
+ log.error(`connector error in update: ${err instanceof Error ? err.message : String(err)}`);
147
+ }
148
+ },
149
+ onReasoning: (acc) => {
150
+ try {
151
+ ch.updateReasoning?.(acc);
152
+ }
153
+ catch (err) {
154
+ log.error(`connector error in updateReasoning: ${err instanceof Error ? err.message : String(err)}`);
155
+ }
156
+ },
157
+ onSegment: () => {
158
+ try {
159
+ ch.segment();
160
+ }
161
+ catch (err) {
162
+ log.error(`connector error in segment: ${err instanceof Error ? err.message : String(err)}`);
163
+ }
164
+ },
165
+ });
166
+ }
167
+ catch (err) {
168
+ const message = err instanceof Error ? err.message : String(err);
169
+ log.error(`agent error: ${message}`);
170
+ recordDiagnostic('error', 'agent.run', message);
171
+ }
172
+ if (result && suggestionCaps)
173
+ result.suggestions = suggestionCaps.getCaptured();
174
+ const botMsgId = await safeCall(() => ch.finish({
175
+ text: result?.text ?? null,
176
+ reasoning: result?.reasoning ?? null,
177
+ suggestions: result?.suggestions ?? null,
178
+ }), null, 'finish');
179
+ if (result?.text)
180
+ db?.logTurn({
181
+ connector: connectorId,
182
+ chatId,
183
+ userId: sender.id,
184
+ role: 'assistant',
185
+ text: result.text,
186
+ tokensIn: result.tokensIn,
187
+ tokensOut: result.tokensOut,
188
+ ms: Date.now() - startedAt,
189
+ agentId: selectedAgentId ?? null,
190
+ presetId: result.presetId,
191
+ });
192
+ await safeCall(() => connector.recordAssistant({
193
+ parentMsgId: incomingMsgId,
194
+ botMsgId,
195
+ text: result?.text ?? '',
196
+ reasoning: result?.reasoning ?? null,
197
+ }), undefined, 'recordAssistant');
198
+ }
@@ -0,0 +1,13 @@
1
+ import type { AgentDescriptor, AgentRuntime, ConnectorRegistration } from './types.ts';
2
+ export declare function registerAgent(runtime: AgentRuntime, opts?: {
3
+ default?: boolean;
4
+ }): () => void;
5
+ export declare function resolveAgent(id?: string): AgentRuntime;
6
+ export declare function liveAgentId(agentId: string | null | undefined): string | undefined;
7
+ export declare function registerConnector(registration: ConnectorRegistration): () => void;
8
+ export declare function isConnectorRegistered(id: string): boolean;
9
+ export declare function listRegisteredAgents(): string[];
10
+ export declare function listRegisteredConnectors(): string[];
11
+ export declare function listAgentCatalog(): Promise<AgentDescriptor[]>;
12
+ export declare function getDefaultAgentId(): string | undefined;
13
+ export declare function clearRuntimeRegistries(): void;
@@ -0,0 +1,74 @@
1
+ import { getLogger } from '@coffer-org/sdk/logger';
2
+ const log = getLogger('orchestrator');
3
+ const agents = new Map();
4
+ const connectors = new Map();
5
+ let defaultAgentId;
6
+ export function registerAgent(runtime, opts = {}) {
7
+ const current = agents.get(runtime.id);
8
+ if (current && current !== runtime)
9
+ throw new Error(`agent already registered: ${runtime.id}`);
10
+ agents.set(runtime.id, runtime);
11
+ if (opts.default || !defaultAgentId)
12
+ defaultAgentId = runtime.id;
13
+ return () => unregisterAgent(runtime.id, runtime);
14
+ }
15
+ function unregisterAgent(id, expected) {
16
+ if (agents.get(id) !== expected)
17
+ return;
18
+ agents.delete(id);
19
+ if (defaultAgentId === id)
20
+ defaultAgentId = agents.keys().next().value;
21
+ }
22
+ export function resolveAgent(id) {
23
+ const key = id ?? defaultAgentId;
24
+ const runtime = key ? agents.get(key) : undefined;
25
+ if (!runtime)
26
+ throw new Error(id ? `agent is not registered: ${id}` : 'no agent is registered');
27
+ return runtime;
28
+ }
29
+ export function liveAgentId(agentId) {
30
+ return agentId && agents.has(agentId) ? agentId : undefined;
31
+ }
32
+ export function registerConnector(registration) {
33
+ const current = connectors.get(registration.id);
34
+ if (current && current !== registration)
35
+ throw new Error(`connector already registered: ${registration.id}`);
36
+ connectors.set(registration.id, registration);
37
+ return () => {
38
+ if (connectors.get(registration.id) === registration)
39
+ connectors.delete(registration.id);
40
+ };
41
+ }
42
+ export function isConnectorRegistered(id) {
43
+ return connectors.has(id);
44
+ }
45
+ export function listRegisteredAgents() {
46
+ return [...agents.keys()].sort();
47
+ }
48
+ export function listRegisteredConnectors() {
49
+ return [...connectors.keys()].sort();
50
+ }
51
+ export async function listAgentCatalog() {
52
+ const ids = [...agents.keys()].sort();
53
+ const out = [];
54
+ for (const id of ids) {
55
+ const runtime = agents.get(id);
56
+ if (!runtime)
57
+ continue;
58
+ try {
59
+ out.push(await runtime.describe());
60
+ }
61
+ catch (err) {
62
+ log.error(`agent describe failed for ${id}: ${err instanceof Error ? err.message : String(err)}`);
63
+ }
64
+ }
65
+ return out;
66
+ }
67
+ export function getDefaultAgentId() {
68
+ return defaultAgentId;
69
+ }
70
+ export function clearRuntimeRegistries() {
71
+ agents.clear();
72
+ connectors.clear();
73
+ defaultAgentId = undefined;
74
+ }
@@ -0,0 +1,19 @@
1
+ import { getPluginSettings } from '../plugin-runtime.ts';
2
+ import { getPluginState, setPluginState } from '../plugin-state.ts';
3
+ import { collectStarterHints } from '../mcp-tools.ts';
4
+ import { loadAgentId } from './config.ts';
5
+ import { getDefaultAgentId } from './registry.ts';
6
+ import type { AgentRuntime } from './types.ts';
7
+ export interface StartersDeps {
8
+ getPluginSettings: typeof getPluginSettings;
9
+ getPluginState: typeof getPluginState;
10
+ setPluginState: typeof setPluginState;
11
+ collectStarterHints: typeof collectStarterHints;
12
+ loadAgentId: typeof loadAgentId;
13
+ resolveAgent: (id?: string) => AgentRuntime;
14
+ getDefaultAgentId: typeof getDefaultAgentId;
15
+ today: () => string;
16
+ now: () => string;
17
+ }
18
+ export declare function getConversationStarters(deps?: StartersDeps): Promise<string[]>;
19
+ export declare function refreshSystemStarters(deps?: StartersDeps): Promise<void>;
@@ -0,0 +1,81 @@
1
+ import { getPluginSettings } from "../plugin-runtime.js";
2
+ import { SYSTEM_SETTINGS_ID } from "../system-settings.js";
3
+ import { getPluginState, setPluginState } from "../plugin-state.js";
4
+ import { collectStarterHints } from "../mcp-tools.js";
5
+ import { getLogger } from '@coffer-org/sdk/logger';
6
+ import { todayDateString } from "./environment.js";
7
+ import { loadAgentId } from "./config.js";
8
+ import { resolveAgent, getDefaultAgentId } from "./registry.js";
9
+ const log = getLogger('orchestrator');
10
+ const PLUGIN = 'orchestrator';
11
+ const STATE_KEY = 'system_starters';
12
+ const defaultDeps = {
13
+ getPluginSettings,
14
+ getPluginState,
15
+ setPluginState,
16
+ collectStarterHints,
17
+ loadAgentId,
18
+ resolveAgent,
19
+ getDefaultAgentId,
20
+ today: todayDateString,
21
+ now: () => new Date().toISOString(),
22
+ };
23
+ async function currentLanguage(deps) {
24
+ const system = await deps.getPluginSettings(SYSTEM_SETTINGS_ID);
25
+ const v = system['language'];
26
+ return typeof v === 'string' && v ? v : 'en';
27
+ }
28
+ async function readCache(deps) {
29
+ const raw = await deps.getPluginState(PLUGIN, STATE_KEY);
30
+ if (!raw)
31
+ return null;
32
+ try {
33
+ return JSON.parse(raw);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ export async function getConversationStarters(deps = defaultDeps) {
40
+ return (await readCache(deps))?.starters ?? [];
41
+ }
42
+ export async function refreshSystemStarters(deps = defaultDeps) {
43
+ const date = deps.today();
44
+ const [language, hints] = await Promise.all([currentLanguage(deps), deps.collectStarterHints()]);
45
+ const agentId = (await deps.loadAgentId()) ?? deps.getDefaultAgentId();
46
+ if (!agentId)
47
+ return;
48
+ const cached = await readCache(deps);
49
+ if (cached &&
50
+ cached.date === date &&
51
+ cached.language === language &&
52
+ cached.hintsHash === hints.hash &&
53
+ cached.agentId === agentId) {
54
+ return;
55
+ }
56
+ let runtime;
57
+ try {
58
+ runtime = deps.resolveAgent(agentId);
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ if (!runtime.starters)
64
+ return;
65
+ let starters;
66
+ try {
67
+ starters = await runtime.starters();
68
+ }
69
+ catch (err) {
70
+ log.warn(`system starters generation failed: ${err instanceof Error ? err.message : String(err)}`);
71
+ return;
72
+ }
73
+ await deps.setPluginState(PLUGIN, STATE_KEY, JSON.stringify({
74
+ date,
75
+ language,
76
+ hintsHash: hints.hash,
77
+ agentId,
78
+ starters,
79
+ generatedAt: deps.now(),
80
+ }));
81
+ }
@@ -0,0 +1,5 @@
1
+ import type { AgentToolProvider } from './types.ts';
2
+ export interface SuggestionCapability extends AgentToolProvider {
3
+ getCaptured(): string[] | null;
4
+ }
5
+ export declare function makeSuggestionCapabilities(): SuggestionCapability;
@@ -0,0 +1,33 @@
1
+ const MAX_SUGGESTIONS = 4;
2
+ export function makeSuggestionCapabilities() {
3
+ let captured = null;
4
+ const tool = {
5
+ name: 'suggest_replies',
6
+ description: 'You have already given your final answer, shown above. Propose 2-4 short, concrete follow-up replies in ' +
7
+ "the user's own language that a user might plausibly send next — grounded in what you ACTUALLY wrote, not " +
8
+ 'generic filler. If your answer ended with a question, one suggestion should directly answer that exact ' +
9
+ 'question. If your answer named specific items (a record, a recipe, a place), prefer a suggestion that ' +
10
+ 'references one of them by name over a vague "tell me more". Call this once; skip it entirely if nothing ' +
11
+ 'concrete fits — it does not change your answer, it only offers the user clickable shortcuts.',
12
+ inputSchema: {
13
+ suggestions: {
14
+ type: 'array',
15
+ items: { type: 'string' },
16
+ description: '2-4 short reply options, grounded in the answer above, in the language of the conversation.',
17
+ },
18
+ },
19
+ forcedAfterAnswer: true,
20
+ handler: async (args) => {
21
+ const raw = args['suggestions'];
22
+ const list = Array.isArray(raw)
23
+ ? raw
24
+ .map((v) => String(v).trim())
25
+ .filter((v) => v.length > 0)
26
+ .slice(0, MAX_SUGGESTIONS)
27
+ : [];
28
+ captured = list.length ? list : null;
29
+ return { ok: true };
30
+ },
31
+ };
32
+ return { tools: [tool], getCaptured: () => captured };
33
+ }
@@ -0,0 +1,7 @@
1
+ import type { SystemLayer } from './types.ts';
2
+ export declare function buildSystem(input: {
3
+ base: string;
4
+ channelSystem?: string;
5
+ volatileSystem?: string;
6
+ environment?: string;
7
+ }): SystemLayer[];
@@ -0,0 +1,13 @@
1
+ import { currentEnvironment } from "./environment.js";
2
+ export function buildSystem(input) {
3
+ const text = [input.base, input.channelSystem].filter(Boolean).join('\n\n');
4
+ const layers = [{ text, stable: true }];
5
+ const environment = input.environment ?? currentEnvironment();
6
+ const volatile = [environment, input.volatileSystem]
7
+ .map((part) => part?.trim())
8
+ .filter(Boolean)
9
+ .join('\n\n');
10
+ if (volatile)
11
+ layers.push({ text: volatile, stable: false });
12
+ return layers;
13
+ }
@@ -0,0 +1,2 @@
1
+ import type { AgentToolProvider } from './types.ts';
2
+ export declare function makeSystemCapabilities(): AgentToolProvider;
@@ -0,0 +1,63 @@
1
+ import { stat, statfs } from 'node:fs/promises';
2
+ import { arch, freemem, platform, totalmem } from 'node:os';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { discoverRuntime } from "../plugin-discovery.js";
5
+ import { systemTimeZone } from "./environment.js";
6
+ const mb = (bytes) => Math.round(bytes / 1024 / 1024);
7
+ function databasePath() {
8
+ return resolve(process.env['DB_PATH'] ?? 'data/app.db');
9
+ }
10
+ async function databaseState() {
11
+ const path = databasePath();
12
+ const out = { path };
13
+ try {
14
+ out['size_mb'] = mb((await stat(path)).size);
15
+ }
16
+ catch {
17
+ out['size_mb'] = null;
18
+ }
19
+ try {
20
+ const fs = await statfs(dirname(path));
21
+ out['disk_free_mb'] = mb(Number(fs.bavail) * Number(fs.bsize));
22
+ out['disk_total_mb'] = mb(Number(fs.blocks) * Number(fs.bsize));
23
+ }
24
+ catch {
25
+ out['disk_free_mb'] = null;
26
+ out['disk_total_mb'] = null;
27
+ }
28
+ return out;
29
+ }
30
+ async function runtimeVersion() {
31
+ try {
32
+ return (await discoverRuntime())?.installedVersion ?? null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ export function makeSystemCapabilities() {
39
+ const serverState = {
40
+ name: 'mcp__coffer__server_state',
41
+ description: 'Health and identity of the Coffer server this assistant runs on: installed version, uptime, Node version, ' +
42
+ 'platform, memory, and the database file path with its size and free disk space. ' +
43
+ 'Use it for questions about the instance itself ("which version am I running", "is the disk filling up", ' +
44
+ '"how long has the server been up"). It returns nothing about the user\'s records — use count_records for those. ' +
45
+ 'The current date and time are already given in the system prompt; do not call this tool to find them.',
46
+ inputSchema: {},
47
+ handler: async () => ({
48
+ coffer_version: await runtimeVersion(),
49
+ uptime_seconds: Math.round(process.uptime()),
50
+ node_version: process.version,
51
+ platform: platform(),
52
+ arch: arch(),
53
+ timezone: systemTimeZone(),
54
+ memory: {
55
+ total_mb: mb(totalmem()),
56
+ free_mb: mb(freemem()),
57
+ process_rss_mb: mb(process.memoryUsage().rss),
58
+ },
59
+ database: await databaseState(),
60
+ }),
61
+ };
62
+ return { tools: [serverState] };
63
+ }
@@ -0,0 +1,144 @@
1
+ export interface AttachmentRef {
2
+ name: string;
3
+ mime?: string;
4
+ size?: number;
5
+ label?: string;
6
+ }
7
+ export interface AgentToolDefinition {
8
+ name: string;
9
+ description: string;
10
+ inputSchema: Record<string, unknown>;
11
+ handler: (args: Record<string, unknown>) => Promise<unknown>;
12
+ forcedAfterAnswer?: boolean;
13
+ }
14
+ export interface AgentToolProvider {
15
+ tools: AgentToolDefinition[];
16
+ }
17
+ export type AgentToolContentBlock = {
18
+ type: 'text';
19
+ text: string;
20
+ } | {
21
+ type: 'image';
22
+ mime: string;
23
+ data: string;
24
+ } | {
25
+ type: 'document';
26
+ mime: 'application/pdf';
27
+ data: string;
28
+ };
29
+ export interface AgentToolContentResult {
30
+ __cofferToolContent: true;
31
+ content: AgentToolContentBlock[];
32
+ isError?: boolean;
33
+ }
34
+ export interface ConvMessage {
35
+ role: 'user' | 'assistant';
36
+ content: string;
37
+ attachments?: AttachmentRef[];
38
+ sender?: string | null;
39
+ msgId: string;
40
+ ts: number;
41
+ }
42
+ export interface SystemLayer {
43
+ text: string;
44
+ stable: boolean;
45
+ }
46
+ export interface AgentCapabilities {
47
+ vision?: boolean;
48
+ documents?: boolean;
49
+ tools?: boolean;
50
+ reasoning?: boolean;
51
+ }
52
+ export interface AgentPreset {
53
+ id: string;
54
+ title: string;
55
+ hint?: string;
56
+ quality?: number;
57
+ time?: number;
58
+ default?: boolean;
59
+ capabilities?: AgentCapabilities;
60
+ }
61
+ export interface AgentDescriptor {
62
+ id: string;
63
+ title: string;
64
+ presets: AgentPreset[];
65
+ }
66
+ export interface AgentRequest {
67
+ system: SystemLayer[];
68
+ messages: ConvMessage[];
69
+ toolProvider?: AgentToolProvider;
70
+ presetId?: string;
71
+ onDelta?: (accumulated: string) => void;
72
+ onReasoning?: (accumulated: string) => void;
73
+ onSegment?: () => void;
74
+ }
75
+ export interface AgentResult {
76
+ text: string | null;
77
+ reasoning: string | null;
78
+ tokensIn: number | null;
79
+ tokensOut: number | null;
80
+ stopReason: string | null;
81
+ presetId: string | null;
82
+ suggestions?: string[] | null;
83
+ }
84
+ export interface AgentRuntime {
85
+ id: string;
86
+ run(request: AgentRequest): Promise<AgentResult>;
87
+ systemBase(): Promise<string>;
88
+ describe(): Promise<AgentDescriptor>;
89
+ starters?(): Promise<string[]>;
90
+ }
91
+ export interface ConnectorRegistration {
92
+ id: string;
93
+ }
94
+ export interface AttachmentMaterializer {
95
+ store(bytes: Uint8Array, opts?: {
96
+ originalName?: string;
97
+ mime?: string;
98
+ }): Promise<AttachmentRef>;
99
+ }
100
+ export interface IncomingConversation {
101
+ connectorId: string;
102
+ agentId?: string;
103
+ presetId?: string;
104
+ chatId: string;
105
+ channelSystem?: string;
106
+ volatileSystem?: string;
107
+ sender: {
108
+ id: string;
109
+ displayName?: string;
110
+ };
111
+ messages: ConvMessage[];
112
+ prepareAttachments?: (materializer: AttachmentMaterializer) => Promise<ConvMessage[]>;
113
+ supportsSuggestions?: boolean;
114
+ }
115
+ export interface ReplyContext {
116
+ parentMsgId: string | null;
117
+ }
118
+ export interface ReplyPayload {
119
+ text: string | null;
120
+ reasoning: string | null;
121
+ suggestions: string[] | null;
122
+ }
123
+ export interface ReplyChannel {
124
+ update(text: string): void;
125
+ updateReasoning?(acc: string): void;
126
+ segment(): void;
127
+ finish(r: ReplyPayload): Promise<string | null>;
128
+ }
129
+ export interface Connector {
130
+ id: string;
131
+ reply(chatId: string, ctx: ReplyContext): ReplyChannel;
132
+ recordAssistant(m: {
133
+ parentMsgId: string | null;
134
+ botMsgId: string | null;
135
+ text: string;
136
+ reasoning: string | null;
137
+ }): Promise<void>;
138
+ }
139
+ export interface GatePolicy {
140
+ agentId?: string;
141
+ accessPassword: string;
142
+ triggerPrefix: string;
143
+ replyWindow: number;
144
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,7 @@
1
1
  import type { EntityManager } from '@mikro-orm/core';
2
2
  import { type LayoutEl } from '@coffer-org/sdk/fields';
3
- import { type RefState } from './part-ref.ts';
4
- type Row = Record<string, unknown>;
3
+ import type { RefState } from './part-ref.ts';
4
+ import { type Row } from './compute-unit.ts';
5
5
  export type PartMemo = Map<string, unknown>;
6
6
  export declare const newPartMemo: () => PartMemo;
7
7
  export interface PartCtx {
@@ -14,8 +14,7 @@ export interface PartCtx {
14
14
  em?: EntityManager;
15
15
  memo?: PartMemo;
16
16
  refs?: RefState;
17
+ now?: string;
17
18
  }
18
- export declare function injectParts(fields: LayoutEl[], row: Row, ctx: PartCtx): Promise<Row>;
19
19
  export declare function hasStoredPartWork(fields: LayoutEl[]): boolean;
20
20
  export declare function applyStoredParts(fields: LayoutEl[], row: Row, ctx: PartCtx): Promise<Row>;
21
- export {};