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.
Files changed (48) hide show
  1. package/dist/core/audit-store.d.ts +71 -8
  2. package/dist/core/audit-store.js +206 -12
  3. package/dist/core/input-schema.d.ts +47 -0
  4. package/dist/core/input-schema.js +180 -0
  5. package/dist/core/output-schema.d.ts +30 -0
  6. package/dist/core/output-schema.js +105 -0
  7. package/dist/core/run-agent.js +35 -2
  8. package/dist/core/scheduler.d.ts +6 -0
  9. package/dist/core/scheduler.js +22 -16
  10. package/dist/core/system-agents/goal-planner.d.ts +3 -3
  11. package/dist/core/system-agents/goal-planner.js +9 -5
  12. package/dist/core/trace.d.ts +34 -0
  13. package/dist/core/trace.js +149 -0
  14. package/dist/core/workflow-runs.d.ts +30 -5
  15. package/dist/core/workflow-runs.js +62 -12
  16. package/dist/core/workflow-triggers.d.ts +8 -1
  17. package/dist/core/workflow-triggers.js +13 -0
  18. package/dist/core/workflows.d.ts +17 -1
  19. package/dist/core/workflows.js +72 -9
  20. package/dist/index.d.ts +6 -2
  21. package/dist/index.js +6 -2
  22. package/dist/web/agents-config-page.js +372 -67
  23. package/dist/web/audit-admin.d.ts +2 -2
  24. package/dist/web/audit-admin.js +5 -3
  25. package/dist/web/audit-page.js +7 -5
  26. package/dist/web/change-log.js +4 -2
  27. package/dist/web/console-shell.js +1 -1
  28. package/dist/web/decide-page.js +1 -1
  29. package/dist/web/goals-admin.d.ts +8 -5
  30. package/dist/web/goals-admin.js +25 -5
  31. package/dist/web/goals-page.js +28 -8
  32. package/dist/web/home-page.js +3 -3
  33. package/dist/web/inbox-page.js +143 -1
  34. package/dist/web/run-trace.d.ts +114 -0
  35. package/dist/web/run-trace.js +79 -0
  36. package/dist/web/upgrade-admin.js +19 -5
  37. package/dist/web/workflow-admin.d.ts +12 -3
  38. package/dist/web/workflow-admin.js +42 -7
  39. package/dist/web/workflow-audit-report.js +5 -5
  40. package/dist/web/workflow-audit.d.ts +3 -3
  41. package/dist/web/workflow-audit.js +12 -11
  42. package/dist/web/workflow-drafts.d.ts +75 -0
  43. package/dist/web/workflow-drafts.js +112 -0
  44. package/dist/web/workflow-evidence.d.ts +17 -4
  45. package/dist/web/workflow-evidence.js +22 -6
  46. package/dist/web/workflow-health.d.ts +2 -2
  47. package/dist/web/workflow-health.js +7 -1
  48. package/package.json +9 -1
@@ -0,0 +1,114 @@
1
+ import type { AuditEvent, TraceSpan } from '../core/audit-store.js';
2
+ import type { UsageRow } from '../core/usage.js';
3
+ import { type WorkflowRun } from '../core/workflow-runs.js';
4
+ export interface TraceToolCall {
5
+ id: string;
6
+ name: string;
7
+ input: unknown;
8
+ output: unknown;
9
+ /** Allowed, approved, denied, skipped, or not run (a test run). */
10
+ status: string | null;
11
+ error: string | null;
12
+ started_at: string;
13
+ duration_ms: number | null;
14
+ }
15
+ export type TraceStepEvent = {
16
+ type: 'prompt';
17
+ at: string;
18
+ resumed: boolean;
19
+ system: string;
20
+ tools: string[];
21
+ input: unknown;
22
+ prior_messages: number;
23
+ } | {
24
+ type: 'model_call';
25
+ at: string;
26
+ duration_ms: number | null;
27
+ model: string | null;
28
+ input: unknown;
29
+ output: unknown;
30
+ input_tokens: number | null;
31
+ output_tokens: number | null;
32
+ messages_sent: number | null;
33
+ stop_reason: string | null;
34
+ error: string | null;
35
+ } | ({
36
+ type: 'tool_call';
37
+ at: string;
38
+ } & Omit<TraceToolCall, 'started_at'>) | {
39
+ type: 'decision';
40
+ at: string;
41
+ tool: string;
42
+ approved: boolean;
43
+ changed: boolean;
44
+ by: string | null;
45
+ reason: string | null;
46
+ } | {
47
+ type: 'answer';
48
+ at: string;
49
+ question: string;
50
+ answer: string;
51
+ by: string | null;
52
+ } | {
53
+ type: 'feedback';
54
+ at: string;
55
+ by: string | null;
56
+ verdict: string | null;
57
+ edit: string | null;
58
+ note: string | null;
59
+ };
60
+ export interface RunTrace {
61
+ execution_id: string;
62
+ agent: string;
63
+ workflow_id: string;
64
+ /** The workflow version it ran under (core/audit-store.ts), and that
65
+ * version's id, "<workflow>@v<number>". */
66
+ workflow_version: number | null;
67
+ workflow_version_id: string | null;
68
+ status: WorkflowRun['status'];
69
+ started_at: string;
70
+ finished_at: string | null;
71
+ input: {
72
+ params: Record<string, string>;
73
+ message: string;
74
+ };
75
+ final_output: string | null;
76
+ /** The result's JSON, for a workflow with an output schema, once it
77
+ * matched; and the check: valid (null without a schema), how many
78
+ * times the agent was asked again, and what was wrong last. */
79
+ final_output_json: unknown;
80
+ output_schema_check: {
81
+ valid: boolean | null;
82
+ retries: number;
83
+ errors: string[];
84
+ };
85
+ model: {
86
+ provider: string | null;
87
+ model: string;
88
+ } | null;
89
+ tool_calls: TraceToolCall[];
90
+ step_events: TraceStepEvent[];
91
+ error: string | null;
92
+ duration_ms: number | null;
93
+ /** usd is null unless every model call's model has a price. */
94
+ cost: {
95
+ usd: number | null;
96
+ input_tokens: number;
97
+ output_tokens: number;
98
+ model_calls: number;
99
+ model_ms: number;
100
+ };
101
+ feedback: {
102
+ verdict: string | null;
103
+ edit: string | null;
104
+ final_output_used: string | null;
105
+ note: string | null;
106
+ at: string;
107
+ } | null;
108
+ }
109
+ export declare function buildRunTrace(input: {
110
+ run: WorkflowRun;
111
+ spans: TraceSpan[];
112
+ usage: UsageRow[];
113
+ events: AuditEvent[];
114
+ }): RunTrace;
@@ -0,0 +1,79 @@
1
+ import { workflowVersionOf } from '../core/workflow-runs.js';
2
+ const str = (v) => (typeof v === 'string' && v ? v : null);
3
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
4
+ export function buildRunTrace(input) {
5
+ const { run, spans, usage } = input;
6
+ const version = workflowVersionOf(run) ?? null;
7
+ const toolCalls = [];
8
+ const steps = spans.map((s) => {
9
+ if (s.kind === 'prompt') {
10
+ const p = (s.input ?? {});
11
+ return { type: 'prompt', at: s.at, resumed: s.meta?.resumed === true, system: p.system ?? '', tools: p.tools ?? [], input: p.start ?? null, prior_messages: p.priorMessages ?? 0 };
12
+ }
13
+ if (s.kind === 'llm') {
14
+ return {
15
+ type: 'model_call', at: s.at, duration_ms: s.durationMs ?? null, model: s.name ?? null, input: s.input ?? [], output: s.output ?? null,
16
+ input_tokens: num(s.meta?.inputTokens), output_tokens: num(s.meta?.outputTokens), messages_sent: num(s.meta?.sent), stop_reason: str(s.meta?.stopReason), error: s.error ?? null,
17
+ };
18
+ }
19
+ const call = {
20
+ id: str(s.meta?.toolUseId) ?? String(s.id),
21
+ name: s.name ?? 'tool',
22
+ input: s.input ?? null,
23
+ output: s.output ?? null,
24
+ status: str(s.meta?.status),
25
+ error: s.error ?? null,
26
+ started_at: s.at,
27
+ duration_ms: s.durationMs ?? null,
28
+ };
29
+ toolCalls.push(call);
30
+ const { started_at: at, ...rest } = call;
31
+ return { type: 'tool_call', at, ...rest };
32
+ });
33
+ for (const d of run.decisions ?? [])
34
+ steps.push({ type: 'decision', at: d.at, tool: d.tool, approved: d.approved, changed: Boolean(d.edited), by: d.by ?? null, reason: d.reason ?? null });
35
+ for (const a of run.answers ?? [])
36
+ steps.push({ type: 'answer', at: a.at, question: a.question, answer: a.answer, by: a.by ?? null });
37
+ for (const e of input.events.filter((x) => x.kind === 'feedback')) {
38
+ steps.push({ type: 'feedback', at: e.at, by: e.by ?? null, verdict: str(e.data.verdict), edit: str(e.data.edit), note: str(e.data.note) });
39
+ }
40
+ // In time order; a step and a decision at the same moment keep their place.
41
+ const order = new Map(steps.map((s, i) => [s, i]));
42
+ steps.sort((a, b) => a.at.localeCompare(b.at) || order.get(a) - order.get(b));
43
+ const firstCall = spans.find((s) => s.kind === 'llm');
44
+ const firstPrompt = spans.find((s) => s.kind === 'prompt')?.input;
45
+ const modelName = str(firstCall?.meta?.model) ?? firstPrompt?.model?.model ?? usage[0]?.model ?? null;
46
+ const provider = str(firstCall?.meta?.provider) ?? firstPrompt?.model?.provider ?? usage[0]?.provider ?? null;
47
+ const priced = usage.length > 0 && usage.every((u) => u.costUsd != null);
48
+ return {
49
+ execution_id: run.run_id,
50
+ agent: run.agent,
51
+ workflow_id: run.workflow_id,
52
+ workflow_version: version,
53
+ workflow_version_id: version ? `${run.workflow_id}@v${version}` : null,
54
+ status: run.status,
55
+ started_at: run.started_at,
56
+ finished_at: run.finished_at ?? null,
57
+ input: { params: run.params ?? {}, message: run.message },
58
+ final_output: run.result ?? null,
59
+ final_output_json: run.output ?? null,
60
+ output_schema_check: {
61
+ valid: run.output !== undefined ? true : run.output_errors?.length && run.status === 'error' ? false : null,
62
+ retries: run.output_retries ?? 0,
63
+ errors: run.output_errors ?? [],
64
+ },
65
+ model: modelName ? { provider, model: modelName } : null,
66
+ tool_calls: toolCalls,
67
+ step_events: steps,
68
+ error: run.error ?? null,
69
+ duration_ms: run.finished_at ? Math.max(0, Date.parse(run.finished_at) - Date.parse(run.started_at)) : null,
70
+ cost: {
71
+ usd: priced ? usage.reduce((n, u) => n + u.costUsd, 0) : null,
72
+ input_tokens: usage.reduce((n, u) => n + u.inputTokens, 0),
73
+ output_tokens: usage.reduce((n, u) => n + u.outputTokens, 0),
74
+ model_calls: usage.length,
75
+ model_ms: usage.reduce((n, u) => n + (u.durationMs ?? 0), 0),
76
+ },
77
+ feedback: run.feedback ? { verdict: run.feedback.verdict ?? null, edit: run.feedback.edit ?? null, final_output_used: run.feedback.final ?? null, note: run.feedback.note ?? null, at: run.feedback.at } : null,
78
+ };
79
+ }
@@ -59,8 +59,19 @@ async function latestVersions(projectDir) {
59
59
  latestCache = { value, template, until: Date.now() + 60_000, at: new Date().toISOString() };
60
60
  return latestCache;
61
61
  }
62
- async function latestLoopengine(projectDir) {
63
- return (await latestVersions(projectDir)).value;
62
+ /** The newest version of a package that the project's package.json
63
+ * allows (npm lists the matching ones, oldest first). */
64
+ async function newestWithinRange(name, projectDir) {
65
+ try {
66
+ const range = JSON.parse(readFileSync(join(projectDir, 'package.json'), 'utf8')).dependencies?.[name];
67
+ if (!range)
68
+ return null;
69
+ const parsed = JSON.parse((await run('npm', ['view', `${name}@${range}`, 'version', '--json'], projectDir, 15_000)).trim() || 'null');
70
+ return (Array.isArray(parsed) ? parsed[parsed.length - 1] : parsed) ?? null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
64
75
  }
65
76
  function templateVersion(projectDir) {
66
77
  const path = join(projectDir, '.create-loopengine.json');
@@ -159,9 +170,12 @@ export async function runUpgrade(options) {
159
170
  throw new UpgradeError(result.error);
160
171
  if (result.npmInstall && !result.npmInstall.ok)
161
172
  throw new UpgradeError(`Installing the new packages failed: ${result.npmInstall.error ?? 'unknown error'}`);
162
- // package.json may already allow the latest version while an older
163
- // one stays installed (the lockfile keeps it); install it outright.
164
- const latest = await latestLoopengine(projectDir);
173
+ // package.json may already allow a newer version while an older one
174
+ // stays installed (the lockfile keeps it); install it outright. Only
175
+ // within package.json's range (the template's, after the step above):
176
+ // a loopengine newer than the template was made for may drop a name
177
+ // its adapters/http.ts imports, and the server wouldn't start.
178
+ const latest = await newestWithinRange('loopengine', projectDir);
165
179
  const current = loopengineVersion();
166
180
  if (latest && semver.valid(current) && semver.gt(latest, current) && !result.dependencies.some((d) => d.name === 'loopengine')) {
167
181
  try {
@@ -4,7 +4,8 @@ import { type PublicTrigger } from '../core/workflow-triggers.js';
4
4
  import { type GeneratedMcpAbility, type McpAbilityRequest } from '../core/mcp-ability-generator.js';
5
5
  import type { McpDirectoryServer } from '../core/mcp-directory.js';
6
6
  import { type AppToolInputs } from '../core/mcp-apps.js';
7
- import { type Workflow, type WorkflowModel } from '../core/workflows.js';
7
+ import { type Workflow, type WorkflowDelivery, type WorkflowFields, type WorkflowModel } from '../core/workflows.js';
8
+ import { type JsonSchema } from '../core/output-schema.js';
8
9
  import { type WorkflowEvals, type WorkflowScores } from './workflow-evidence.js';
9
10
  import { type WorkflowRun } from '../core/workflow-runs.js';
10
11
  import { type ScheduledTask } from '../core/scheduler.js';
@@ -318,12 +319,20 @@ export declare function prepareWorkflowRun(agentName: string, agentDir: string,
318
319
  export declare function contractFields(input: Record<string, unknown>): {
319
320
  model?: WorkflowModel | null;
320
321
  output?: string | null;
322
+ outputSchema?: JsonSchema | null;
321
323
  };
322
- /** The Messages tab's save: where every run's updates, approvals and
324
+ /** The Messaging tab's settings, checked, without saving them (for a
325
+ * draft): its delivery, or null for the messaging app's defaults. */
326
+ export declare function checkWorkflowMessages(input: Record<string, unknown>): WorkflowDelivery | null;
327
+ /** The Messaging tab's save: where every run's updates, approvals and
323
328
  * questions, start notice and result go. { callback_url, decisions,
324
329
  * chat_notice, result_to_chat }; empty for the messaging app's defaults. */
325
330
  export declare function updateWorkflowMessages(agentDir: string, id: string, input: Record<string, unknown>): Workflow;
326
331
  export declare function updateWorkflow(agentDir: string, id: string, input: Record<string, unknown>): Workflow;
332
+ /** An edit from the console's editor, checked: what saving it (or
333
+ * publishing it, as a draft) writes. Throws WorkflowError saying what's
334
+ * wrong. */
335
+ export declare function workflowEdit(agentDir: string, id: string, input: Record<string, unknown>): WorkflowFields;
327
336
  /** Removes a workflow: its skill stays, as a plain skill the agent can
328
337
  * still use in chat, and what started it goes: its schedules are
329
338
  * cancelled and its webhooks deleted (their URLs stop working). Returns
@@ -347,7 +356,7 @@ export declare function forgetAgent(agentName: string, agentDir: string): Promis
347
356
  export declare function agentDirIn(projectDir: string, name: string): string;
348
357
  /** Before 0.3.85 a workflow's schedule could post each run's result to
349
358
  * chat itself (its notify box); that's the workflow's own setting now (its
350
- * Messages tab, delivery.result_to_chat). Moves each live schedule's box
359
+ * Messaging tab, delivery.result_to_chat). Moves each live schedule's box
351
360
  * onto its workflow and clears it from the schedule, so one setting
352
361
  * decides. Returns the workflows turned on, as "agent/workflow". */
353
362
  export declare function moveScheduleResultsToWorkflows(agentDirOf: (agent: string) => string | undefined): Promise<string[]>;
@@ -17,6 +17,8 @@ import { checkRunDelivery, createTrigger, getTriggerStore, listTriggers, publicT
17
17
  import { mcpAbilityNames } from '../core/mcp-ability-generator.js';
18
18
  import { contextToolsFor } from '../core/mcp-apps.js';
19
19
  import { clearWorkflowFields, migrateWorkflowsFile, readWorkflow, readWorkflows, setWorkflowDelivery, setWorkflowFields, validateParams, workflowRunMessage } from '../core/workflows.js';
20
+ import { checkOutputSchema } from '../core/output-schema.js';
21
+ import { checkInputSpec } from '../core/input-schema.js';
20
22
  import { readEvals, setEvalCriteria, workflowScores } from './workflow-evidence.js';
21
23
  import { isUnderWay, listRuns } from '../core/workflow-runs.js';
22
24
  import { cancelScheduledTask, createScheduledTask, deleteScheduledTask, describeSchedule, getSchedulerStore, listScheduledTasks, pauseScheduledTask } from '../core/scheduler.js';
@@ -66,7 +68,7 @@ export async function workflowRequirements(plan, agent, appStatus) {
66
68
  if (need) {
67
69
  out.push(agent.messaging
68
70
  ? { kind: 'messaging', title: `Messaging (${agent.messaging})`, ready: true }
69
- : { kind: 'messaging', title: 'Messaging', ready: false, todo: `Set up ${agent.name}'s Messaging (Slack, email, Lark or a webhook), so ${need} when you're not in Chat`, href: tab('messaging') });
71
+ : { kind: 'messaging', title: 'Messaging Apps', ready: false, todo: `Set up ${agent.name}'s Messaging Apps (Slack, email, Lark or a webhook), so ${need} when you're not in Chat`, href: tab('messaging') });
70
72
  }
71
73
  return out;
72
74
  }
@@ -767,7 +769,8 @@ export async function listAgentWorkflows(agentName, agentDir) {
767
769
  return workflows.map((w) => {
768
770
  const schedules = workflowTasks(w.id, tasks).map(scheduleView);
769
771
  const recentRuns = runs.filter((r) => r.workflow_id === w.id).slice(0, RECENT_RUNS);
770
- const own = triggers.filter((t) => t.workflow_id === w.id);
772
+ // Its live webhooks: one made in a draft doesn't start runs yet.
773
+ const own = triggers.filter((t) => t.workflow_id === w.id && !t.draft);
771
774
  const webhooks = own.filter((t) => t.enabled).length;
772
775
  // Made by the planner, waiting for the sender's signing secret.
773
776
  const webhooksWaiting = own.filter((t) => !t.enabled && t.verify && !t.verify.secret).length;
@@ -833,6 +836,20 @@ export function contractFields(input) {
833
836
  throw new WorkflowError('The result format is too long: keep it under 2000 characters.');
834
837
  fields.output = typeof input.output === 'string' ? input.output : null;
835
838
  }
839
+ // A JSON Schema its result must match (core/output-schema.ts): an
840
+ // object, or its text; null or empty for none.
841
+ if (input.outputSchema !== undefined) {
842
+ if (input.outputSchema === null || (typeof input.outputSchema === 'string' && !input.outputSchema.trim()))
843
+ fields.outputSchema = null;
844
+ else {
845
+ try {
846
+ fields.outputSchema = checkOutputSchema(input.outputSchema);
847
+ }
848
+ catch (err) {
849
+ throw new WorkflowError(err instanceof Error ? err.message : String(err));
850
+ }
851
+ }
852
+ }
836
853
  // Where every run's updates and decisions go: { callback_url, decisions,
837
854
  // chat_notice }, or null for the messaging app only.
838
855
  if (input.delivery !== undefined) {
@@ -846,11 +863,16 @@ export function contractFields(input) {
846
863
  }
847
864
  return fields;
848
865
  }
866
+ /** The Messaging tab's settings, checked, without saving them (for a
867
+ * draft): its delivery, or null for the messaging app's defaults. */
868
+ export function checkWorkflowMessages(input) {
869
+ return deliveryOf(input);
870
+ }
849
871
  function deliveryOf(input) {
850
872
  const d = checkRunDelivery(input, (m) => new WorkflowError(m));
851
873
  return Object.keys(d).length ? d : null;
852
874
  }
853
- /** The Messages tab's save: where every run's updates, approvals and
875
+ /** The Messaging tab's save: where every run's updates, approvals and
854
876
  * questions, start notice and result go. { callback_url, decisions,
855
877
  * chat_notice, result_to_chat }; empty for the messaging app's defaults. */
856
878
  export function updateWorkflowMessages(agentDir, id, input) {
@@ -860,6 +882,13 @@ export function updateWorkflowMessages(agentDir, id, input) {
860
882
  return readWorkflow(agentDir, id);
861
883
  }
862
884
  export function updateWorkflow(agentDir, id, input) {
885
+ setWorkflowFields(agentDir, id, workflowEdit(agentDir, id, input));
886
+ return readWorkflow(agentDir, id);
887
+ }
888
+ /** An edit from the console's editor, checked: what saving it (or
889
+ * publishing it, as a draft) writes. Throws WorkflowError saying what's
890
+ * wrong. */
891
+ export function workflowEdit(agentDir, id, input) {
863
892
  if (!readWorkflow(agentDir, id))
864
893
  throw new WorkflowError(`No workflow ${id}.`);
865
894
  const text = (value, field, max) => {
@@ -889,11 +918,17 @@ export function updateWorkflow(agentDir, id, input) {
889
918
  if (!/^[a-z_][a-z0-9_]*$/.test(name))
890
919
  throw new WorkflowError(`Parameter "${name}": use lowercase letters, digits and _, starting with a letter, e.g. "order_number".`);
891
920
  const s = spec && typeof spec === 'object' ? spec : {};
892
- parameters[name] = { description: text(s.description, `The description of "${name}"`, 300), required: s.required === true };
921
+ let typed;
922
+ try {
923
+ typed = checkInputSpec(name, s);
924
+ }
925
+ catch (err) {
926
+ throw new WorkflowError(err instanceof Error ? err.message : String(err));
927
+ }
928
+ parameters[name] = { description: text(s.description, `The description of "${name}"`, 300), required: s.required === true, ...typed };
893
929
  }
894
930
  const named = { ...(title ? { title } : {}), ...(description ? { description: description.replace(/\s+/g, ' ') } : {}), ...contractFields(input) };
895
- setWorkflowFields(agentDir, id, instructions !== undefined ? { ...named, instructions, parameters } : { ...named, startMessage, ...(trigger ? { trigger } : {}), parameters });
896
- return readWorkflow(agentDir, id);
931
+ return instructions !== undefined ? { ...named, instructions, parameters } : { ...named, startMessage, ...(trigger ? { trigger } : {}), parameters };
897
932
  }
898
933
  /** Removes a workflow: its skill stays, as a plain skill the agent can
899
934
  * still use in chat, and what started it goes: its schedules are
@@ -941,7 +976,7 @@ export function agentDirIn(projectDir, name) {
941
976
  }
942
977
  /** Before 0.3.85 a workflow's schedule could post each run's result to
943
978
  * chat itself (its notify box); that's the workflow's own setting now (its
944
- * Messages tab, delivery.result_to_chat). Moves each live schedule's box
979
+ * Messaging tab, delivery.result_to_chat). Moves each live schedule's box
945
980
  * onto its workflow and clears it from the schedule, so one setting
946
981
  * decides. Returns the workflows turned on, as "agent/workflow". */
947
982
  export async function moveScheduleResultsToWorkflows(agentDirOf) {
@@ -1,7 +1,7 @@
1
1
  // A workflow's audit report (web/workflow-audit.ts) as a page to read,
2
2
  // print, or save as a PDF from the browser's print dialog: the summary,
3
3
  // the numbers, who decided what, every denial and change with its reason,
4
- // how the brief changed (line by line), other settings changed, every
4
+ // how the workflow changed (line by line), other settings changed, every
5
5
  // case, and whether the log checks out. Rendered here, with no script, so
6
6
  // the printed copy is exactly what's shown.
7
7
  import { devUiCss } from './dev-ui-styles.js';
@@ -30,7 +30,7 @@ export function workflowAuditReportHtml(audit, options) {
30
30
  <td>${d.reason ? `“${esc(d.reason)}”` : ''}${(d.changes ?? []).map((ch) => `<div><code>${esc(ch.field)}</code>: <del>${esc(ch.from)}</del> → <ins>${esc(ch.to)}</ins></div>`).join('')}</td>
31
31
  <td><a href="${esc(options.caseHref(d.runId))}">case</a></td></tr>`).join('');
32
32
  const people = audit.people.map((p) => `<tr><td>${esc(p.by)}</td><td>${p.approved}</td><td>${p.changed}</td><td>${p.denied}</td><td>${p.answered}</td></tr>`).join('');
33
- const cases = audit.cases.slice(0, 500).map((k) => `<tr><td>${esc(when(k.at))}</td><td>${STATUS[k.status] ?? esc(k.status)}</td><td>${esc(k.inputs)}</td><td>${k.briefVersion ? `v${k.briefVersion}` : ''}</td><td>${esc(k.decidedBy.join(', '))}</td><td class="ar-outcome">${esc(k.outcome)}</td><td><a href="${esc(options.caseHref(k.runId))}">open</a></td></tr>`).join('');
33
+ const cases = audit.cases.slice(0, 500).map((k) => `<tr><td>${esc(when(k.at))}</td><td>${STATUS[k.status] ?? esc(k.status)}</td><td>${esc(k.inputs)}</td><td>${k.workflowVersion ? `v${k.workflowVersion}` : ''}</td><td>${esc(k.decidedBy.join(', '))}</td><td class="ar-outcome">${esc(k.outcome)}</td><td><a href="${esc(options.caseHref(k.runId))}">open</a></td></tr>`).join('');
34
34
  const changes = audit.changes.map((ch) => `<li>${esc(when(ch.at))} · ${esc(ch.label)}${ch.by ? ` · ${esc(ch.by)}` : ''}${(ch.fields ?? []).map((f) => (f.added || f.removed
35
35
  ? `<div class="ar-diff"><div class="hint">${esc(f.field)}</div>${(f.removed ?? []).map((l) => `<div class="del">− ${esc(l)}</div>`).join('')}${(f.added ?? []).map((l) => `<div class="ins">+ ${esc(l)}</div>`).join('')}</div>`
36
36
  : `<div class="hint">${esc(f.field)}: <del>${esc(f.from)}</del> → <ins>${esc(f.to)}</ins></div>`)).join('')}</li>`).join('');
@@ -100,7 +100,7 @@ export function workflowAuditReportHtml(audit, options) {
100
100
  <section>
101
101
  <h2>Runs and decisions</h2>
102
102
  <table><thead><tr><th></th><th>Runs</th><th>Done</th><th>Failed</th><th>Decided</th><th>Approved as asked</th><th>Changed</th><th>Denied</th><th>Questions answered</th></tr></thead>
103
- <tbody>${countsRow('All', c)}${audit.versions.filter((ver) => ver.counts.runs).map((ver) => countsRow(`Brief v${ver.number}`, ver.counts)).join('')}</tbody></table>
103
+ <tbody>${countsRow('All', c)}${audit.versions.filter((ver) => ver.counts.runs).map((ver) => countsRow(`Version ${ver.number}`, ver.counts)).join('')}</tbody></table>
104
104
  ${audit.cost ? `<p class="hint">Model cost ${dollars(audit.cost.totalUsd)}, ${dollars(audit.cost.perRunUsd)} a run${audit.cost.pricedRuns < c.runs ? ` (${audit.cost.pricedRuns} of ${c.runs} runs priced)` : ''}.</p>` : ''}
105
105
  </section>
106
106
 
@@ -112,7 +112,7 @@ export function workflowAuditReportHtml(audit, options) {
112
112
  </section>
113
113
 
114
114
  <section>
115
- <h2>The brief</h2>
115
+ <h2>Workflow versions</h2>
116
116
  ${versions || '<p class="hint">No versions recorded.</p>'}
117
117
  </section>
118
118
 
@@ -123,7 +123,7 @@ export function workflowAuditReportHtml(audit, options) {
123
123
 
124
124
  <section>
125
125
  <h2>Cases (${audit.cases.length})</h2>
126
- ${cases ? `<table><thead><tr><th>Started</th><th>Outcome</th><th>Inputs</th><th>Brief</th><th>Decided by</th><th>Result</th><th></th></tr></thead><tbody>${cases}</tbody></table>${audit.cases.length > 500 ? '<p class="hint">The 500 most recent are listed; the JSON has them all.</p>' : ''}` : '<p class="hint">None.</p>'}
126
+ ${cases ? `<table><thead><tr><th>Started</th><th>Outcome</th><th>Inputs</th><th>Version</th><th>Decided by</th><th>Result</th><th></th></tr></thead><tbody>${cases}</tbody></table>${audit.cases.length > 500 ? '<p class="hint">The 500 most recent are listed; the JSON has them all.</p>' : ''}` : '<p class="hint">None.</p>'}
127
127
  </section>
128
128
  </div>
129
129
  </body>
@@ -1,5 +1,5 @@
1
1
  import type { AuditEvent, ChainCheck, Version } from '../core/audit-store.js';
2
- import type { WorkflowRun } from '../core/workflow-runs.js';
2
+ import { type WorkflowRun } from '../core/workflow-runs.js';
3
3
  export interface AuditCounts {
4
4
  runs: number;
5
5
  done: number;
@@ -58,7 +58,7 @@ export interface AuditCase {
58
58
  at: string;
59
59
  inputs: string;
60
60
  status: WorkflowRun['status'];
61
- briefVersion?: number;
61
+ workflowVersion?: number;
62
62
  decidedBy: string[];
63
63
  outcome: string;
64
64
  }
@@ -109,7 +109,7 @@ export interface WorkflowAuditInput {
109
109
  runs: WorkflowRun[];
110
110
  /** Each run's cost in US dollars, where known. */
111
111
  costs: Map<string, number>;
112
- /** Every brief version, any order. */
112
+ /** Every workflow version, any order. */
113
113
  versions: Version[];
114
114
  /** Its settings changes (events of kind "change") in the period. */
115
115
  changes: AuditEvent[];
@@ -1,3 +1,4 @@
1
+ import { workflowVersionOf } from '../core/workflow-runs.js';
1
2
  const short = (text, max) => {
2
3
  const flat = text.replace(/\s+/g, ' ').trim();
3
4
  return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
@@ -97,7 +98,7 @@ export function buildWorkflowAudit(input) {
97
98
  const changes = d.edited ? fieldChanges(d.before, d.after) : undefined;
98
99
  return { at: d.at, runId: r.run_id, tool: d.tool, ...(d.by ? { by: d.by } : {}), approved: d.approved, edited: Boolean(d.edited), ...(d.reason ? { reason: d.reason } : {}), ...(changes?.length ? { changes } : {}) };
99
100
  }));
100
- // The brief: the version in use when the period began, and each saved in it.
101
+ // The workflow: the version in use when the period began, and each saved in it.
101
102
  const all = [...input.versions].sort((a, b) => a.number - b.number);
102
103
  const atStart = all.filter((v) => v.at < input.since).at(-1);
103
104
  const shown = all.filter((v) => v === atStart || (v.at >= input.since && v.at <= input.until));
@@ -110,7 +111,7 @@ export function buildWorkflowAudit(input) {
110
111
  ...(v.by ? { by: v.by } : {}),
111
112
  ...(v.reason ? { reason: v.reason } : {}),
112
113
  changedInPeriod,
113
- counts: counts(runs.filter((r) => r.versions?.brief === v.number)),
114
+ counts: counts(runs.filter((r) => workflowVersionOf(r) === v.number)),
114
115
  ...(changedInPeriod && previous ? { diff: lineDiff(previous.content, v.content) } : {}),
115
116
  };
116
117
  });
@@ -122,14 +123,14 @@ export function buildWorkflowAudit(input) {
122
123
  at: r.started_at,
123
124
  inputs: short(Object.entries(r.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · '), 160),
124
125
  status: r.status,
125
- ...(r.versions?.brief ? { briefVersion: r.versions.brief } : {}),
126
+ ...(workflowVersionOf(r) ? { workflowVersion: workflowVersionOf(r) } : {}),
126
127
  decidedBy: [...new Set([...(r.decisions ?? []), ...(r.answers ?? [])].map((d) => d.by).filter((b) => Boolean(b)))],
127
128
  outcome: short(r.status === 'error' ? r.error ?? '' : r.result ?? '', 200),
128
129
  }));
129
130
  const changes = input.changes.map((e) => {
130
131
  const fields = Array.isArray(e.data.changes) ? e.data.changes : [];
131
- const brief = e.data.brief;
132
- const detail = [brief?.from && brief.to ? `brief v${brief.from} → v${brief.to}` : '', fields.map((f) => (f.added || f.removed ? `${f.field}: ${f.added?.length ?? 0} line${f.added?.length === 1 ? '' : 's'} added, ${f.removed?.length ?? 0} removed` : `${f.field}: ${f.from} → ${f.to}`)).join('; ')].filter(Boolean).join('; ');
132
+ const version = (e.data.version ?? e.data.brief);
133
+ const detail = [version?.from && version.to ? `workflow v${version.from} → v${version.to}` : '', fields.map((f) => (f.added || f.removed ? `${f.field}: ${f.added?.length ?? 0} line${f.added?.length === 1 ? '' : 's'} added, ${f.removed?.length ?? 0} removed` : `${f.field}: ${f.from} → ${f.to}`)).join('; ')].filter(Boolean).join('; ');
133
134
  return { at: e.at, ...(e.by ? { by: e.by } : {}), label: typeof e.data.label === 'string' ? e.data.label : 'Changed a setting', ...(detail ? { detail } : {}), ...(fields.length ? { fields } : {}) };
134
135
  });
135
136
  // ---- The summary, in sentences. ----
@@ -156,7 +157,7 @@ export function buildWorkflowAudit(input) {
156
157
  if (total.feedback)
157
158
  summary.push(`Feedback on ${plural(total.feedback, 'result')}: ${total.unedited} used unedited, ${total.bad} marked bad.`);
158
159
  }
159
- // The brief: each change in a sentence when there are one or two, else
160
+ // The workflow: each change in a sentence when there are one or two, else
160
161
  // one sentence for them all; and what changed in how people judged its
161
162
  // work, from the version before to the one after.
162
163
  const saved = versions.filter((x) => x.changedInPeriod);
@@ -177,8 +178,8 @@ export function buildWorkflowAudit(input) {
177
178
  const what = ver.diff ? ` (${plural(ver.diff.added.length, 'line')} added, ${ver.diff.removed.length} removed)` : '';
178
179
  const first = !previous && ver.number === 1;
179
180
  summary.push(first
180
- ? `The brief was first recorded, as version 1, on ${day(ver.at)}.`
181
- : `The brief changed to version ${ver.number} on ${day(ver.at)}${ver.by ? ` by ${ver.by}` : ''}${ver.reason ? `, ${quote(ver.reason, 60)}` : ''}${what}${effect(previous, ver)}.`);
181
+ ? `The workflow was first recorded, as version 1, on ${day(ver.at)}.`
182
+ : `The workflow changed to version ${ver.number} on ${day(ver.at)}${ver.by ? ` by ${ver.by}` : ''}${ver.reason ? `, ${quote(ver.reason, 60)}` : ''}${what}${effect(previous, ver)}.`);
182
183
  }
183
184
  }
184
185
  else if (saved.length > 2) {
@@ -188,11 +189,11 @@ export function buildWorkflowAudit(input) {
188
189
  const firstRan = versions.find(ran);
189
190
  const lastRan = [...versions].reverse().find(ran);
190
191
  const change = firstRan && lastRan && firstRan !== lastRan ? effect(firstRan, lastRan).replace(/^; /, ` From version ${firstRan.number} to ${lastRan.number}, `) : '';
191
- summary.push(`The brief changed ${saved.length} times${start ? `, from version ${start.number}` : ''} to version ${latest.number}, last on ${day(latest.at)}${people.length ? `, by ${people.join(', ')}` : ''}.${change ? `${change}.` : ''}`);
192
+ summary.push(`The workflow changed ${saved.length} times${start ? `, from version ${start.number}` : ''} to version ${latest.number}, last on ${day(latest.at)}${people.length ? `, by ${people.join(', ')}` : ''}.${change ? `${change}.` : ''}`);
192
193
  }
193
194
  else if (versions.length)
194
- summary.push(`The brief stayed at version ${versions[0].number} all period.`);
195
- const otherChanges = changes.filter((c) => !/^Edited the workflow$|^Restored brief version/.test(c.label));
195
+ summary.push(`The workflow stayed at version ${versions[0].number} all period.`);
196
+ const otherChanges = changes.filter((c) => !/^Edited the workflow$|^Published the workflow$|^Restored (brief|workflow) version/.test(c.label));
196
197
  if (otherChanges.length)
197
198
  summary.push(`${plural(otherChanges.length, 'other setting change')}: ${[...new Set(otherChanges.map((c) => c.label.toLowerCase()))].slice(0, 4).join(', ')}.`);
198
199
  if (cost)
@@ -0,0 +1,75 @@
1
+ import { type FieldChange } from './change-log.js';
2
+ import type { Workflow, WorkflowDelivery, WorkflowFields } from '../core/workflows.js';
3
+ /** A schedule added in the draft, created when it's published. */
4
+ export interface DraftSchedule {
5
+ /** "d-…", to refer to it before it exists. */
6
+ id: string;
7
+ task_name?: string;
8
+ /** As given ({ every, at } or { run_at }), checked when added. */
9
+ schedule: Record<string, unknown>;
10
+ params?: Record<string, string>;
11
+ notify?: boolean;
12
+ }
13
+ export interface WorkflowDraft {
14
+ /** The editor's edit, checked (web/workflow-admin.ts's workflowEdit),
15
+ * less the name and description, which are saved straight away. */
16
+ fields?: WorkflowFields;
17
+ /** The success criteria, all of them, checked. */
18
+ criteria?: {
19
+ id?: string;
20
+ text: string;
21
+ kind: string;
22
+ value?: string;
23
+ }[];
24
+ /** Where messages go: its delivery, or null for the messaging app's
25
+ * defaults. */
26
+ messages?: {
27
+ delivery: WorkflowDelivery | null;
28
+ };
29
+ schedules?: {
30
+ add: DraftSchedule[];
31
+ remove: string[];
32
+ };
33
+ /** Webhooks made in the draft (not live yet), changes to live ones (each
34
+ * one's checked settings), and live ones to delete. */
35
+ webhooks?: {
36
+ added: string[];
37
+ update: Record<string, Record<string, unknown>>;
38
+ remove: string[];
39
+ };
40
+ savedAt: string;
41
+ savedBy?: string;
42
+ /** The published version it was started from. */
43
+ basedOn?: number;
44
+ }
45
+ export declare function readDraft(projectDir: string, agent: string, workflowId: string): WorkflowDraft | undefined;
46
+ /** A draft with nothing in it. */
47
+ export declare function isEmptyDraft(d: WorkflowDraft): boolean;
48
+ /** Changes the draft (making one when there's none), saving who changed
49
+ * it and when; an empty draft is removed. `basedOn` stays the version the
50
+ * draft began from. */
51
+ export declare function changeDraft(projectDir: string, agent: string, workflowId: string, about: {
52
+ by?: string;
53
+ basedOn?: number;
54
+ }, change: (d: WorkflowDraft) => WorkflowDraft): WorkflowDraft | undefined;
55
+ /** Saves a whole draft (tests, and replacing one outright). */
56
+ export declare function saveDraft(projectDir: string, agent: string, workflowId: string, draft: WorkflowDraft): WorkflowDraft | undefined;
57
+ export declare function discardDraft(projectDir: string, agent: string, workflowId: string): void;
58
+ /** The workflow as the draft's editor fields would make it. */
59
+ export declare function withDraft(workflow: Workflow, fields: WorkflowFields | undefined): Workflow;
60
+ /** Where messages go, in words, for comparing. */
61
+ export declare function messagesText(d: WorkflowDelivery | null | undefined): string;
62
+ /** Everything a draft can change, as fields to compare. */
63
+ export interface DraftState {
64
+ workflow: Workflow;
65
+ criteria: {
66
+ text: string;
67
+ kind: string;
68
+ value?: string;
69
+ }[];
70
+ delivery: WorkflowDelivery | null | undefined;
71
+ /** Each schedule and webhook that starts it, in a line. */
72
+ triggers: string[];
73
+ }
74
+ /** What publishing changes: the published state against the drafted. */
75
+ export declare function draftChanges(published: DraftState, drafted: DraftState): FieldChange[];