loopengine 0.4.14 → 0.5.1
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/core/audit-store.d.ts +71 -8
- package/dist/core/audit-store.js +206 -12
- package/dist/core/input-schema.d.ts +47 -0
- package/dist/core/input-schema.js +180 -0
- package/dist/core/output-schema.d.ts +30 -0
- package/dist/core/output-schema.js +105 -0
- package/dist/core/run-agent.js +35 -2
- package/dist/core/scheduler.d.ts +6 -0
- package/dist/core/scheduler.js +22 -16
- package/dist/core/trace.d.ts +34 -0
- package/dist/core/trace.js +149 -0
- package/dist/core/workflow-runs.d.ts +30 -5
- package/dist/core/workflow-runs.js +62 -12
- package/dist/core/workflow-triggers.d.ts +8 -1
- package/dist/core/workflow-triggers.js +13 -0
- package/dist/core/workflows.d.ts +17 -1
- package/dist/core/workflows.js +72 -9
- package/dist/index.d.ts +12 -2
- package/dist/index.js +14 -2
- package/dist/web/agents-config-page.js +372 -67
- package/dist/web/audit-admin.d.ts +2 -2
- package/dist/web/audit-admin.js +5 -3
- package/dist/web/audit-page.js +7 -5
- package/dist/web/change-log.js +4 -2
- package/dist/web/console-shell.js +1 -1
- package/dist/web/decide-page.js +1 -1
- package/dist/web/goals-admin.d.ts +8 -5
- package/dist/web/goals-admin.js +25 -5
- package/dist/web/goals-page.js +8 -2
- package/dist/web/inbox-page.js +143 -1
- package/dist/web/run-trace.d.ts +114 -0
- package/dist/web/run-trace.js +79 -0
- package/dist/web/workflow-admin.d.ts +12 -3
- package/dist/web/workflow-admin.js +42 -7
- package/dist/web/workflow-audit-report.js +5 -5
- package/dist/web/workflow-audit.d.ts +3 -3
- package/dist/web/workflow-audit.js +12 -11
- package/dist/web/workflow-drafts.d.ts +75 -0
- package/dist/web/workflow-drafts.js +112 -0
- package/dist/web/workflow-evidence.d.ts +17 -4
- package/dist/web/workflow-evidence.js +22 -6
- package/dist/web/workflow-health.d.ts +2 -2
- package/dist/web/workflow-health.js +7 -1
- package/package.json +9 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
export type VersionKind = '
|
|
2
|
+
export type VersionKind = 'workflow' | 'policies';
|
|
3
3
|
export interface Version {
|
|
4
4
|
number: number;
|
|
5
5
|
at: string;
|
|
@@ -100,6 +100,30 @@ export interface EventFilter {
|
|
|
100
100
|
export declare function listEvents(filter?: EventFilter, database?: DatabaseSync | undefined): AuditEvent[];
|
|
101
101
|
/** Everyone named on an event, most recent first (for a filter). */
|
|
102
102
|
export declare function eventPeople(limit?: number, database?: DatabaseSync | undefined): string[];
|
|
103
|
+
/** One step of a turn's trace: the prompt it ran with ("prompt"), a model
|
|
104
|
+
* call ("llm"), or a tool call ("tool"). Input and output are what was
|
|
105
|
+
* sent and what came back, as JSON values. */
|
|
106
|
+
export interface TraceSpan {
|
|
107
|
+
id: number;
|
|
108
|
+
sessionId: string;
|
|
109
|
+
at: string;
|
|
110
|
+
kind: 'prompt' | 'llm' | 'tool';
|
|
111
|
+
name?: string;
|
|
112
|
+
durationMs?: number;
|
|
113
|
+
input?: unknown;
|
|
114
|
+
output?: unknown;
|
|
115
|
+
error?: string;
|
|
116
|
+
meta?: Record<string, unknown>;
|
|
117
|
+
}
|
|
118
|
+
/** Keeps a system prompt once, by its hash, and returns the hash. */
|
|
119
|
+
export declare function recordTracePrompt(text: string, database?: DatabaseSync | undefined): string | undefined;
|
|
120
|
+
/** Appends a step to a turn's trace. Never throws: the trace must not stop
|
|
121
|
+
* the work it records. */
|
|
122
|
+
export declare function recordTraceSpan(span: Omit<TraceSpan, 'id'>, database?: DatabaseSync | undefined): void;
|
|
123
|
+
/** A session's trace, oldest first; each prompt step carries its system
|
|
124
|
+
* prompt's text (as input.system). */
|
|
125
|
+
export declare function listTraceSpans(sessionId: string, database?: DatabaseSync | undefined): TraceSpan[];
|
|
126
|
+
export declare function pruneTraces(database?: DatabaseSync | undefined): void;
|
|
103
127
|
/** The version number of `content`: the latest version's when it's the
|
|
104
128
|
* same text, else a new version noted now. Undefined without a database.
|
|
105
129
|
* `agent` and `workflowId` are '' for the workspace's policies. */
|
|
@@ -122,14 +146,53 @@ export declare function getVersion(key: {
|
|
|
122
146
|
workflowId: string;
|
|
123
147
|
kind: VersionKind;
|
|
124
148
|
}, number: number, database?: DatabaseSync | undefined): Version | undefined;
|
|
125
|
-
/** What a workflow
|
|
126
|
-
*
|
|
127
|
-
|
|
149
|
+
/** What a workflow version holds, as text people can read and compare
|
|
150
|
+
* line by line: which workflow it is, its name and description, its input
|
|
151
|
+
* schema, model, the tools it uses with each one's permission, its
|
|
152
|
+
* triggers, its success criteria, its output schema, its instructions and
|
|
153
|
+
* its result format. */
|
|
154
|
+
export interface WorkflowSnapshot {
|
|
155
|
+
agent: string;
|
|
156
|
+
workflowId: string;
|
|
157
|
+
title: string;
|
|
158
|
+
description: string;
|
|
159
|
+
/** Each input: what it is, whether it's required, and any type and
|
|
160
|
+
* limits (core/input-schema.ts). */
|
|
161
|
+
parameters: Record<string, {
|
|
162
|
+
description: string;
|
|
163
|
+
required: boolean;
|
|
164
|
+
[limit: string]: unknown;
|
|
165
|
+
}>;
|
|
166
|
+
model?: {
|
|
167
|
+
provider: string;
|
|
168
|
+
model: string;
|
|
169
|
+
};
|
|
170
|
+
/** The agent's tools its instructions name, each with its permission
|
|
171
|
+
* (allow, ask or deny): the workflow's contract. */
|
|
172
|
+
tools: {
|
|
173
|
+
name: string;
|
|
174
|
+
permission: string;
|
|
175
|
+
}[];
|
|
176
|
+
/** Each schedule and webhook that starts it, in a line. */
|
|
177
|
+
triggers: string[];
|
|
178
|
+
criteria: {
|
|
179
|
+
text: string;
|
|
180
|
+
kind: string;
|
|
181
|
+
value?: string;
|
|
182
|
+
}[];
|
|
128
183
|
instructions: string;
|
|
129
184
|
output?: string;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
185
|
+
/** The JSON Schema its result must match (core/output-schema.ts). */
|
|
186
|
+
outputSchema?: Record<string, unknown>;
|
|
187
|
+
/** Its inputs as one JSON Schema, as the version holds them (read
|
|
188
|
+
* back from a version; made from `parameters` when one is written). */
|
|
189
|
+
inputSchema?: Record<string, unknown>;
|
|
190
|
+
}
|
|
191
|
+
export declare function workflowContent(w: WorkflowSnapshot): string;
|
|
192
|
+
/** What a version holds. Older versions hold less: one from when only
|
|
193
|
+
* the brief was numbered has just the instructions and result format;
|
|
194
|
+
* one from before tools, triggers and criteria were part of it has no
|
|
195
|
+
* such sections, and none comes back. */
|
|
196
|
+
export declare function workflowFromContent(content: string): Partial<WorkflowSnapshot> & {
|
|
133
197
|
instructions: string;
|
|
134
|
-
output?: string;
|
|
135
198
|
};
|
package/dist/core/audit-store.js
CHANGED
|
@@ -14,12 +14,19 @@
|
|
|
14
14
|
// - session_entries: every conversation's messages, in order, each with
|
|
15
15
|
// when it was written (core/session-store.ts's SqliteSessionStore);
|
|
16
16
|
// - usage: tokens and time of every model call (core/usage.ts);
|
|
17
|
+
// - trace_spans and trace_prompts: each turn's trace (core/trace.ts): the
|
|
18
|
+
// prompt it ran with, each model call's new input and its output, and
|
|
19
|
+
// each tool call's input, output and time; system prompts kept once,
|
|
20
|
+
// by hash;
|
|
17
21
|
// - threads and job_threads: which chat message each request or job is
|
|
18
22
|
// (core/messaging/threads.ts);
|
|
19
|
-
// - versions: each workflow
|
|
20
|
-
// and
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
+
// - versions: each workflow as a whole (its name, inputs, model,
|
|
24
|
+
// instructions and result format; not its triggers or where its messages
|
|
25
|
+
// go) and the workspace's shared policies, numbered. A new version is
|
|
26
|
+
// noted whenever the text differs from the latest, however it changed:
|
|
27
|
+
// saved in the console, restored, or edited in the file. Workflows were
|
|
28
|
+
// once versioned by their brief alone (kind "brief"); those versions are
|
|
29
|
+
// the workflow's first ones, numbers unchanged.
|
|
23
30
|
//
|
|
24
31
|
// It uses node:sqlite, built into Node 22.5 and later. Where that's
|
|
25
32
|
// missing, auditDb() is undefined: runs stay in JSON files and nothing is
|
|
@@ -28,6 +35,7 @@ import { createHash } from 'node:crypto';
|
|
|
28
35
|
import { mkdirSync } from 'node:fs';
|
|
29
36
|
import { createRequire } from 'node:module';
|
|
30
37
|
import path from 'node:path';
|
|
38
|
+
import { inputSchemaOf } from './input-schema.js';
|
|
31
39
|
const SCHEMA = `
|
|
32
40
|
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
33
41
|
CREATE TABLE IF NOT EXISTS runs (
|
|
@@ -113,6 +121,25 @@ CREATE TABLE IF NOT EXISTS usage (
|
|
|
113
121
|
);
|
|
114
122
|
CREATE INDEX IF NOT EXISTS usage_session ON usage (session_id, id);
|
|
115
123
|
CREATE INDEX IF NOT EXISTS usage_agent ON usage (agent, at);
|
|
124
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
125
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
126
|
+
session_id TEXT NOT NULL,
|
|
127
|
+
at TEXT NOT NULL,
|
|
128
|
+
kind TEXT NOT NULL,
|
|
129
|
+
name TEXT,
|
|
130
|
+
duration_ms INTEGER,
|
|
131
|
+
input TEXT,
|
|
132
|
+
output TEXT,
|
|
133
|
+
error TEXT,
|
|
134
|
+
meta TEXT
|
|
135
|
+
);
|
|
136
|
+
CREATE INDEX IF NOT EXISTS trace_spans_session ON trace_spans (session_id, id);
|
|
137
|
+
CREATE INDEX IF NOT EXISTS trace_spans_at ON trace_spans (at);
|
|
138
|
+
CREATE TABLE IF NOT EXISTS trace_prompts (
|
|
139
|
+
hash TEXT PRIMARY KEY,
|
|
140
|
+
text TEXT NOT NULL,
|
|
141
|
+
at TEXT NOT NULL
|
|
142
|
+
);
|
|
116
143
|
CREATE TABLE IF NOT EXISTS versions (
|
|
117
144
|
agent TEXT NOT NULL,
|
|
118
145
|
workflow_id TEXT NOT NULL,
|
|
@@ -154,6 +181,9 @@ export function openAuditDb(dir) {
|
|
|
154
181
|
const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
|
|
155
182
|
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
|
|
156
183
|
db.exec(SCHEMA);
|
|
184
|
+
// Brief versions became workflow versions (same numbers, so runs that
|
|
185
|
+
// name one still find it).
|
|
186
|
+
db.exec("UPDATE versions SET kind = 'workflow' WHERE kind = 'brief'");
|
|
157
187
|
chainEvents(db);
|
|
158
188
|
return db;
|
|
159
189
|
}
|
|
@@ -346,6 +376,92 @@ function eventOf(r) {
|
|
|
346
376
|
...(r.hash ? { hash: String(r.hash) } : {}),
|
|
347
377
|
};
|
|
348
378
|
}
|
|
379
|
+
// A field longer than this is cut, so one huge tool result can't swell the
|
|
380
|
+
// database; the cut says how much was left out.
|
|
381
|
+
const MAX_TRACE_FIELD = 100_000;
|
|
382
|
+
function traceJson(value) {
|
|
383
|
+
if (value === undefined)
|
|
384
|
+
return null;
|
|
385
|
+
const text = JSON.stringify(value);
|
|
386
|
+
if (text.length <= MAX_TRACE_FIELD)
|
|
387
|
+
return text;
|
|
388
|
+
return JSON.stringify({ truncated: true, chars: text.length, start: text.slice(0, MAX_TRACE_FIELD) });
|
|
389
|
+
}
|
|
390
|
+
/** Keeps a system prompt once, by its hash, and returns the hash. */
|
|
391
|
+
export function recordTracePrompt(text, database = auditDb()) {
|
|
392
|
+
if (!database)
|
|
393
|
+
return undefined;
|
|
394
|
+
try {
|
|
395
|
+
const hash = hashOf(text);
|
|
396
|
+
database.prepare('INSERT OR IGNORE INTO trace_prompts (hash, text, at) VALUES (?, ?, ?)').run(hash, text, new Date().toISOString());
|
|
397
|
+
return hash;
|
|
398
|
+
}
|
|
399
|
+
catch (err) {
|
|
400
|
+
console.error('[loopengine] could not keep a trace prompt:', err);
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/** Appends a step to a turn's trace. Never throws: the trace must not stop
|
|
405
|
+
* the work it records. */
|
|
406
|
+
export function recordTraceSpan(span, database = auditDb()) {
|
|
407
|
+
if (!database)
|
|
408
|
+
return;
|
|
409
|
+
try {
|
|
410
|
+
database.prepare('INSERT INTO trace_spans (session_id, at, kind, name, duration_ms, input, output, error, meta) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(span.sessionId, span.at, span.kind, span.name ?? null, span.durationMs ?? null, traceJson(span.input), traceJson(span.output), span.error ?? null, span.meta ? JSON.stringify(span.meta) : null);
|
|
411
|
+
}
|
|
412
|
+
catch (err) {
|
|
413
|
+
console.error('[loopengine] could not record a trace step:', err);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/** A session's trace, oldest first; each prompt step carries its system
|
|
417
|
+
* prompt's text (as input.system). */
|
|
418
|
+
export function listTraceSpans(sessionId, database = auditDb()) {
|
|
419
|
+
if (!database)
|
|
420
|
+
return [];
|
|
421
|
+
const rows = database.prepare('SELECT * FROM trace_spans WHERE session_id = ? ORDER BY id').all(sessionId);
|
|
422
|
+
const prompts = new Map();
|
|
423
|
+
const promptText = (hash) => {
|
|
424
|
+
if (!prompts.has(hash))
|
|
425
|
+
prompts.set(hash, String(database.prepare('SELECT text FROM trace_prompts WHERE hash = ?').get(hash)?.text ?? ''));
|
|
426
|
+
return prompts.get(hash);
|
|
427
|
+
};
|
|
428
|
+
const parse = (v) => (v == null ? undefined : JSON.parse(String(v)));
|
|
429
|
+
return rows.map((r) => {
|
|
430
|
+
let input = parse(r.input);
|
|
431
|
+
if (r.kind === 'prompt' && input && typeof input === 'object' && typeof input.systemHash === 'string') {
|
|
432
|
+
const { systemHash, ...rest } = input;
|
|
433
|
+
input = { system: promptText(systemHash), ...rest };
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
id: Number(r.id),
|
|
437
|
+
sessionId: String(r.session_id),
|
|
438
|
+
at: String(r.at),
|
|
439
|
+
kind: String(r.kind),
|
|
440
|
+
...(r.name != null ? { name: String(r.name) } : {}),
|
|
441
|
+
...(r.duration_ms != null ? { durationMs: Number(r.duration_ms) } : {}),
|
|
442
|
+
...(input !== undefined ? { input } : {}),
|
|
443
|
+
...(r.output != null ? { output: parse(r.output) } : {}),
|
|
444
|
+
...(r.error != null ? { error: String(r.error) } : {}),
|
|
445
|
+
...(r.meta != null ? { meta: JSON.parse(String(r.meta)) } : {}),
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
/** At most hourly: trace steps older than the retention period, and the
|
|
450
|
+
* system prompts no step uses any more. */
|
|
451
|
+
let lastTracePrune = 0;
|
|
452
|
+
export function pruneTraces(database = auditDb()) {
|
|
453
|
+
if (!database || Date.now() - lastTracePrune < 60 * 60 * 1000)
|
|
454
|
+
return;
|
|
455
|
+
lastTracePrune = Date.now();
|
|
456
|
+
try {
|
|
457
|
+
const before = new Date(Date.now() - retentionDays() * 24 * 60 * 60 * 1000).toISOString();
|
|
458
|
+
database.prepare('DELETE FROM trace_spans WHERE at < ?').run(before);
|
|
459
|
+
database.prepare("DELETE FROM trace_prompts WHERE at < ? AND hash NOT IN (SELECT json_extract(input, '$.systemHash') FROM trace_spans WHERE kind = 'prompt' AND input IS NOT NULL)").run(before);
|
|
460
|
+
}
|
|
461
|
+
catch (err) {
|
|
462
|
+
console.error('[loopengine] could not prune old traces:', err);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
349
465
|
// ---------- versions ----------
|
|
350
466
|
const hashOf = (content) => createHash('sha256').update(content).digest('hex');
|
|
351
467
|
/** The version number of `content`: the latest version's when it's the
|
|
@@ -386,13 +502,91 @@ export function listVersions(key, database = auditDb()) {
|
|
|
386
502
|
export function getVersion(key, number, database = auditDb()) {
|
|
387
503
|
return listVersions(key, database).find((v) => v.number === number);
|
|
388
504
|
}
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
export function
|
|
392
|
-
|
|
505
|
+
const INSTRUCTIONS_HEADING = '\n## Instructions\n\n';
|
|
506
|
+
const RESULT_HEADING = '\n\n## Result format\n\n';
|
|
507
|
+
export function workflowContent(w) {
|
|
508
|
+
const line = (text) => text.replace(/\s+/g, ' ').trim();
|
|
509
|
+
const list = (items) => (items.length ? items.join('\n') : 'None');
|
|
510
|
+
const json = (schema) => `\`\`\`json\n${JSON.stringify(schema, null, 2)}\n\`\`\``;
|
|
511
|
+
const criteria = w.criteria.map((c) => `- [${c.kind}${c.value !== undefined ? `: ${JSON.stringify(c.value)}` : ''}] ${line(c.text)}`);
|
|
512
|
+
const head = `# ${line(w.title)}` +
|
|
513
|
+
(line(w.description) ? `\n\n${line(w.description)}` : '') +
|
|
514
|
+
`\n\n## Workflow\n\n${w.agent}/${w.workflowId}` +
|
|
515
|
+
`\n\n## Input schema\n\n${json(inputSchemaOf(w.parameters))}` +
|
|
516
|
+
`\n\n## Model\n\n${w.model ? `${w.model.provider}/${w.model.model}` : "The agent's"}` +
|
|
517
|
+
`\n\n## Tools\n\n${list(w.tools.map((t) => `- ${t.name}: ${t.permission}`))}` +
|
|
518
|
+
`\n\n## Triggers\n\n${list(w.triggers.map((t) => `- ${line(t)}`))}` +
|
|
519
|
+
`\n\n## Success criteria\n\n${list(criteria)}` +
|
|
520
|
+
`\n\n## Output schema\n\n${w.outputSchema ? json(w.outputSchema) : 'None'}\n`;
|
|
521
|
+
return head + INSTRUCTIONS_HEADING + w.instructions + (w.output?.trim() ? RESULT_HEADING + w.output.trim() : '');
|
|
393
522
|
}
|
|
394
|
-
/**
|
|
395
|
-
|
|
396
|
-
const
|
|
397
|
-
|
|
523
|
+
/** A section's ```json block, parsed. */
|
|
524
|
+
function jsonBlock(text) {
|
|
525
|
+
const json = text?.match(/^```json\n([\s\S]*)\n```$/)?.[1];
|
|
526
|
+
if (!json)
|
|
527
|
+
return undefined;
|
|
528
|
+
try {
|
|
529
|
+
return JSON.parse(json);
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return undefined;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/** A workflow's inputs, from its input schema (inputSchemaOf's): each
|
|
536
|
+
* property's description, whether it's required, and its type and
|
|
537
|
+
* limits (a text input's "string" type left out, as it's saved). */
|
|
538
|
+
function parametersFromSchema(schema) {
|
|
539
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
540
|
+
const properties = (schema.properties && typeof schema.properties === 'object' ? schema.properties : {});
|
|
541
|
+
return Object.fromEntries(Object.entries(properties).map(([name, prop]) => {
|
|
542
|
+
const { description, type, ...spec } = prop;
|
|
543
|
+
return [name, { description: typeof description === 'string' ? description : '', required: required.has(name), ...(type && type !== 'string' ? { type } : {}), ...spec }];
|
|
544
|
+
}));
|
|
545
|
+
}
|
|
546
|
+
/** What a version holds. Older versions hold less: one from when only
|
|
547
|
+
* the brief was numbered has just the instructions and result format;
|
|
548
|
+
* one from before tools, triggers and criteria were part of it has no
|
|
549
|
+
* such sections, and none comes back. */
|
|
550
|
+
export function workflowFromContent(content) {
|
|
551
|
+
const split = (body) => {
|
|
552
|
+
const at = body.lastIndexOf(RESULT_HEADING);
|
|
553
|
+
return at < 0 ? { instructions: body } : { instructions: body.slice(0, at), output: body.slice(at + RESULT_HEADING.length) };
|
|
554
|
+
};
|
|
555
|
+
const at = content.indexOf(INSTRUCTIONS_HEADING);
|
|
556
|
+
if (!content.startsWith('# ') || at < 0)
|
|
557
|
+
return split(content);
|
|
558
|
+
const head = content.slice(0, at);
|
|
559
|
+
const section = (name) => head.match(new RegExp(`\\n## ${name}\\n\\n([\\s\\S]*?)(?=\\n## |$)`))?.[1]?.trim();
|
|
560
|
+
const lines = (name) => (section(name) ?? '').split('\n').filter((l) => l.startsWith('- ')).map((l) => l.slice(2));
|
|
561
|
+
const firstLines = head.split('\n## ')[0].split('\n').filter((l) => l.trim());
|
|
562
|
+
const inputSchema = jsonBlock(section('Input schema'));
|
|
563
|
+
const outputSchema = jsonBlock(section('Output schema'));
|
|
564
|
+
const model = (section('Model') ?? '').match(/^([a-z0-9-]+)\/(.+)$/);
|
|
565
|
+
const which = (section('Workflow') ?? '').match(/^([^/\s]+)\/(\S+)$/);
|
|
566
|
+
const criteria = section('Success criteria') === undefined ? undefined : lines('Success criteria').flatMap((l) => {
|
|
567
|
+
const m = l.match(/^\[([a-z_]+)(?:: (".*"))?\] (.*)$/);
|
|
568
|
+
if (!m)
|
|
569
|
+
return [];
|
|
570
|
+
let value;
|
|
571
|
+
try {
|
|
572
|
+
value = m[2] ? String(JSON.parse(m[2])) : undefined;
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
value = m[2];
|
|
576
|
+
}
|
|
577
|
+
return [{ kind: m[1], text: m[3], ...(value !== undefined ? { value } : {}) }];
|
|
578
|
+
});
|
|
579
|
+
return {
|
|
580
|
+
...(which ? { agent: which[1], workflowId: which[2] } : {}),
|
|
581
|
+
title: firstLines[0].slice(2).trim(),
|
|
582
|
+
description: firstLines.slice(1).join(' ').trim(),
|
|
583
|
+
parameters: inputSchema ? parametersFromSchema(inputSchema) : {},
|
|
584
|
+
...(inputSchema ? { inputSchema } : {}),
|
|
585
|
+
...(model ? { model: { provider: model[1], model: model[2] } } : {}),
|
|
586
|
+
...(section('Tools') !== undefined ? { tools: lines('Tools').flatMap((l) => { const m = l.match(/^(.+): (\S+)$/); return m ? [{ name: m[1], permission: m[2] }] : []; }) } : {}),
|
|
587
|
+
...(section('Triggers') !== undefined ? { triggers: lines('Triggers') } : {}),
|
|
588
|
+
...(criteria ? { criteria } : {}),
|
|
589
|
+
...(outputSchema ? { outputSchema } : {}),
|
|
590
|
+
...split(content.slice(at + INSTRUCTIONS_HEADING.length)),
|
|
591
|
+
};
|
|
398
592
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export declare const INPUT_TYPES: readonly ["string", "number", "integer", "boolean", "object", "array"];
|
|
2
|
+
export type InputType = (typeof INPUT_TYPES)[number];
|
|
3
|
+
export declare const INPUT_FORMATS: readonly ["email", "date", "date-time", "uri"];
|
|
4
|
+
export type InputFormat = (typeof INPUT_FORMATS)[number];
|
|
5
|
+
/** An input's type and limits: all optional. */
|
|
6
|
+
export interface InputSpec {
|
|
7
|
+
type?: InputType;
|
|
8
|
+
format?: InputFormat;
|
|
9
|
+
enum?: (string | number)[];
|
|
10
|
+
pattern?: string;
|
|
11
|
+
minimum?: number;
|
|
12
|
+
maximum?: number;
|
|
13
|
+
minLength?: number;
|
|
14
|
+
maxLength?: number;
|
|
15
|
+
default?: string | number | boolean | Record<string, unknown> | unknown[];
|
|
16
|
+
}
|
|
17
|
+
export declare class InputSpecError extends Error {
|
|
18
|
+
}
|
|
19
|
+
/** An input's spec as saved: only the keys above, each of the right kind,
|
|
20
|
+
* and a default that is itself a valid value. Throws InputSpecError
|
|
21
|
+
* naming the input. */
|
|
22
|
+
export declare function checkInputSpec(name: string, raw: Record<string, unknown>): InputSpec;
|
|
23
|
+
/** The spec keys a parameter has, read from a saved workflow: any that
|
|
24
|
+
* don't check out are dropped (logged), so a bad edit to the file can't
|
|
25
|
+
* stop its runs. */
|
|
26
|
+
export declare function inputSpecFrom(name: string, raw: Record<string, unknown>): InputSpec;
|
|
27
|
+
/** A value given for an input, checked against its spec: the typed value
|
|
28
|
+
* and the text the run keeps, or what's wrong. Text that reads as the
|
|
29
|
+
* type is taken ("20" for a number, "yes" for yes/no, JSON for a list). */
|
|
30
|
+
export declare function checkInputValue(name: string, spec: InputSpec, given: unknown): {
|
|
31
|
+
ok: true;
|
|
32
|
+
value: unknown;
|
|
33
|
+
text: string;
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
error: string;
|
|
37
|
+
};
|
|
38
|
+
/** A workflow's inputs as one JSON Schema, for apps that start it. */
|
|
39
|
+
export declare function inputSchemaOf(parameters: Record<string, InputSpec & {
|
|
40
|
+
description: string;
|
|
41
|
+
required: boolean;
|
|
42
|
+
}>): Record<string, unknown>;
|
|
43
|
+
/** The spec part of a parameter, without its description and required. */
|
|
44
|
+
export declare function specOf(p: InputSpec & {
|
|
45
|
+
description?: string;
|
|
46
|
+
required?: boolean;
|
|
47
|
+
}): InputSpec;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// A workflow's input schema: each input's type and limits, beside its
|
|
2
|
+
// description and whether it's required (core/workflows.ts's parameters).
|
|
3
|
+
// A run's values are checked against it before anything runs, and kept as
|
|
4
|
+
// text, the same as before: a number as "20", yes/no as "true", a list or
|
|
5
|
+
// an object as its JSON. An input with no type is text, as every input
|
|
6
|
+
// was before types.
|
|
7
|
+
//
|
|
8
|
+
// type string (the default), number, integer, boolean, object, array
|
|
9
|
+
// format for a string: email, date (2026-11-25), date-time, uri
|
|
10
|
+
// enum the values allowed
|
|
11
|
+
// pattern for a string: a regular expression it must match
|
|
12
|
+
// minimum, maximum for a number
|
|
13
|
+
// minLength, maxLength for a string
|
|
14
|
+
// default used when a run doesn't give it
|
|
15
|
+
//
|
|
16
|
+
// inputSchemaOf gives the whole thing as one JSON Schema, for apps.
|
|
17
|
+
import { Ajv } from 'ajv';
|
|
18
|
+
import addFormatsModule from 'ajv-formats';
|
|
19
|
+
export const INPUT_TYPES = ['string', 'number', 'integer', 'boolean', 'object', 'array'];
|
|
20
|
+
export const INPUT_FORMATS = ['email', 'date', 'date-time', 'uri'];
|
|
21
|
+
export class InputSpecError extends Error {
|
|
22
|
+
}
|
|
23
|
+
const SPEC_KEYS = ['type', 'format', 'enum', 'pattern', 'minimum', 'maximum', 'minLength', 'maxLength', 'default'];
|
|
24
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
25
|
+
const addFormats = addFormatsModule.default ?? addFormatsModule;
|
|
26
|
+
addFormats(ajv);
|
|
27
|
+
const compiled = new Map();
|
|
28
|
+
function validatorFor(schema) {
|
|
29
|
+
const key = JSON.stringify(schema);
|
|
30
|
+
let fn = compiled.get(key);
|
|
31
|
+
if (!fn) {
|
|
32
|
+
fn = ajv.compile(schema);
|
|
33
|
+
if (compiled.size > 500)
|
|
34
|
+
compiled.clear();
|
|
35
|
+
compiled.set(key, fn);
|
|
36
|
+
}
|
|
37
|
+
return fn;
|
|
38
|
+
}
|
|
39
|
+
/** An input's JSON Schema: its spec and description. */
|
|
40
|
+
function schemaOf(spec, description) {
|
|
41
|
+
// Only the type and limits: a parameter also has its own description
|
|
42
|
+
// and "required", which mean something else in a JSON Schema.
|
|
43
|
+
const { default: _d, ...rest } = specOf(spec);
|
|
44
|
+
return { type: spec.type ?? 'string', ...rest, ...(description ? { description } : {}) };
|
|
45
|
+
}
|
|
46
|
+
/** An input's spec as saved: only the keys above, each of the right kind,
|
|
47
|
+
* and a default that is itself a valid value. Throws InputSpecError
|
|
48
|
+
* naming the input. */
|
|
49
|
+
export function checkInputSpec(name, raw) {
|
|
50
|
+
const bad = (what) => new InputSpecError(`Input "${name}": ${what}`);
|
|
51
|
+
const spec = {};
|
|
52
|
+
if (raw.type !== undefined && raw.type !== '') {
|
|
53
|
+
if (!INPUT_TYPES.includes(raw.type))
|
|
54
|
+
throw bad(`its type must be one of ${INPUT_TYPES.join(', ')}.`);
|
|
55
|
+
if (raw.type !== 'string')
|
|
56
|
+
spec.type = raw.type;
|
|
57
|
+
}
|
|
58
|
+
const type = spec.type ?? 'string';
|
|
59
|
+
if (raw.format !== undefined && raw.format !== '') {
|
|
60
|
+
if (type !== 'string' || !INPUT_FORMATS.includes(raw.format))
|
|
61
|
+
throw bad(`a format is for text only: ${INPUT_FORMATS.join(', ')}.`);
|
|
62
|
+
spec.format = raw.format;
|
|
63
|
+
}
|
|
64
|
+
if (raw.enum !== undefined) {
|
|
65
|
+
const list = Array.isArray(raw.enum) ? raw.enum : [];
|
|
66
|
+
if (!list.length || list.some((v) => typeof v !== 'string' && typeof v !== 'number'))
|
|
67
|
+
throw bad('its allowed values must be a list of text or numbers.');
|
|
68
|
+
if (list.length)
|
|
69
|
+
spec.enum = [...new Set(list)].slice(0, 50);
|
|
70
|
+
}
|
|
71
|
+
if (raw.pattern !== undefined && raw.pattern !== '') {
|
|
72
|
+
if (typeof raw.pattern !== 'string')
|
|
73
|
+
throw bad('its pattern must be text.');
|
|
74
|
+
try {
|
|
75
|
+
new RegExp(raw.pattern, 'u');
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
throw bad(`its pattern isn't a valid regular expression.`);
|
|
79
|
+
}
|
|
80
|
+
spec.pattern = raw.pattern;
|
|
81
|
+
}
|
|
82
|
+
for (const key of ['minimum', 'maximum', 'minLength', 'maxLength']) {
|
|
83
|
+
if (raw[key] === undefined || raw[key] === '')
|
|
84
|
+
continue;
|
|
85
|
+
const n = Number(raw[key]);
|
|
86
|
+
if (!Number.isFinite(n))
|
|
87
|
+
throw bad(`its ${key} must be a number.`);
|
|
88
|
+
spec[key] = n;
|
|
89
|
+
}
|
|
90
|
+
if (raw.default !== undefined && raw.default !== '') {
|
|
91
|
+
const value = checkInputValue(name, spec, raw.default);
|
|
92
|
+
if (!value.ok)
|
|
93
|
+
throw bad(`its default isn't valid: ${value.error}`);
|
|
94
|
+
spec.default = value.value;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
validatorFor(schemaOf(spec));
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
throw bad(`its limits don't make a valid schema: ${err instanceof Error ? err.message : String(err)}`);
|
|
101
|
+
}
|
|
102
|
+
return spec;
|
|
103
|
+
}
|
|
104
|
+
/** The spec keys a parameter has, read from a saved workflow: any that
|
|
105
|
+
* don't check out are dropped (logged), so a bad edit to the file can't
|
|
106
|
+
* stop its runs. */
|
|
107
|
+
export function inputSpecFrom(name, raw) {
|
|
108
|
+
const given = Object.fromEntries(SPEC_KEYS.filter((k) => raw[k] !== undefined).map((k) => [k, raw[k]]));
|
|
109
|
+
if (!Object.keys(given).length)
|
|
110
|
+
return {};
|
|
111
|
+
try {
|
|
112
|
+
return checkInputSpec(name, given);
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
console.error(`[loopengine] ignoring input "${name}"'s type: ${err instanceof Error ? err.message : String(err)}`);
|
|
116
|
+
return {};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function errorText(e) {
|
|
120
|
+
if (e.keyword === 'enum')
|
|
121
|
+
return `must be one of ${(e.params.allowedValues ?? []).map((v) => JSON.stringify(v)).join(', ')}`;
|
|
122
|
+
return e.message ?? 'is not valid';
|
|
123
|
+
}
|
|
124
|
+
/** A value given for an input, checked against its spec: the typed value
|
|
125
|
+
* and the text the run keeps, or what's wrong. Text that reads as the
|
|
126
|
+
* type is taken ("20" for a number, "yes" for yes/no, JSON for a list). */
|
|
127
|
+
export function checkInputValue(name, spec, given) {
|
|
128
|
+
const type = spec.type ?? 'string';
|
|
129
|
+
let value = given;
|
|
130
|
+
const isText = typeof given === 'string';
|
|
131
|
+
if (type === 'string') {
|
|
132
|
+
if (typeof given === 'number' || typeof given === 'boolean')
|
|
133
|
+
value = String(given);
|
|
134
|
+
else if (!isText)
|
|
135
|
+
return { ok: false, error: `"${name}" must be text` };
|
|
136
|
+
}
|
|
137
|
+
else if (type === 'number' || type === 'integer') {
|
|
138
|
+
if (isText)
|
|
139
|
+
value = given.trim() === '' ? NaN : Number(given.trim());
|
|
140
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
141
|
+
return { ok: false, error: `"${name}" must be a ${type === 'integer' ? 'whole number' : 'number'}` };
|
|
142
|
+
}
|
|
143
|
+
else if (type === 'boolean') {
|
|
144
|
+
if (isText) {
|
|
145
|
+
const t = given.trim().toLowerCase();
|
|
146
|
+
value = ['true', 'yes', '1'].includes(t) ? true : ['false', 'no', '0'].includes(t) ? false : given;
|
|
147
|
+
}
|
|
148
|
+
if (typeof value !== 'boolean')
|
|
149
|
+
return { ok: false, error: `"${name}" must be yes or no (true or false)` };
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
if (isText) {
|
|
153
|
+
try {
|
|
154
|
+
value = JSON.parse(given);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return { ok: false, error: `"${name}" must be ${type === 'array' ? 'a list' : 'an object'} as JSON` };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (type === 'array' ? !Array.isArray(value) : !value || typeof value !== 'object' || Array.isArray(value))
|
|
161
|
+
return { ok: false, error: `"${name}" must be ${type === 'array' ? 'a list' : 'an object'}` };
|
|
162
|
+
}
|
|
163
|
+
const validate = validatorFor(schemaOf(spec));
|
|
164
|
+
if (!validate(value))
|
|
165
|
+
return { ok: false, error: `"${name}" ${errorText(validate.errors[0])}` };
|
|
166
|
+
return { ok: true, value, text: typeof value === 'string' ? value : JSON.stringify(value) };
|
|
167
|
+
}
|
|
168
|
+
/** A workflow's inputs as one JSON Schema, for apps that start it. */
|
|
169
|
+
export function inputSchemaOf(parameters) {
|
|
170
|
+
const properties = Object.fromEntries(Object.entries(parameters).map(([name, p]) => {
|
|
171
|
+
const { description, required: _r, ...spec } = p;
|
|
172
|
+
return [name, { ...schemaOf(spec, description), ...(spec.default !== undefined ? { default: spec.default } : {}) }];
|
|
173
|
+
}));
|
|
174
|
+
const required = Object.entries(parameters).filter(([, p]) => p.required).map(([name]) => name);
|
|
175
|
+
return { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false };
|
|
176
|
+
}
|
|
177
|
+
/** The spec part of a parameter, without its description and required. */
|
|
178
|
+
export function specOf(p) {
|
|
179
|
+
return Object.fromEntries(SPEC_KEYS.filter((k) => p[k] !== undefined).map((k) => [k, p[k]]));
|
|
180
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type JsonSchema = Record<string, unknown>;
|
|
2
|
+
/** Times a run is asked again for a result that doesn't match. */
|
|
3
|
+
export declare const MAX_OUTPUT_RETRIES = 2;
|
|
4
|
+
export declare class OutputSchemaError extends Error {
|
|
5
|
+
}
|
|
6
|
+
/** A schema as saved: a JSON object (or its text) that Ajv can compile,
|
|
7
|
+
* describing an object or an array. Throws OutputSchemaError saying
|
|
8
|
+
* what's wrong. */
|
|
9
|
+
export declare function checkOutputSchema(input: unknown): JsonSchema;
|
|
10
|
+
/** The JSON in a reply: the whole reply, else its last ```json block,
|
|
11
|
+
* else the span from its first { or [ to its last } or ]. */
|
|
12
|
+
export declare function jsonInReply(text: string): {
|
|
13
|
+
found: true;
|
|
14
|
+
value: unknown;
|
|
15
|
+
} | {
|
|
16
|
+
found: false;
|
|
17
|
+
};
|
|
18
|
+
/** A reply checked against a schema: its JSON when it matches, else
|
|
19
|
+
* what's wrong, a line each (at most 10). */
|
|
20
|
+
export declare function checkOutput(schema: JsonSchema, text: string): {
|
|
21
|
+
ok: true;
|
|
22
|
+
value: unknown;
|
|
23
|
+
} | {
|
|
24
|
+
ok: false;
|
|
25
|
+
errors: string[];
|
|
26
|
+
};
|
|
27
|
+
/** What the agent is told, with the rest of its instructions. */
|
|
28
|
+
export declare function outputSchemaInstructions(schema: JsonSchema): string;
|
|
29
|
+
/** What the agent is told when its result didn't match. */
|
|
30
|
+
export declare function outputRetryMessage(errors: string[]): string;
|