@coffer-org/server 3.4.0 → 5.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 (101) 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/frontend-agent.d.ts +1 -1
  18. package/dist/frontend-agent.js +2 -3
  19. package/dist/global-search.js +1 -1
  20. package/dist/index.js +20 -26
  21. package/dist/mcp-contract/client.d.ts +24 -0
  22. package/dist/mcp-contract/client.js +12 -0
  23. package/dist/mcp-contract/schema.d.ts +46 -0
  24. package/dist/mcp-contract/schema.js +90 -0
  25. package/dist/mcp-contract/tools.d.ts +19 -0
  26. package/dist/mcp-contract/tools.js +160 -0
  27. package/dist/mcp-http.js +4 -2
  28. package/dist/mcp-local.d.ts +1 -1
  29. package/dist/mcp-local.js +1 -1
  30. package/dist/mcp-tools.d.ts +13 -1
  31. package/dist/mcp-tools.js +46 -16
  32. package/dist/migrations.d.ts +5 -0
  33. package/dist/migrations.js +122 -0
  34. package/dist/mutate.js +77 -36
  35. package/dist/orchestrator/agent-capabilities.d.ts +2 -0
  36. package/dist/orchestrator/agent-capabilities.js +201 -0
  37. package/dist/orchestrator/allow.d.ts +16 -0
  38. package/dist/orchestrator/allow.js +65 -0
  39. package/dist/orchestrator/attachments.d.ts +2 -0
  40. package/dist/orchestrator/attachments.js +11 -0
  41. package/dist/orchestrator/config.d.ts +4 -0
  42. package/dist/orchestrator/config.js +19 -0
  43. package/dist/orchestrator/db.d.ts +17 -0
  44. package/dist/orchestrator/db.js +12 -0
  45. package/dist/orchestrator/diagnostics.d.ts +9 -0
  46. package/dist/orchestrator/diagnostics.js +13 -0
  47. package/dist/orchestrator/environment.d.ts +2 -0
  48. package/dist/orchestrator/environment.js +14 -0
  49. package/dist/orchestrator/file-inspection.d.ts +3 -0
  50. package/dist/orchestrator/file-inspection.js +61 -0
  51. package/dist/orchestrator/format.d.ts +1 -0
  52. package/dist/orchestrator/format.js +6 -0
  53. package/dist/orchestrator/index.d.ts +30 -0
  54. package/dist/orchestrator/index.js +56 -0
  55. package/dist/orchestrator/live-message.d.ts +14 -0
  56. package/dist/orchestrator/live-message.js +100 -0
  57. package/dist/orchestrator/pipeline.d.ts +11 -0
  58. package/dist/orchestrator/pipeline.js +198 -0
  59. package/dist/orchestrator/registry.d.ts +13 -0
  60. package/dist/orchestrator/registry.js +74 -0
  61. package/dist/orchestrator/starters.d.ts +19 -0
  62. package/dist/orchestrator/starters.js +81 -0
  63. package/dist/orchestrator/suggestion-capabilities.d.ts +5 -0
  64. package/dist/orchestrator/suggestion-capabilities.js +33 -0
  65. package/dist/orchestrator/system-assembly.d.ts +4 -0
  66. package/dist/orchestrator/system-assembly.js +3 -0
  67. package/dist/orchestrator/system-capabilities.d.ts +2 -0
  68. package/dist/orchestrator/system-capabilities.js +63 -0
  69. package/dist/orchestrator/types.d.ts +141 -0
  70. package/dist/orchestrator/types.js +1 -0
  71. package/dist/part-injection.d.ts +3 -4
  72. package/dist/part-injection.js +25 -368
  73. package/dist/plugin-hooks.d.ts +1 -0
  74. package/dist/plugin-i18n.js +2 -1
  75. package/dist/plugin-runtime.d.ts +2 -2
  76. package/dist/plugin-runtime.js +20 -11
  77. package/dist/plugin-updates.d.ts +2 -2
  78. package/dist/plugin-updates.js +6 -12
  79. package/dist/public-url.js +2 -1
  80. package/dist/recompute-derived.d.ts +2 -1
  81. package/dist/recompute-derived.js +111 -34
  82. package/dist/records-api.js +14 -16
  83. package/dist/registry-context.d.ts +1 -1
  84. package/dist/registry-context.js +3 -0
  85. package/dist/search-index.js +1 -1
  86. package/dist/search-indexer.d.ts +1 -1
  87. package/dist/search-indexer.js +3 -3
  88. package/dist/settings-groups.d.ts +14 -0
  89. package/dist/settings-groups.js +25 -0
  90. package/dist/settings-write.d.ts +4 -4
  91. package/dist/settings-write.js +23 -26
  92. package/dist/system-settings.d.ts +3 -0
  93. package/dist/system-settings.js +27 -0
  94. package/dist/thread-store.d.ts +3 -2
  95. package/dist/thread-store.js +6 -5
  96. package/dist/trigger-queue.d.ts +33 -0
  97. package/dist/trigger-queue.js +432 -0
  98. package/dist/uploads.js +6 -3
  99. package/dist/value-compare.d.ts +1 -0
  100. package/dist/value-compare.js +7 -0
  101. package/package.json +17 -3
@@ -0,0 +1,201 @@
1
+ import { collectMcpTools } from "../mcp-tools.js";
2
+ import { LocalClient } from "../mcp-local.js";
3
+ import { inspectUpload } from "./file-inspection.js";
4
+ const ok = (data) => ({
5
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
6
+ });
7
+ const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
8
+ function textOf(result) {
9
+ const block = result.content.find((b) => b.type === 'text');
10
+ return block?.type === 'text' ? block.text : '';
11
+ }
12
+ function resultData(result) {
13
+ try {
14
+ return JSON.parse(textOf(result));
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ function fieldType(items, key) {
21
+ for (const item of items) {
22
+ if (!item || typeof item !== 'object')
23
+ continue;
24
+ const raw = item;
25
+ if (raw.key === key && raw.type)
26
+ return raw.type;
27
+ if (raw.kind === 'group' && Array.isArray(raw.fields)) {
28
+ const nested = fieldType(raw.fields, key);
29
+ if (nested)
30
+ return nested;
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ async function findFileField(library, shelf, key) {
36
+ const schema = (await new LocalClient().getSchema());
37
+ const lib = schema.find((item) => item.id === library);
38
+ const sh = lib?.shelves?.find((item) => item.shelf === shelf);
39
+ return sh?.fields ? fieldType(sh.fields, key) : undefined;
40
+ }
41
+ function parseStoredValue(value) {
42
+ if (typeof value !== 'string')
43
+ return value;
44
+ try {
45
+ return JSON.parse(value);
46
+ }
47
+ catch {
48
+ return value;
49
+ }
50
+ }
51
+ function fileItems(value) {
52
+ const parsed = parseStoredValue(value);
53
+ if (Array.isArray(parsed))
54
+ return parsed.filter((item) => !!item && typeof item === 'object');
55
+ return parsed && typeof parsed === 'object' ? [parsed] : [];
56
+ }
57
+ function findTool(defs, name) {
58
+ return defs.find((def) => def.server === 'coffer' && def.bareName === name);
59
+ }
60
+ export async function makeAttachmentCapabilities(attachments) {
61
+ const defs = await collectMcpTools();
62
+ const getRecord = findTool(defs, 'get_record');
63
+ const updateRecord = findTool(defs, 'update_record');
64
+ const tools = [];
65
+ if (getRecord) {
66
+ tools.push({
67
+ name: 'mcp__coffer__inspect_record_file',
68
+ description: 'Read an existing file/image/PDF/text item stored in a Coffer record. ' +
69
+ 'Call get_record first, then pass the exact file name from the field value. ' +
70
+ 'Do not use local paths or URLs. If a field contains multiple files, file_name is required.',
71
+ inputSchema: {
72
+ library: { type: 'string', description: 'Library identifier, e.g. things' },
73
+ shelf: { type: 'string', description: 'Shelf identifier, e.g. item' },
74
+ id: { type: 'integer', description: 'Record id' },
75
+ field: { type: 'string', description: 'File/image/document field key' },
76
+ file_name: {
77
+ type: 'string',
78
+ description: 'Exact stored file name from get_record; required for multiple files',
79
+ },
80
+ },
81
+ handler: async (args) => {
82
+ const library = String(args['library'] ?? '');
83
+ const shelf = String(args['shelf'] ?? '');
84
+ const id = Number(args['id']);
85
+ const field = String(args['field'] ?? '');
86
+ if (!library || !shelf || !field || !Number.isInteger(id))
87
+ return fail('library, shelf, field and integer id are required');
88
+ const type = await findFileField(library, shelf, field);
89
+ if (!type || type.prim !== 'file')
90
+ return fail(`Field is not a file field: ${library}/${shelf}.${field}`);
91
+ const currentResult = await getRecord.handler({ library, shelf, id });
92
+ if (currentResult.isError)
93
+ return currentResult;
94
+ const current = resultData(currentResult);
95
+ if (!current || typeof current !== 'object')
96
+ return fail(`Record not found: ${library}/${shelf}/${id}`);
97
+ const existing = fileItems(current[field]);
98
+ if (!existing.length)
99
+ return fail(`Record field is empty: ${library}/${shelf}/${id}.${field}`);
100
+ const requested = typeof args['file_name'] === 'string' ? args['file_name'] : '';
101
+ const item = requested
102
+ ? existing.find((entry) => entry['name'] === requested)
103
+ : existing.length === 1
104
+ ? existing[0]
105
+ : undefined;
106
+ if (!item || typeof item['name'] !== 'string') {
107
+ const available = existing
108
+ .map((entry) => String(entry['name'] ?? ''))
109
+ .filter(Boolean)
110
+ .join(', ');
111
+ return fail(existing.length > 1
112
+ ? `Multiple files are stored in this field; file_name is required. Available: ${available}`
113
+ : `Stored file was not found in record field: ${requested}`);
114
+ }
115
+ return inspectUpload(item['name'], {
116
+ ...(typeof item['mime'] === 'string' ? { mime: item['mime'] } : {}),
117
+ ...(typeof item['size'] === 'number' ? { size: item['size'] } : {}),
118
+ });
119
+ },
120
+ });
121
+ }
122
+ if (!attachments.length || !getRecord || !updateRecord)
123
+ return { tools };
124
+ const attach = {
125
+ name: 'mcp__coffer__attach_conversation_attachments',
126
+ description: 'Attach files already received in the current conversation to a file/image/document field in a Coffer record. ' +
127
+ 'Use attachment_names for selected files, or omit it to attach every current-conversation attachment. ' +
128
+ 'The default mode appends to a multiple field; use mode="replace" only when explicitly requested. ' +
129
+ 'This is the unified attachment tool for every connector — never use a local path or invent an upload name.',
130
+ inputSchema: {
131
+ library: { type: 'string', description: 'Library identifier, e.g. things' },
132
+ shelf: { type: 'string', description: 'Shelf identifier, e.g. item' },
133
+ id: { type: 'integer', description: 'Record id' },
134
+ field: { type: 'string', description: 'File/image/document field key' },
135
+ attachment_names: {
136
+ type: 'array',
137
+ items: { type: 'string' },
138
+ description: 'Exact server-generated names from the current conversation; omit to use all attachments',
139
+ },
140
+ mode: {
141
+ type: 'string',
142
+ enum: ['append', 'replace'],
143
+ description: 'append by default; replace only on explicit request',
144
+ },
145
+ },
146
+ handler: async (args) => {
147
+ const library = String(args['library'] ?? '');
148
+ const shelf = String(args['shelf'] ?? '');
149
+ const id = Number(args['id']);
150
+ const field = String(args['field'] ?? '');
151
+ const mode = args['mode'] === 'replace' ? 'replace' : 'append';
152
+ if (!library || !shelf || !field || !Number.isInteger(id))
153
+ return fail('library, shelf, field and integer id are required');
154
+ const names = Array.isArray(args['attachment_names'])
155
+ ? args['attachment_names'].filter((name) => typeof name === 'string')
156
+ : attachments.map((item) => item.name);
157
+ const uniqueNames = [...new Set(names)];
158
+ const refs = uniqueNames.map((name) => attachments.find((item) => item.name === name));
159
+ if (refs.some((ref) => !ref)) {
160
+ const missing = uniqueNames.filter((name) => !attachments.some((item) => item.name === name));
161
+ return fail(`Attachment is not available in the current conversation: ${missing.join(', ')}`);
162
+ }
163
+ if (!refs.length)
164
+ return fail('No conversation attachments were selected');
165
+ const type = await findFileField(library, shelf, field);
166
+ if (!type || type.prim !== 'file')
167
+ return fail(`Field is not a file field: ${library}/${shelf}.${field}`);
168
+ const multiple = type.hints?.multiple === true;
169
+ const currentResult = await getRecord.handler({ library, shelf, id });
170
+ if (currentResult.isError)
171
+ return currentResult;
172
+ const current = resultData(currentResult);
173
+ if (!current || typeof current !== 'object')
174
+ return fail(`Record not found: ${library}/${shelf}/${id}`);
175
+ const existing = fileItems(current[field]);
176
+ const incoming = refs.map((ref) => ({ name: ref.name }));
177
+ if (!multiple && mode === 'append' && existing.length)
178
+ return fail(`Field already contains a file; use mode="replace" to replace it`);
179
+ if (!multiple && incoming.length > 1)
180
+ return fail(`Field accepts one file; select one attachment or use a multiple field`);
181
+ const next = mode === 'replace'
182
+ ? incoming
183
+ : [...existing, ...incoming.filter((item) => !existing.some((old) => old.name === item.name))];
184
+ const value = multiple ? next : (next[0] ?? null);
185
+ const updated = await updateRecord.handler({ library, shelf, id, fields: { [field]: value } });
186
+ if (updated.isError)
187
+ return updated;
188
+ return ok({
189
+ attached: incoming.map((item) => item.name),
190
+ mode,
191
+ library,
192
+ shelf,
193
+ id,
194
+ field,
195
+ record: resultData(updated),
196
+ });
197
+ },
198
+ };
199
+ tools.push(attach);
200
+ return { tools };
201
+ }
@@ -0,0 +1,16 @@
1
+ import type { GatePolicy } from './types.ts';
2
+ export declare const stateDir: () => string;
3
+ export declare function carryLegacyState(): void;
4
+ export declare function allowFileFor(connectorId: string): string;
5
+ export interface AllowState {
6
+ ids: Record<string, number>;
7
+ }
8
+ export declare function emptyAllowed(): AllowState;
9
+ export declare function loadAllowed(file: string): AllowState;
10
+ export declare function saveAllowed(file: string, state: AllowState): void;
11
+ export declare function isAllowed(state: AllowState, id: string | number | null | undefined): boolean;
12
+ export declare function addAllowed(state: AllowState, id: string | number, now: number): AllowState;
13
+ export declare function isSenderAllowed(connectorId: string, senderId: string, deps?: {
14
+ policy?: GatePolicy;
15
+ }): Promise<boolean>;
16
+ export declare function makeThrottle(maxAttempts?: number, windowMs?: number): (id: string | number, now?: number) => boolean;
@@ -0,0 +1,65 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadGatePolicy } from "./config.js";
4
+ import { carryInto, dataDir } from "../data-dir.js";
5
+ export const stateDir = () => process.env['ORCHESTRATOR_STATE_DIR'] ?? path.join(dataDir(), 'state');
6
+ function legacyStateDirs() {
7
+ return [
8
+ path.join(process.cwd(), 'packages', 'plugin-orchestrator', 'runtime', 'state'),
9
+ path.join(process.cwd(), 'node_modules', '@coffer-org', 'plugin-orchestrator', 'runtime', 'state'),
10
+ ];
11
+ }
12
+ export function carryLegacyState() {
13
+ carryInto(stateDir(), ...legacyStateDirs());
14
+ }
15
+ export function allowFileFor(connectorId) {
16
+ return path.join(stateDir(), `${connectorId}.allowed.json`);
17
+ }
18
+ export function emptyAllowed() {
19
+ return { ids: {} };
20
+ }
21
+ export function loadAllowed(file) {
22
+ try {
23
+ const obj = JSON.parse(fs.readFileSync(file, 'utf-8'));
24
+ if (obj && typeof obj === 'object' && 'ids' in obj && typeof obj.ids === 'object') {
25
+ return obj;
26
+ }
27
+ return emptyAllowed();
28
+ }
29
+ catch {
30
+ return emptyAllowed();
31
+ }
32
+ }
33
+ export function saveAllowed(file, state) {
34
+ fs.mkdirSync(path.dirname(file), { recursive: true });
35
+ const tmp = `${file}.${process.pid}.tmp`;
36
+ fs.writeFileSync(tmp, JSON.stringify(state), 'utf-8');
37
+ fs.renameSync(tmp, file);
38
+ }
39
+ export function isAllowed(state, id) {
40
+ return id != null && Object.prototype.hasOwnProperty.call(state.ids, String(id));
41
+ }
42
+ export function addAllowed(state, id, now) {
43
+ return { ids: { ...state.ids, [String(id)]: now } };
44
+ }
45
+ export async function isSenderAllowed(connectorId, senderId, deps) {
46
+ const policy = deps?.policy ?? (await loadGatePolicy());
47
+ if (!policy.accessPassword)
48
+ return true;
49
+ return isAllowed(loadAllowed(allowFileFor(connectorId)), senderId);
50
+ }
51
+ export function makeThrottle(maxAttempts = 5, windowMs = 60_000) {
52
+ const hits = new Map();
53
+ return function allowAttempt(id, now = Date.now()) {
54
+ const key = String(id);
55
+ const rec = hits.get(key);
56
+ if (!rec || now - rec.start >= windowMs) {
57
+ hits.set(key, { start: now, count: 1 });
58
+ return true;
59
+ }
60
+ if (rec.count >= maxAttempts)
61
+ return false;
62
+ rec.count += 1;
63
+ return true;
64
+ };
65
+ }
@@ -0,0 +1,2 @@
1
+ import type { AttachmentMaterializer } from './types.ts';
2
+ export declare const attachmentMaterializer: AttachmentMaterializer;
@@ -0,0 +1,11 @@
1
+ import { saveUploadBytes } from "../uploads.js";
2
+ export const attachmentMaterializer = {
3
+ async store(bytes, opts = {}) {
4
+ const stored = await saveUploadBytes(bytes, opts);
5
+ return {
6
+ name: stored.name,
7
+ ...(stored.mime ? { mime: stored.mime } : {}),
8
+ size: stored.size,
9
+ };
10
+ },
11
+ };
@@ -0,0 +1,4 @@
1
+ import type { GatePolicy } from './types.ts';
2
+ export declare function buildPolicy(dbSettings?: Record<string, unknown>): GatePolicy;
3
+ export declare function loadAgentId(): Promise<string | undefined>;
4
+ export declare function loadGatePolicy(): Promise<GatePolicy>;
@@ -0,0 +1,19 @@
1
+ import { SYSTEM_SETTINGS_ID } from "../system-settings.js";
2
+ export function buildPolicy(dbSettings = {}) {
3
+ const db = dbSettings;
4
+ return {
5
+ ...(typeof db.agent_id === 'string' && db.agent_id ? { agentId: db.agent_id } : {}),
6
+ accessPassword: db.access_password ?? '',
7
+ triggerPrefix: db.trigger_prefix ?? '',
8
+ replyWindow: Number(db.reply_window ?? 1800) || 1800,
9
+ };
10
+ }
11
+ export async function loadAgentId() {
12
+ const { getPluginSettings } = await import("../plugin-runtime.js");
13
+ const value = (await getPluginSettings(SYSTEM_SETTINGS_ID))['agent_id'];
14
+ return typeof value === 'string' && value ? value : undefined;
15
+ }
16
+ export async function loadGatePolicy() {
17
+ const { getPluginSettings } = await import("../plugin-runtime.js");
18
+ return buildPolicy(await getPluginSettings(SYSTEM_SETTINGS_ID));
19
+ }
@@ -0,0 +1,17 @@
1
+ export type LogTurn = {
2
+ connector: string;
3
+ chatId: string;
4
+ userId: string;
5
+ role: 'user' | 'assistant';
6
+ text: string;
7
+ tokensIn: number | null;
8
+ tokensOut: number | null;
9
+ ms: number | null;
10
+ agentId: string | null;
11
+ presetId: string | null;
12
+ };
13
+ export interface LogDb {
14
+ logTurn(row: LogTurn): void;
15
+ close(): void;
16
+ }
17
+ export declare function openLogDb(): LogDb;
@@ -0,0 +1,12 @@
1
+ import { logMessage } from "../msg-log.js";
2
+ import { getLogger } from '@coffer-org/sdk/logger';
3
+ const log = getLogger('orchestrator');
4
+ export function openLogDb() {
5
+ return {
6
+ logTurn(row) {
7
+ logMessage(row).catch((e) => log.error('logTurn failed', e));
8
+ },
9
+ close() {
10
+ },
11
+ };
12
+ }
@@ -0,0 +1,9 @@
1
+ export interface DiagnosticEvent {
2
+ ts: string;
3
+ level: 'error' | 'warn';
4
+ source: string;
5
+ message: string;
6
+ }
7
+ export declare function recordDiagnostic(level: DiagnosticEvent['level'], source: string, message: string): void;
8
+ export declare function listDiagnostics(limit?: number): DiagnosticEvent[];
9
+ export declare function clearDiagnostics(): void;
@@ -0,0 +1,13 @@
1
+ const MAX_EVENTS = 100;
2
+ const events = [];
3
+ export function recordDiagnostic(level, source, message) {
4
+ events.unshift({ ts: new Date().toISOString(), level, source, message: message.slice(0, 500) });
5
+ if (events.length > MAX_EVENTS)
6
+ events.length = MAX_EVENTS;
7
+ }
8
+ export function listDiagnostics(limit = 25) {
9
+ return events.slice(0, Math.max(1, Math.min(100, Math.trunc(limit))));
10
+ }
11
+ export function clearDiagnostics() {
12
+ events.length = 0;
13
+ }
@@ -0,0 +1,2 @@
1
+ export declare function systemTimeZone(): string;
2
+ export declare function todayDateString(now?: Date, timeZone?: string): string;
@@ -0,0 +1,14 @@
1
+ export function systemTimeZone() {
2
+ try {
3
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
4
+ }
5
+ catch {
6
+ return 'UTC';
7
+ }
8
+ }
9
+ function part(now, timeZone, locale, options) {
10
+ return new Intl.DateTimeFormat(locale, { ...options, timeZone }).format(now);
11
+ }
12
+ export function todayDateString(now = new Date(), timeZone = systemTimeZone()) {
13
+ return part(now, timeZone, 'en-CA', { year: 'numeric', month: '2-digit', day: '2-digit' });
14
+ }
@@ -0,0 +1,3 @@
1
+ import type { AgentToolContentResult, AttachmentRef } from './types.ts';
2
+ export declare function inspectUpload(name: string, ref?: Pick<AttachmentRef, 'mime' | 'size' | 'label'>): Promise<AgentToolContentResult>;
3
+ export declare function isAgentToolContentResult(value: unknown): value is AgentToolContentResult;
@@ -0,0 +1,61 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { basename, join } from 'node:path';
3
+ import { mimeForName } from "../file-fields.js";
4
+ import { uploadsDir } from "../uploads.js";
5
+ const MAX_VISION_BYTES = 5 * 1024 * 1024;
6
+ const MAX_DOCUMENT_BYTES = 10 * 1024 * 1024;
7
+ const MAX_TEXT_BYTES = 512 * 1024;
8
+ const textResult = (text, isError = false) => ({
9
+ __cofferToolContent: true,
10
+ content: [{ type: 'text', text }],
11
+ ...(isError ? { isError: true } : {}),
12
+ });
13
+ export async function inspectUpload(name, ref = {}) {
14
+ if (!name || basename(name) !== name)
15
+ return textResult('Invalid upload name.', true);
16
+ const file = join(uploadsDir(), name);
17
+ let size;
18
+ try {
19
+ size = (await stat(file)).size;
20
+ }
21
+ catch {
22
+ return textResult(`File is no longer present on the server: ${name}`, true);
23
+ }
24
+ const mime = ref.mime ?? mimeForName(name);
25
+ if (mime === 'image/jpeg' || mime === 'image/png' || mime === 'image/gif' || mime === 'image/webp') {
26
+ if (size > MAX_VISION_BYTES)
27
+ return textResult(`Image is ${size} bytes, above the ${MAX_VISION_BYTES}-byte inspection limit.`, true);
28
+ const bytes = await readFile(file);
29
+ return {
30
+ __cofferToolContent: true,
31
+ content: [
32
+ { type: 'text', text: `Image: ${ref.label ?? name} (${mime}, ${size} bytes).` },
33
+ { type: 'image', mime, data: bytes.toString('base64') },
34
+ ],
35
+ };
36
+ }
37
+ if (mime === 'application/pdf') {
38
+ if (size > MAX_DOCUMENT_BYTES)
39
+ return textResult(`PDF is ${size} bytes, above the ${MAX_DOCUMENT_BYTES}-byte inspection limit.`, true);
40
+ const bytes = await readFile(file);
41
+ return {
42
+ __cofferToolContent: true,
43
+ content: [
44
+ { type: 'text', text: `PDF: ${ref.label ?? name} (${size} bytes).` },
45
+ { type: 'document', mime: 'application/pdf', data: bytes.toString('base64') },
46
+ ],
47
+ };
48
+ }
49
+ if (mime?.startsWith('text/') || mime === 'application/json' || mime === 'text/csv') {
50
+ if (size > MAX_TEXT_BYTES)
51
+ return textResult(`Text file is too large to inspect: ${size} bytes.`, true);
52
+ return textResult(`Text file: ${ref.label ?? name}\n\n${(await readFile(file)).toString('utf8')}`);
53
+ }
54
+ return textResult(`This file type cannot be inspected by the agent (${mime ?? 'unknown'}). ` +
55
+ 'It can still be attached to a record.', true);
56
+ }
57
+ export function isAgentToolContentResult(value) {
58
+ return (typeof value === 'object' &&
59
+ value !== null &&
60
+ value.__cofferToolContent === true);
61
+ }
@@ -0,0 +1 @@
1
+ export declare function chunk(text: string, max: number): string[];
@@ -0,0 +1,6 @@
1
+ export function chunk(text, max) {
2
+ const out = [];
3
+ for (let i = 0; i < text.length; i += max)
4
+ out.push(text.slice(i, i + max));
5
+ return out.length ? out : [''];
6
+ }
@@ -0,0 +1,30 @@
1
+ import type { BackgroundTask } from '../background-scheduler.ts';
2
+ import { listRecentMessageMetrics } from '../msg-log.ts';
3
+ import { listDiagnostics } from './diagnostics.ts';
4
+ export { handleIncoming } from './pipeline.ts';
5
+ export { registerAgent, resolveAgent, registerConnector, isConnectorRegistered, clearRuntimeRegistries, listRegisteredAgents, listRegisteredConnectors, listAgentCatalog, getDefaultAgentId, liveAgentId, } from './registry.ts';
6
+ export { attachmentMaterializer } from './attachments.ts';
7
+ export { makeAttachmentCapabilities } from './agent-capabilities.ts';
8
+ export { makeSystemCapabilities } from './system-capabilities.ts';
9
+ export { makeSuggestionCapabilities } from './suggestion-capabilities.ts';
10
+ export type { SuggestionCapability } from './suggestion-capabilities.ts';
11
+ export { systemTimeZone } from './environment.ts';
12
+ export { inspectUpload, isAgentToolContentResult } from './file-inspection.ts';
13
+ export type { PipelineDeps, RunAgentFn } from './pipeline.ts';
14
+ export { buildPolicy, loadGatePolicy, loadAgentId } from './config.ts';
15
+ export { getConversationStarters, refreshSystemStarters } from './starters.ts';
16
+ export { isSenderAllowed } from './allow.ts';
17
+ export { makeLiveChannel, plainRender } from './live-message.ts';
18
+ export type { LiveChannelOps, LiveChannelOpts, RenderFn } from './live-message.ts';
19
+ export { chunk } from './format.ts';
20
+ export type { Connector, IncomingConversation, GatePolicy, ReplyContext, ReplyPayload, ReplyChannel, AttachmentRef, AttachmentMaterializer, AgentToolDefinition, AgentToolProvider, ConvMessage, AgentRequest, AgentResult, AgentRuntime, AgentCapabilities, AgentPreset, AgentDescriptor, ConnectorRegistration, AgentToolContentBlock, AgentToolContentResult, } from './types.ts';
21
+ export declare function startOrchestrator(): void;
22
+ export declare function stopOrchestrator(): void;
23
+ export declare const orchestratorStartersTask: BackgroundTask;
24
+ export declare function orchestratorDiagnostics(): Promise<{
25
+ generatedAt: string;
26
+ agents: string[];
27
+ connectors: string[];
28
+ recentMessages: Awaited<ReturnType<typeof listRecentMessageMetrics>>;
29
+ recentErrors: ReturnType<typeof listDiagnostics>;
30
+ }>;
@@ -0,0 +1,56 @@
1
+ import { openLogDb } from "./db.js";
2
+ import { listRecentMessageMetrics } from "../msg-log.js";
3
+ import { listRegisteredAgents, listRegisteredConnectors } from "./registry.js";
4
+ import { listDiagnostics } from "./diagnostics.js";
5
+ import { setLogDb } from "./pipeline.js";
6
+ import { refreshSystemStarters } from "./starters.js";
7
+ import { getLogger } from '@coffer-org/sdk/logger';
8
+ const log = getLogger('orchestrator');
9
+ export { handleIncoming } from "./pipeline.js";
10
+ export { registerAgent, resolveAgent, registerConnector, isConnectorRegistered, clearRuntimeRegistries, listRegisteredAgents, listRegisteredConnectors, listAgentCatalog, getDefaultAgentId, liveAgentId, } from "./registry.js";
11
+ export { attachmentMaterializer } from "./attachments.js";
12
+ export { makeAttachmentCapabilities } from "./agent-capabilities.js";
13
+ export { makeSystemCapabilities } from "./system-capabilities.js";
14
+ export { makeSuggestionCapabilities } from "./suggestion-capabilities.js";
15
+ export { systemTimeZone } from "./environment.js";
16
+ export { inspectUpload, isAgentToolContentResult } from "./file-inspection.js";
17
+ export { buildPolicy, loadGatePolicy, loadAgentId } from "./config.js";
18
+ export { getConversationStarters, refreshSystemStarters } from "./starters.js";
19
+ export { isSenderAllowed } from "./allow.js";
20
+ import { carryLegacyState } from "./allow.js";
21
+ export { makeLiveChannel, plainRender } from "./live-message.js";
22
+ export { chunk } from "./format.js";
23
+ let db;
24
+ const STARTERS_CHECK_INTERVAL_MS = 10 * 60_000;
25
+ function runStartersRefresh() {
26
+ return refreshSystemStarters().catch((err) => log.warn(`system starters: ${String(err)}`));
27
+ }
28
+ export function startOrchestrator() {
29
+ carryLegacyState();
30
+ db = openLogDb();
31
+ setLogDb(db);
32
+ void runStartersRefresh();
33
+ }
34
+ export function stopOrchestrator() {
35
+ try {
36
+ db?.close();
37
+ }
38
+ catch {
39
+ }
40
+ db = undefined;
41
+ setLogDb(undefined);
42
+ }
43
+ export const orchestratorStartersTask = {
44
+ name: 'core:orchestrator-starters',
45
+ intervalMs: STARTERS_CHECK_INTERVAL_MS,
46
+ run: runStartersRefresh,
47
+ };
48
+ export async function orchestratorDiagnostics() {
49
+ return {
50
+ generatedAt: new Date().toISOString(),
51
+ agents: listRegisteredAgents(),
52
+ connectors: listRegisteredConnectors(),
53
+ recentMessages: await listRecentMessageMetrics(25),
54
+ recentErrors: listDiagnostics(25),
55
+ };
56
+ }
@@ -0,0 +1,14 @@
1
+ import type { ReplyChannel, ReplyPayload } from './types.ts';
2
+ export interface LiveChannelOps {
3
+ send(text: string): Promise<string | null>;
4
+ edit(msgId: string, text: string): Promise<void>;
5
+ }
6
+ export type RenderFn = (r: ReplyPayload) => string[];
7
+ export interface LiveChannelOpts {
8
+ ops: LiveChannelOps;
9
+ throttleMs: number;
10
+ render: RenderFn;
11
+ maxLength: number;
12
+ }
13
+ export declare function plainRender(max: number): RenderFn;
14
+ export declare function makeLiveChannel(o: LiveChannelOpts): ReplyChannel;