loopengine 0.4.13 → 0.5.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.
- 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/system-agents/goal-planner.d.ts +3 -3
- package/dist/core/system-agents/goal-planner.js +9 -5
- 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 +6 -2
- package/dist/index.js +6 -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 +28 -8
- package/dist/web/home-page.js +3 -3
- 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/upgrade-admin.js +19 -5
- 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
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// A workflow's output schema: a JSON Schema its result must match. With
|
|
2
|
+
// one, the agent is told to end with JSON that matches it; each run's
|
|
3
|
+
// reply is checked (core/workflow-runs.ts), and when it doesn't match the
|
|
4
|
+
// agent is told what's wrong and asked again, up to MAX_OUTPUT_RETRIES
|
|
5
|
+
// times, before the run fails. A run that matches keeps the parsed JSON
|
|
6
|
+
// as its `output`, beside the text `result`, for apps, callbacks and the
|
|
7
|
+
// next workflow in a chain (which can take one field of it).
|
|
8
|
+
//
|
|
9
|
+
// Checked with Ajv (JSON Schema draft 2020-12's common keywords, and
|
|
10
|
+
// formats such as email, date and uri).
|
|
11
|
+
import { Ajv } from 'ajv';
|
|
12
|
+
import addFormatsModule from 'ajv-formats';
|
|
13
|
+
/** Times a run is asked again for a result that doesn't match. */
|
|
14
|
+
export const MAX_OUTPUT_RETRIES = 2;
|
|
15
|
+
const MAX_SCHEMA_CHARS = 20_000;
|
|
16
|
+
export class OutputSchemaError extends Error {
|
|
17
|
+
}
|
|
18
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
19
|
+
const addFormats = addFormatsModule.default ?? addFormatsModule;
|
|
20
|
+
addFormats(ajv);
|
|
21
|
+
const compiled = new Map();
|
|
22
|
+
function validatorFor(schema) {
|
|
23
|
+
const key = JSON.stringify(schema);
|
|
24
|
+
let fn = compiled.get(key);
|
|
25
|
+
if (!fn) {
|
|
26
|
+
fn = ajv.compile(schema);
|
|
27
|
+
if (compiled.size > 200)
|
|
28
|
+
compiled.clear();
|
|
29
|
+
compiled.set(key, fn);
|
|
30
|
+
}
|
|
31
|
+
return fn;
|
|
32
|
+
}
|
|
33
|
+
/** A schema as saved: a JSON object (or its text) that Ajv can compile,
|
|
34
|
+
* describing an object or an array. Throws OutputSchemaError saying
|
|
35
|
+
* what's wrong. */
|
|
36
|
+
export function checkOutputSchema(input) {
|
|
37
|
+
let schema = input;
|
|
38
|
+
if (typeof input === 'string') {
|
|
39
|
+
try {
|
|
40
|
+
schema = JSON.parse(input);
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
throw new OutputSchemaError(`The output schema isn't valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!schema || typeof schema !== 'object' || Array.isArray(schema))
|
|
47
|
+
throw new OutputSchemaError('The output schema must be a JSON object, e.g. { "type": "object", "properties": { … } }.');
|
|
48
|
+
const s = schema;
|
|
49
|
+
if (JSON.stringify(s).length > MAX_SCHEMA_CHARS)
|
|
50
|
+
throw new OutputSchemaError(`The output schema is too long (at most ${MAX_SCHEMA_CHARS.toLocaleString('en-US')} characters).`);
|
|
51
|
+
if (s.type !== 'object' && s.type !== 'array')
|
|
52
|
+
throw new OutputSchemaError('The output schema\'s "type" must be "object" or "array": the result is one JSON value with named fields, or a list.');
|
|
53
|
+
try {
|
|
54
|
+
validatorFor(s);
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
throw new OutputSchemaError(`The output schema isn't a valid JSON Schema: ${err instanceof Error ? err.message : String(err)}`);
|
|
58
|
+
}
|
|
59
|
+
return s;
|
|
60
|
+
}
|
|
61
|
+
/** The JSON in a reply: the whole reply, else its last ```json block,
|
|
62
|
+
* else the span from its first { or [ to its last } or ]. */
|
|
63
|
+
export function jsonInReply(text) {
|
|
64
|
+
const attempts = [text.trim()];
|
|
65
|
+
const fences = [...text.matchAll(/```(?:json)?\s*\n([\s\S]*?)\n?```/g)].map((m) => m[1]);
|
|
66
|
+
if (fences.length)
|
|
67
|
+
attempts.push(fences[fences.length - 1].trim());
|
|
68
|
+
const start = text.search(/[{[]/);
|
|
69
|
+
const end = Math.max(text.lastIndexOf('}'), text.lastIndexOf(']'));
|
|
70
|
+
if (start >= 0 && end > start)
|
|
71
|
+
attempts.push(text.slice(start, end + 1));
|
|
72
|
+
for (const candidate of attempts) {
|
|
73
|
+
try {
|
|
74
|
+
return { found: true, value: JSON.parse(candidate) };
|
|
75
|
+
}
|
|
76
|
+
catch { }
|
|
77
|
+
}
|
|
78
|
+
return { found: false };
|
|
79
|
+
}
|
|
80
|
+
function errorLine(e) {
|
|
81
|
+
const where = e.instancePath ? e.instancePath.replace(/^\//, '').replace(/\//g, '.') : 'the result';
|
|
82
|
+
const extra = e.keyword === 'additionalProperties' ? ` (${String(e.params.additionalProperty)})`
|
|
83
|
+
: e.keyword === 'enum' ? `: ${(e.params.allowedValues ?? []).map((v) => JSON.stringify(v)).join(', ')}`
|
|
84
|
+
: '';
|
|
85
|
+
return `${where} ${e.message ?? 'is not valid'}${extra}`;
|
|
86
|
+
}
|
|
87
|
+
/** A reply checked against a schema: its JSON when it matches, else
|
|
88
|
+
* what's wrong, a line each (at most 10). */
|
|
89
|
+
export function checkOutput(schema, text) {
|
|
90
|
+
const json = jsonInReply(text);
|
|
91
|
+
if (!json.found)
|
|
92
|
+
return { ok: false, errors: ['The reply has no JSON in it.'] };
|
|
93
|
+
const validate = validatorFor(schema);
|
|
94
|
+
if (validate(json.value))
|
|
95
|
+
return { ok: true, value: json.value };
|
|
96
|
+
return { ok: false, errors: (validate.errors ?? []).slice(0, 10).map(errorLine) };
|
|
97
|
+
}
|
|
98
|
+
/** What the agent is told, with the rest of its instructions. */
|
|
99
|
+
export function outputSchemaInstructions(schema) {
|
|
100
|
+
return `End with your result as JSON that matches this JSON Schema, and nothing after it (a short note before it is fine):\n\n\`\`\`json\n${JSON.stringify(schema, null, 2)}\n\`\`\``;
|
|
101
|
+
}
|
|
102
|
+
/** What the agent is told when its result didn't match. */
|
|
103
|
+
export function outputRetryMessage(errors) {
|
|
104
|
+
return `Your result doesn't match the workflow's output schema:\n${errors.map((e) => `- ${e}`).join('\n')}\n\nReply again with the corrected result as JSON matching the schema. Use what you already found; don't redo work or repeat any action that sends, posts or changes something.`;
|
|
105
|
+
}
|
package/dist/core/run-agent.js
CHANGED
|
@@ -24,6 +24,7 @@ import { loadMcpAbilityTools } from './mcp-abilities.js';
|
|
|
24
24
|
import { skillsForResult, skillsInHistory, toolSkillsFor } from './ability-skills.js';
|
|
25
25
|
import { systemTools, createAskUserTool, createScheduleTools, CliQuestionHandler, isDurableQuestionHandler } from './system-tools/index.js';
|
|
26
26
|
import { resolveHttpNotifier } from './http-notifier.js';
|
|
27
|
+
import { startTurnTrace } from './trace.js';
|
|
27
28
|
import { CRASH_RECOVERY_CONTINUATION } from './session-store.js';
|
|
28
29
|
export { systemTools } from './system-tools/index.js';
|
|
29
30
|
// Resolved relative to *this file's own location* (via import.meta.url),
|
|
@@ -504,10 +505,26 @@ async function buildTurnContext(config, modelCall, options) {
|
|
|
504
505
|
* fresh in each case) but mutated here via pushMessage, same as the
|
|
505
506
|
* single function this was split out of always did. */
|
|
506
507
|
async function runLoop(ctx, messages, newMessages, starterMessage) {
|
|
507
|
-
|
|
508
|
+
// The turn's trace (core/trace.ts): its prompt, each model call and each
|
|
509
|
+
// tool call, as they happen; what's left is written however it ends.
|
|
510
|
+
const trace = startTurnTrace(ctx.sessionId);
|
|
511
|
+
try {
|
|
512
|
+
return await runTracedLoop(ctx, trace, messages, newMessages, starterMessage);
|
|
513
|
+
}
|
|
514
|
+
finally {
|
|
515
|
+
trace.flush();
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
async function runTracedLoop(ctx, trace, messages, newMessages, starterMessage) {
|
|
519
|
+
const { modelCall, log: logEvent, scope, sessionId, skillGarden, toolSkills, skillText, toolsByName, systemToolInstances, toolSchemas, systemPrompt, budgetTracker, compactor, gate, toolLane, maxTurns, tailMessages, askUserTool, questionHandler, toolContext, modelLabel, evalMode, unattended } = ctx;
|
|
520
|
+
const log = (event) => {
|
|
521
|
+
trace.event(event);
|
|
522
|
+
logEvent(event);
|
|
523
|
+
};
|
|
508
524
|
function pushMessage(message) {
|
|
509
525
|
messages.push(message);
|
|
510
526
|
newMessages.push(message);
|
|
527
|
+
trace.message(message);
|
|
511
528
|
}
|
|
512
529
|
// See known-urls.ts's own doc comment — seeded once from this
|
|
513
530
|
// session's full prior history (a resumed session's own tool results,
|
|
@@ -557,6 +574,14 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
|
|
|
557
574
|
return recovered;
|
|
558
575
|
},
|
|
559
576
|
});
|
|
577
|
+
trace.start({
|
|
578
|
+
system: systemPrompt,
|
|
579
|
+
tools: toolSchemas.map((t) => t.name),
|
|
580
|
+
model: modelLabel,
|
|
581
|
+
history: [...messages],
|
|
582
|
+
starter: starterMessage,
|
|
583
|
+
resumed: typeof starterMessage.content !== 'string' && starterMessage.content.some((b) => b.type === 'tool_result'),
|
|
584
|
+
});
|
|
560
585
|
pushMessage(starterMessage);
|
|
561
586
|
let turn = 0;
|
|
562
587
|
let nudges = 0;
|
|
@@ -583,7 +608,15 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
|
|
|
583
608
|
// spent tokens and then failed is still counted.
|
|
584
609
|
const { value: response } = await recovery.call(async (msgs) => {
|
|
585
610
|
const started = Date.now();
|
|
586
|
-
|
|
611
|
+
let result;
|
|
612
|
+
try {
|
|
613
|
+
result = await modelCall(msgs, systemPrompt, toolSchemas);
|
|
614
|
+
}
|
|
615
|
+
catch (err) {
|
|
616
|
+
trace.llm({ sent: msgs, error: err, durationMs: Date.now() - started, model: modelLabel });
|
|
617
|
+
throw err;
|
|
618
|
+
}
|
|
619
|
+
trace.llm({ sent: msgs, response: result, durationMs: Date.now() - started, model: modelLabel });
|
|
587
620
|
if (result.usage) {
|
|
588
621
|
recordUsage({
|
|
589
622
|
at: new Date().toISOString(),
|
package/dist/core/scheduler.d.ts
CHANGED
|
@@ -114,6 +114,12 @@ export interface CreateScheduledTaskInput {
|
|
|
114
114
|
task_name?: string;
|
|
115
115
|
notify?: boolean;
|
|
116
116
|
}
|
|
117
|
+
/** A schedule as a task gives it, checked: what it's saved as and when it
|
|
118
|
+
* first runs. Throws ScheduleError saying what's wrong. */
|
|
119
|
+
export declare function parseScheduleInput(requested: CreateScheduledTaskInput['schedule'], nowMs?: number): {
|
|
120
|
+
schedule: Schedule;
|
|
121
|
+
nextRunMs: number;
|
|
122
|
+
};
|
|
117
123
|
export declare function createScheduledTask(input: CreateScheduledTaskInput, nowMs?: number): Promise<ScheduledTask>;
|
|
118
124
|
export declare function listScheduledTasks(filter?: {
|
|
119
125
|
agent?: string;
|
package/dist/core/scheduler.js
CHANGED
|
@@ -138,31 +138,25 @@ export function getSchedulerStore() {
|
|
|
138
138
|
export function setSchedulerStore(next) {
|
|
139
139
|
store = next;
|
|
140
140
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const message = typeof input.message === 'string' ? input.message : '';
|
|
145
|
-
const workflowId = typeof input.workflow_id === 'string' ? input.workflow_id.trim() : '';
|
|
146
|
-
if (message.trim() && workflowId)
|
|
147
|
-
throw new ScheduleError('give either a message or a workflow_id, not both');
|
|
148
|
-
if (!message.trim() && !workflowId)
|
|
149
|
-
throw new ScheduleError('message or workflow_id is required');
|
|
141
|
+
/** A schedule as a task gives it, checked: what it's saved as and when it
|
|
142
|
+
* first runs. Throws ScheduleError saying what's wrong. */
|
|
143
|
+
export function parseScheduleInput(requested, nowMs = Date.now()) {
|
|
150
144
|
let schedule;
|
|
151
145
|
let nextRunMs;
|
|
152
146
|
const timeZone = workspaceTimeZone();
|
|
153
|
-
if (typeof
|
|
154
|
-
const runAtMs = parseTimestamp(
|
|
147
|
+
if (typeof requested?.run_at === 'string' && requested.run_at) {
|
|
148
|
+
const runAtMs = parseTimestamp(requested.run_at, timeZone);
|
|
155
149
|
if (Number.isNaN(runAtMs))
|
|
156
|
-
throw new ScheduleError(`"${
|
|
150
|
+
throw new ScheduleError(`"${requested.run_at}" is not a valid ISO 8601 timestamp`);
|
|
157
151
|
schedule = { run_at: new Date(runAtMs).toISOString() };
|
|
158
152
|
nextRunMs = runAtMs;
|
|
159
153
|
}
|
|
160
|
-
else if (typeof
|
|
161
|
-
const every =
|
|
154
|
+
else if (typeof requested?.every === 'string' && requested.every) {
|
|
155
|
+
const every = requested.every.trim();
|
|
162
156
|
const intervalMs = parseEvery(every);
|
|
163
157
|
const days = everyDays(every);
|
|
164
158
|
const calendar = days ? { days, timeZone } : undefined;
|
|
165
|
-
const { start_at: startAt, at, weekday } =
|
|
159
|
+
const { start_at: startAt, at, weekday } = requested;
|
|
166
160
|
const given = (v) => v !== undefined && v !== null && v !== '';
|
|
167
161
|
let startMs;
|
|
168
162
|
if (given(at)) {
|
|
@@ -193,10 +187,22 @@ export async function createScheduledTask(input, nowMs = Date.now()) {
|
|
|
193
187
|
}
|
|
194
188
|
}
|
|
195
189
|
else {
|
|
196
|
-
if (
|
|
190
|
+
if (requested?.start_at || requested?.at)
|
|
197
191
|
throw new ScheduleError('start_at and at go with "every" (a repeating task); a one-off task uses run_at');
|
|
198
192
|
throw new ScheduleError('schedule must be { "run_at": "<ISO timestamp>" } or { "every": "<interval, e.g. 1h>", "start_at"?: "<ISO timestamp>" } or { "every": "1d", "at": "09:00" }');
|
|
199
193
|
}
|
|
194
|
+
return { schedule, nextRunMs };
|
|
195
|
+
}
|
|
196
|
+
export async function createScheduledTask(input, nowMs = Date.now()) {
|
|
197
|
+
if (!input.agent)
|
|
198
|
+
throw new ScheduleError('agent is required');
|
|
199
|
+
const message = typeof input.message === 'string' ? input.message : '';
|
|
200
|
+
const workflowId = typeof input.workflow_id === 'string' ? input.workflow_id.trim() : '';
|
|
201
|
+
if (message.trim() && workflowId)
|
|
202
|
+
throw new ScheduleError('give either a message or a workflow_id, not both');
|
|
203
|
+
if (!message.trim() && !workflowId)
|
|
204
|
+
throw new ScheduleError('message or workflow_id is required');
|
|
205
|
+
const { schedule, nextRunMs } = parseScheduleInput(input.schedule, nowMs);
|
|
200
206
|
const task = {
|
|
201
207
|
task_id: randomUUID(),
|
|
202
208
|
task_name: input.task_name?.trim() || undefined,
|
|
@@ -159,9 +159,9 @@ export interface GoalPipelineInput {
|
|
|
159
159
|
/** The focus the person chose, instead of the one the brief reads. */
|
|
160
160
|
focus?: GoalFocus | 'other';
|
|
161
161
|
}
|
|
162
|
-
export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". When none fits, focus \"other\" and newFocus: name the stage in a few generic words (label, e.g. \"Hiring\", \"Closing sales deals\", \"Personal health habits\") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't).\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- profile: what makes this goal different from others with the same focus. metric: the number it moves; direction: \"up\", \"down\", \"reach\" (a milestone) or \"keep\"; constraints: limits that rule approaches out (no budget, night shifts, vegetarian, an injury, only one market), from the goal and the context, empty when none; timeframe (\"by March\", \"unknown\"); startingPoint (first try, tried before, what's already in place, or \"unknown\"); bottleneck: what's most likely to stop this particular goal (for most weight goals it's sticking with it; for a new product it may be that nobody knows it exists), and bottleneckWhy in a sentence.\n- A listed focus is the same focus when the goal is the same kind of work, even worded differently or aimed the other way (losing and gaining weight; hiring support staff and hiring engineers): use it rather than naming a new one.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
|
|
163
|
-
export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each suggestion is one workflow (recurring work for one AI agent; a person reviews what it drafts), or a group of workflows that run in order. A small goal may need one or two workflows; a big one several, and groups.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many goals of this focus (no names of this business, its products, people, places or sites; no direction, target or amount when the approach works either way: \"a weekly meal routine toward the target\", not \"eat less\"), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n3b. Choose levers for this goal, not for the focus in general. Look at every lever listed: rule out one whose \"not when\", needs or the profile's constraints don't fit; prefer the ones that address the profile's bottleneck; pick ones that work in different ways (not three kinds of tracking). In considered, list every lever you looked at with chosen or ruled_out and a short reason tied to this goal (\"addresses sticking with it\", \"no gym: ruled out\"). Reuse a listed lever whenever its approach fits, even if it was written for a goal aimed the other way: put what's specific to this goal (the direction, the target, the details) in the workflow's request. Write a new lever only for what no listed lever covers.\n4.
|
|
164
|
-
export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- a measure whose source isn't connected, with no setup step (new or already on the goal) that connects it or a manual record, or no baseline;\n- more than four setup steps, a step longer than a sentence, or one that repeats or rewords a step already on the goal;\n- a qualifier from the brief no workflow addresses;\n- a suggestion for one-time work, or one on a finite list that will run out (it should be left out);\n- a title longer than six words, or one that names the mechanism (\"Send welcome emails\", \"Lead scan\") instead of the result it brings (\"Get new signups started\");\n- a group whose steps don't hand their result on, or with fewer than two or more than four steps;\n- a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;\n- a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
|
|
162
|
+
export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- A goal can be big or small. It may be a result to reach (more signups, fewer refunds, lose 5 kg) or work to hand off (research a topic and publish a weekly report, answer every customer email within a day). Both are \"in\" when agents can do the work.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". When none fits, focus \"other\" and newFocus: name the stage in a few generic words (label, e.g. \"Hiring\", \"Closing sales deals\", \"Personal health habits\") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't). For work to hand off, it's that work done well and on time (\"a report published every Monday\", \"emails answered within a day\"), with direction \"keep\".\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- profile: what makes this goal different from others with the same focus. metric: the number it moves; direction: \"up\", \"down\", \"reach\" (a milestone) or \"keep\"; constraints: limits that rule approaches out (no budget, night shifts, vegetarian, an injury, only one market), from the goal and the context, empty when none; timeframe (\"by March\", \"unknown\"); startingPoint (first try, tried before, what's already in place, or \"unknown\"); bottleneck: what's most likely to stop this particular goal (for most weight goals it's sticking with it; for a new product it may be that nobody knows it exists), and bottleneckWhy in a sentence.\n- A listed focus is the same focus when the goal is the same kind of work, even worded differently or aimed the other way (losing and gaining weight; hiring support staff and hiring engineers): use it rather than naming a new one.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
|
|
163
|
+
export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each suggestion is one workflow (recurring work for one AI agent; a person reviews what it drafts), or a group of workflows that run in order. A small goal may need one or two workflows; a big one several, and groups.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many goals of this focus (no names of this business, its products, people, places or sites; no direction, target or amount when the approach works either way: \"a weekly meal routine toward the target\", not \"eat less\"), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n3b. Choose levers for this goal, not for the focus in general. Look at every lever listed: rule out one whose \"not when\", needs or the profile's constraints don't fit; prefer the ones that address the profile's bottleneck; pick ones that work in different ways (not three kinds of tracking). In considered, list every lever you looked at with chosen or ruled_out and a short reason tied to this goal (\"addresses sticking with it\", \"no gym: ruled out\"). Reuse a listed lever whenever its approach fits, even if it was written for a goal aimed the other way: put what's specific to this goal (the direction, the target, the details) in the workflow's request. Write a new lever only for what no listed lever covers.\n4. As many workflows as the goal needs, no more. Work to hand off usually needs one workflow, or one group when it happens in stages (research, then draft, then publish); add others only when they clearly make that work better. A result to reach, like growth, usually needs three to five. Order them by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.\n4b. Every suggestion runs again and again (a weekly scan, a reply to each signup). Work done one time or on a finite list (a one-time audit, submitting to a set list of directories) isn't a workflow: leave it out, or say in setup what the person does once. Never make a weekly workflow that runs out of things to do.\n4c. measure: its own number, in the person's terms, that shows it's working (\"replies per week\", \"signups tagged ref=directories\"). A playbook lever says the measure it usually has: start from it, and change it only when the context calls for it.\n4d. title: the result it brings, in plain words, at most six words: \"Reach new leads every week\", \"Get new signups started\", \"Answer refund requests the same day\". Short enough to read at a glance on a card, keeping the one detail that tells it apart (where or who: \"Answer AI-agent questions on Reddit\"); the other details go in measure, why and request. Not the mechanism (\"Lead scan\", \"Send welcome emails\"): that's a workflow's name.\n4e. group: make a group instead of one workflow when the work happens in stages that hand their result on, each better as its own workflow (its own agent, tools or review): find leads, then draft outreach to each; collect reviews, then reply to the bad ones. Two to four steps, in the order they run; the next starts when the one before finishes and is given its result. Each step has a name (a short label, two or three words, like a workflow's: \"Lead scan\", \"Outreach draft\"), its own request, specific to this context, its agent and needs. The group's title, measure, lever and mechanism are for the whole; leave its request and agent the first step's. Don't group workflows that don't hand anything on: suggest them separately. Approval isn't a step: every workflow already waits for the person's approval before it sends, posts or publishes, so the step that publishes does it after approval.\n5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.\n6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.\n7. Every request that posts, sends or publishes says nothing goes out without the person's approval.\n8. The measure must be readable. For work to hand off, the workflows' own runs show it's done: no baseline, source or manual record is needed unless the brief's measure is a number beyond that. Otherwise, when measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. \"connect Clerk's user.created webhook so signups and their ref are recorded\"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.\n8b. setup: what the person does once before the workflows start, at most four steps, each one short sentence (about 20 words at most) saying the action, not the reasoning. When the request lists setup already on the goal, add only what those steps don't cover, usually nothing: never repeat or reword one (the baseline, the signup link, the manual record are said once).\n8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.\n9. \"partial\" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message (\"helps you pursue\", never \"achieves\"). \"out\" scope: no workflows; the message says plainly why, and offers a smaller or related goal.\n10. agent: an existing agent's exact name when its work fits. When none fits, or there are no agents yet, suggest a new one: agent and newAgent.name the same short lowercase name with hyphens (e.g. \"community-agent\"), and newAgent.instructions two or three sentences on what it does and how it behaves. Group workflows that belong together in one agent rather than one agent each.\n\nCall save_plan once.";
|
|
164
|
+
export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- for a result to reach, a measure whose source isn't connected, with no setup step (new or already on the goal) that connects it or a manual record, or no baseline;\n- more than four setup steps, a step longer than a sentence, or one that repeats or rewords a step already on the goal;\n- a qualifier from the brief no workflow addresses;\n- for work to hand off, a setup step for a baseline or a manual record (its runs show it's done);\n- a group step that only approves or reviews (approval is built into every workflow);\n- workflows a small goal didn't need, added to fill out the plan (work to hand off may need just one workflow or one group);\n- a suggestion for one-time work, or one on a finite list that will run out (it should be left out);\n- a title longer than six words, or one that names the mechanism (\"Send welcome emails\", \"Lead scan\") instead of the result it brings (\"Get new signups started\");\n- a group whose steps don't hand their result on, or with fewer than two or more than four steps;\n- a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;\n- a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
|
|
165
165
|
/** A job a person added in their own words, shaped like a planned one. */
|
|
166
166
|
export declare const GOAL_ADD_JOB_PROMPT = "A person adds a workflow of their own to a goal in LoopEngine, in their own words. Shape it into one suggestion like a planner's (a workflow, or a group of workflows that run in order when the idea has stages that hand their result on), and judge it honestly; it's their business, so advise, don't lecture.\n\nShape it:\n- title: the result it brings, in plain words, at most six words (\"Get weekly sales to the team\", \"Answer customer emails within an hour\"). When the person wrote a long or mechanism-style idea (\"send a weekly sales summary to the team every Monday\"), keep their meaning and the detail that sets it apart (where or who) in a short title, and put the details in measure and request; the mechanism becomes the workflow's name later.\n- measure (its own number), why it moves the goal (mechanism), the agent (an existing agent's exact name when its work fits, else newAgent with a short name and two or three sentences of instructions), needs (connected only when the context lists it), humanMinutesPerWeek, and a request specific to this business that the agent can act on. Anything that posts, sends or publishes says nothing goes out without the person's approval.\n- lever: when it's one of the playbook levers listed, its id in leverId. When none fits, write one generic lever in newLever (one approach, no names of this business, its products, people, places or sites; when it fits and doesn't; what it needs; how its effect shows up; guardrails; a generic template) and put its key in leverId.\n\nJudge it, in verdict:\n- \"added\": it fits the goal and is safe.\n- \"changed\": a sound idea with risky details you changed (an approval added, volume limited, a platform's rules respected); say what you changed in note.\n- \"warned\": it's safe but unlikely to move the goal's measure, repeats a workflow already under the goal, is one-time work rather than something that repeats, or is unlikely to work; say why in note and give a better-aimed alternative.\n- \"refused\": it's deceptive, illegal or against a platform's rules (fake reviews or accounts, spam, buying followers, harvesting private data, impersonation, misleading claims) or could harm people. Don't shape it; say why in note, plainly and briefly, and give a legitimate alternative.\n\nWhen there is no goal, judge it on its own: \"added\" when it suits this business and is safe; \"warned\" when it's unlikely to work or repeats a workflow already listed. Its mechanism is what it gets done for the business, and it has no lever: leave leverId and newLever out.\n\nCall save_job once.";
|
|
167
167
|
export interface ShapedJob {
|
|
@@ -7,9 +7,10 @@ export const GOAL_BRIEF_PROMPT = `You read a goal someone gives LoopEngine, a pl
|
|
|
7
7
|
|
|
8
8
|
Call save_brief once:
|
|
9
9
|
- scope: "in" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all "in"); "partial" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; "out" when there is nothing useful an agent could do. scopeReason: one sentence.
|
|
10
|
+
- A goal can be big or small. It may be a result to reach (more signups, fewer refunds, lose 5 kg) or work to hand off (research a topic and publish a weekly report, answer every customer email within a day). Both are "in" when agents can do the work.
|
|
10
11
|
- reading: how you read it. When the wording could be a metaphor ("land on the moon", "climb Everest" said of a business), prefer the reading the context supports and say which.
|
|
11
12
|
- focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means "new-signups" unless the goal speaks of using, keeping or activating people. Answering customers sooner is "faster-support". When none fits, focus "other" and newFocus: name the stage in a few generic words (label, e.g. "Hiring", "Closing sales deals", "Personal health habits") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.
|
|
12
|
-
- measure: the number that shows progress, in the person's terms, with what is known about its current value ("unknown" when it isn't).
|
|
13
|
+
- measure: the number that shows progress, in the person's terms, with what is known about its current value ("unknown" when it isn't). For work to hand off, it's that work done well and on time ("a report published every Monday", "emails answered within a day"), with direction "keep".
|
|
13
14
|
- measureSource: the system in the context that holds that number ("none" when no system does), and measureSourceConnected: true only when the context lists that system as connected.
|
|
14
15
|
- qualifiers: what the goal singles out beyond its main outcome, in its own words ("mostly small e-commerce shops", "especially refunds", "this Christmas"); empty when it singles out nothing.
|
|
15
16
|
- profile: what makes this goal different from others with the same focus. metric: the number it moves; direction: "up", "down", "reach" (a milestone) or "keep"; constraints: limits that rule approaches out (no budget, night shifts, vegetarian, an injury, only one market), from the goal and the context, empty when none; timeframe ("by March", "unknown"); startingPoint (first try, tried before, what's already in place, or "unknown"); bottleneck: what's most likely to stop this particular goal (for most weight goals it's sticking with it; for a new product it may be that nobody knows it exists), and bottleneckWhy in a sentence.
|
|
@@ -23,15 +24,15 @@ Rules:
|
|
|
23
24
|
2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.
|
|
24
25
|
3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: "list in app marketplaces", not "list Wick & Ember on Shopify"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.
|
|
25
26
|
3b. Choose levers for this goal, not for the focus in general. Look at every lever listed: rule out one whose "not when", needs or the profile's constraints don't fit; prefer the ones that address the profile's bottleneck; pick ones that work in different ways (not three kinds of tracking). In considered, list every lever you looked at with chosen or ruled_out and a short reason tied to this goal ("addresses sticking with it", "no gym: ruled out"). Reuse a listed lever whenever its approach fits, even if it was written for a goal aimed the other way: put what's specific to this goal (the direction, the target, the details) in the workflow's request. Write a new lever only for what no listed lever covers.
|
|
26
|
-
4.
|
|
27
|
+
4. As many workflows as the goal needs, no more. Work to hand off usually needs one workflow, or one group when it happens in stages (research, then draft, then publish); add others only when they clearly make that work better. A result to reach, like growth, usually needs three to five. Order them by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.
|
|
27
28
|
4b. Every suggestion runs again and again (a weekly scan, a reply to each signup). Work done one time or on a finite list (a one-time audit, submitting to a set list of directories) isn't a workflow: leave it out, or say in setup what the person does once. Never make a weekly workflow that runs out of things to do.
|
|
28
29
|
4c. measure: its own number, in the person's terms, that shows it's working ("replies per week", "signups tagged ref=directories"). A playbook lever says the measure it usually has: start from it, and change it only when the context calls for it.
|
|
29
30
|
4d. title: the result it brings, in plain words, at most six words: "Reach new leads every week", "Get new signups started", "Answer refund requests the same day". Short enough to read at a glance on a card, keeping the one detail that tells it apart (where or who: "Answer AI-agent questions on Reddit"); the other details go in measure, why and request. Not the mechanism ("Lead scan", "Send welcome emails"): that's a workflow's name.
|
|
30
|
-
4e. group: make a group instead of one workflow when the work happens in stages that hand their result on, each better as its own workflow (its own agent, tools or review): find leads, then draft outreach to each; collect reviews, then reply to the bad ones. Two to four steps, in the order they run; the next starts when the one before finishes and is given its result. Each step has a name (a short label, two or three words, like a workflow's: "Lead scan", "Outreach draft"), its own request, specific to this context, its agent and needs. The group's title, measure, lever and mechanism are for the whole; leave its request and agent the first step's. Don't group workflows that don't hand anything on: suggest them separately.
|
|
31
|
+
4e. group: make a group instead of one workflow when the work happens in stages that hand their result on, each better as its own workflow (its own agent, tools or review): find leads, then draft outreach to each; collect reviews, then reply to the bad ones. Two to four steps, in the order they run; the next starts when the one before finishes and is given its result. Each step has a name (a short label, two or three words, like a workflow's: "Lead scan", "Outreach draft"), its own request, specific to this context, its agent and needs. The group's title, measure, lever and mechanism are for the whole; leave its request and agent the first step's. Don't group workflows that don't hand anything on: suggest them separately. Approval isn't a step: every workflow already waits for the person's approval before it sends, posts or publishes, so the step that publishes does it after approval.
|
|
31
32
|
5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.
|
|
32
33
|
6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.
|
|
33
34
|
7. Every request that posts, sends or publishes says nothing goes out without the person's approval.
|
|
34
|
-
8. The measure must be readable.
|
|
35
|
+
8. The measure must be readable. For work to hand off, the workflows' own runs show it's done: no baseline, source or manual record is needed unless the brief's measure is a number beyond that. Otherwise, when measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. "connect Clerk's user.created webhook so signups and their ref are recorded"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.
|
|
35
36
|
8b. setup: what the person does once before the workflows start, at most four steps, each one short sentence (about 20 words at most) saying the action, not the reasoning. When the request lists setup already on the goal, add only what those steps don't cover, usually nothing: never repeat or reword one (the baseline, the signup link, the manual record are said once).
|
|
36
37
|
8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.
|
|
37
38
|
9. "partial" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message ("helps you pursue", never "achieves"). "out" scope: no workflows; the message says plainly why, and offers a smaller or related goal.
|
|
@@ -45,9 +46,12 @@ export const GOAL_CRITIQUE_PROMPT = `You check a goal plan against its rules bef
|
|
|
45
46
|
- a need marked connected that the context doesn't list as connected;
|
|
46
47
|
- a request that posts, sends or publishes without saying it waits for approval;
|
|
47
48
|
- review time over three quarters of the weekly budget;
|
|
48
|
-
- a measure whose source isn't connected, with no setup step (new or already on the goal) that connects it or a manual record, or no baseline;
|
|
49
|
+
- for a result to reach, a measure whose source isn't connected, with no setup step (new or already on the goal) that connects it or a manual record, or no baseline;
|
|
49
50
|
- more than four setup steps, a step longer than a sentence, or one that repeats or rewords a step already on the goal;
|
|
50
51
|
- a qualifier from the brief no workflow addresses;
|
|
52
|
+
- for work to hand off, a setup step for a baseline or a manual record (its runs show it's done);
|
|
53
|
+
- a group step that only approves or reviews (approval is built into every workflow);
|
|
54
|
+
- workflows a small goal didn't need, added to fill out the plan (work to hand off may need just one workflow or one group);
|
|
51
55
|
- a suggestion for one-time work, or one on a finite list that will run out (it should be left out);
|
|
52
56
|
- a title longer than six words, or one that names the mechanism ("Send welcome emails", "Lead scan") instead of the result it brings ("Get new signups started");
|
|
53
57
|
- a group whose steps don't hand their result on, or with fewer than two or more than four steps;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { LoopEvent } from './loop-events.js';
|
|
2
|
+
import type { Message, ModelResponse } from './run-agent.js';
|
|
3
|
+
export interface TurnTrace {
|
|
4
|
+
/** The turn begins: `history` is what came before it (never repeated). */
|
|
5
|
+
start(input: {
|
|
6
|
+
system: string;
|
|
7
|
+
tools: string[];
|
|
8
|
+
model: {
|
|
9
|
+
provider?: string;
|
|
10
|
+
model?: string;
|
|
11
|
+
};
|
|
12
|
+
history: Message[];
|
|
13
|
+
starter: Message;
|
|
14
|
+
resumed: boolean;
|
|
15
|
+
}): void;
|
|
16
|
+
/** A model call: the messages sent, and what came back or the error. */
|
|
17
|
+
llm(call: {
|
|
18
|
+
sent: Message[];
|
|
19
|
+
response?: ModelResponse;
|
|
20
|
+
error?: unknown;
|
|
21
|
+
durationMs: number;
|
|
22
|
+
model: {
|
|
23
|
+
provider?: string;
|
|
24
|
+
model?: string;
|
|
25
|
+
};
|
|
26
|
+
}): void;
|
|
27
|
+
/** A message added to the conversation (tool results among them). */
|
|
28
|
+
message(message: Message): void;
|
|
29
|
+
/** The loop's own events: tool calls starting and resolving. */
|
|
30
|
+
event(event: LoopEvent): void;
|
|
31
|
+
/** Writes what's left: tool calls that finished since the last call. */
|
|
32
|
+
flush(): void;
|
|
33
|
+
}
|
|
34
|
+
export declare function startTurnTrace(sessionId: string | undefined): TurnTrace;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { auditDb, pruneTraces, recordTracePrompt, recordTraceSpan } from './audit-store.js';
|
|
2
|
+
const NONE = { start() { }, llm() { }, message() { }, event() { }, flush() { } };
|
|
3
|
+
const blocksOf = (m) => (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content);
|
|
4
|
+
export function startTurnTrace(sessionId) {
|
|
5
|
+
if (!sessionId || !auditDb())
|
|
6
|
+
return NONE;
|
|
7
|
+
pruneTraces();
|
|
8
|
+
// Messages (and model replies, by their content) a step already shows.
|
|
9
|
+
const shownSet = new WeakSet();
|
|
10
|
+
const shown = {
|
|
11
|
+
add: (v) => { if (v && typeof v === 'object')
|
|
12
|
+
shownSet.add(v); },
|
|
13
|
+
has: (v) => Boolean(v && typeof v === 'object' && shownSet.has(v)),
|
|
14
|
+
};
|
|
15
|
+
const calls = new Map();
|
|
16
|
+
const order = [];
|
|
17
|
+
// Every tool call a model reply asked for, by its id: its name and input.
|
|
18
|
+
const asked = new Map();
|
|
19
|
+
const noteAsked = (messages) => {
|
|
20
|
+
for (const b of messages.flatMap(blocksOf))
|
|
21
|
+
if (b.type === 'tool_use' && b.id)
|
|
22
|
+
asked.set(b.id, { ...(b.name ? { name: b.name } : {}), ...(b.input ? { input: b.input } : {}) });
|
|
23
|
+
};
|
|
24
|
+
const callFor = (id, tool) => {
|
|
25
|
+
let call = calls.get(id);
|
|
26
|
+
if (!call) {
|
|
27
|
+
// A call with no start event (a built-in like Skill, or one from
|
|
28
|
+
// before this turn, resumed after an approval): its name and input
|
|
29
|
+
// are on the model reply that asked for it.
|
|
30
|
+
const request = asked.get(id);
|
|
31
|
+
call = { tool: tool ?? request?.name ?? 'tool', ...(request?.input ? { args: request.input } : {}), at: new Date().toISOString() };
|
|
32
|
+
calls.set(id, call);
|
|
33
|
+
order.push(id);
|
|
34
|
+
}
|
|
35
|
+
return call;
|
|
36
|
+
};
|
|
37
|
+
const writeTools = () => {
|
|
38
|
+
for (const id of order) {
|
|
39
|
+
const call = calls.get(id);
|
|
40
|
+
if (call.written || (call.status === undefined && call.output === undefined))
|
|
41
|
+
continue;
|
|
42
|
+
call.written = true;
|
|
43
|
+
recordTraceSpan({
|
|
44
|
+
sessionId,
|
|
45
|
+
at: call.at,
|
|
46
|
+
kind: 'tool',
|
|
47
|
+
name: call.tool,
|
|
48
|
+
...(call.startedAt && call.endedAt ? { durationMs: Math.max(0, call.endedAt - call.startedAt) } : {}),
|
|
49
|
+
...(call.args ? { input: call.args } : {}),
|
|
50
|
+
...(call.output !== undefined ? { output: call.output } : {}),
|
|
51
|
+
...(call.isError ? { error: typeof call.output === 'string' ? call.output.slice(0, 500) : 'The tool returned an error.' } : {}),
|
|
52
|
+
// A built-in that reports no status (Skill): done, or failed.
|
|
53
|
+
meta: { toolUseId: id, status: call.status ?? (call.isError ? 'Failed.' : 'Done.') },
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
return safe({
|
|
58
|
+
start(input) {
|
|
59
|
+
noteAsked(input.history);
|
|
60
|
+
for (const m of input.history) {
|
|
61
|
+
shown.add(m);
|
|
62
|
+
shown.add(m.content);
|
|
63
|
+
}
|
|
64
|
+
shown.add(input.starter);
|
|
65
|
+
const systemHash = recordTracePrompt(input.system);
|
|
66
|
+
recordTraceSpan({
|
|
67
|
+
sessionId,
|
|
68
|
+
at: new Date().toISOString(),
|
|
69
|
+
kind: 'prompt',
|
|
70
|
+
input: { ...(systemHash ? { systemHash } : { system: input.system }), tools: input.tools, model: input.model, start: input.starter.content, priorMessages: input.history.length },
|
|
71
|
+
meta: { resumed: input.resumed },
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
llm(call) {
|
|
75
|
+
writeTools();
|
|
76
|
+
const fresh = call.sent.filter((m) => !shown.has(m) && !shown.has(m.content));
|
|
77
|
+
for (const m of call.sent)
|
|
78
|
+
shown.add(m);
|
|
79
|
+
if (call.response) {
|
|
80
|
+
shown.add(call.response.content);
|
|
81
|
+
noteAsked([{ role: 'assistant', content: call.response.content }]);
|
|
82
|
+
}
|
|
83
|
+
const usage = call.response?.usage;
|
|
84
|
+
recordTraceSpan({
|
|
85
|
+
sessionId,
|
|
86
|
+
at: new Date(Date.now() - call.durationMs).toISOString(),
|
|
87
|
+
kind: 'llm',
|
|
88
|
+
name: call.model.model ?? 'model',
|
|
89
|
+
durationMs: call.durationMs,
|
|
90
|
+
input: fresh,
|
|
91
|
+
...(call.response ? { output: call.response.content } : {}),
|
|
92
|
+
...(call.error !== undefined ? { error: call.error instanceof Error ? call.error.message : String(call.error) } : {}),
|
|
93
|
+
meta: {
|
|
94
|
+
...call.model,
|
|
95
|
+
sent: call.sent.length,
|
|
96
|
+
...(usage ? { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } : {}),
|
|
97
|
+
...(call.response?.stop_reason ? { stopReason: call.response.stop_reason } : {}),
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
},
|
|
101
|
+
message(message) {
|
|
102
|
+
for (const b of blocksOf(message)) {
|
|
103
|
+
if (b.type !== 'tool_result' || !b.tool_use_id)
|
|
104
|
+
continue;
|
|
105
|
+
const call = callFor(b.tool_use_id);
|
|
106
|
+
call.output = b.content;
|
|
107
|
+
call.endedAt ??= Date.now();
|
|
108
|
+
if (b.is_error)
|
|
109
|
+
call.isError = true;
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
event(e) {
|
|
113
|
+
if (e.type === 'tool:started') {
|
|
114
|
+
const call = callFor(e.id, e.tool);
|
|
115
|
+
call.startedAt = Date.now();
|
|
116
|
+
call.at = new Date().toISOString();
|
|
117
|
+
call.args = e.args;
|
|
118
|
+
}
|
|
119
|
+
else if (e.type === 'tool:result') {
|
|
120
|
+
const call = callFor(e.id, e.tool);
|
|
121
|
+
call.status = e.statusText;
|
|
122
|
+
call.endedAt ??= Date.now();
|
|
123
|
+
if (e.args && !call.args)
|
|
124
|
+
call.args = e.args;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
flush() {
|
|
128
|
+
writeTools();
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
// Every method, made unable to throw into the turn.
|
|
133
|
+
function safe(trace) {
|
|
134
|
+
const guard = (name, fn) => (...args) => {
|
|
135
|
+
try {
|
|
136
|
+
fn(...args);
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
console.error(`[loopengine] trace ${name} failed:`, err instanceof Error ? err.message : err);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
start: guard('start', trace.start),
|
|
144
|
+
llm: guard('llm', trace.llm),
|
|
145
|
+
message: guard('message', trace.message),
|
|
146
|
+
event: guard('event', trace.event),
|
|
147
|
+
flush: guard('flush', trace.flush),
|
|
148
|
+
};
|
|
149
|
+
}
|