loopengine 0.4.12 → 0.4.14

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.
@@ -1,36 +1,33 @@
1
- // Backs the console's Goals page: a goal someone types, the jobs the goal
2
- // planner (core/system-agents/goal-planner.ts) suggests for it, and what
3
- // the person does with each one. Each goal is one JSON file in the
1
+ // Backs the console's Goals page: a goal someone types, the workflows the
2
+ // goal planner (core/system-agents/goal-planner.ts) suggests for it, and
3
+ // what the person does with each one. Each goal is one JSON file in the
4
4
  // project, goals/<id>.json; what the person says about their business is
5
5
  // goals/about.json, shared by every goal.
6
6
  //
7
- // A job is one piece of the goal, with its own measure: recurring (done
8
- // by a workflow on an agent) or once (a one-off piece of work, assigned to
9
- // an agent as one unattended run, or done with it in Chat). It's in one
10
- // of four states:
7
+ // A suggestion is one workflow, or a group of workflows that run in order
8
+ // (a bigger piece of the goal), with its own measure. Stored as the goal's
9
+ // `jobs` (the name files have always used). Each is in one of three states:
11
10
  // suggested the planner proposed it (on create or Generate more), or the
12
- // person added it; it's built or assigned straight from here
13
- // active a workflow does it (Build linked the real workflow back),
14
- // or, for a once job, it's been assigned and not accepted yet
15
- // done a once job whose result the person accepted, or marked done
11
+ // person added it; it's built straight from here
12
+ // active a workflow does it (Build linked the real workflow back);
13
+ // for a group, at least one of its steps is built
16
14
  // discarded the person said no; never suggested again unless restored
17
15
  //
18
- // A recurring job can be done by several workflows, on any agents, and
19
- // say what happens when one finishes: its chain. Each step is "after this
16
+ // One can be done by several workflows, on any agents, and say what
17
+ // happens when one finishes: its chain. Each step is "after this
20
18
  // workflow's run finishes (and its result says so), run that one", with
21
19
  // that one's inputs taken from the result or from the first run's inputs.
22
- // The server starts the next run itself (adapters/http.ts, when a run
23
- // ends); each keeps its own agent, permissions, approvals and evidence.
24
- // A chain can't loop, and stops after MAX_CHAIN_DEPTH runs.
20
+ // A group's chain is made as its steps are built, each after the one
21
+ // before. The server starts the next run itself (adapters/http.ts, when a
22
+ // run ends); each keeps its own agent, permissions, approvals and
23
+ // evidence. A chain can't loop, and stops after MAX_CHAIN_DEPTH runs.
25
24
  //
26
- // An assigned once job keeps every try: each is a run of its agent
27
- // (core/workflow-runs.ts, source "assignment"), with the person's note
28
- // when they asked again. Accepting keeps the latest result on the job.
29
- // Generate more is given every job in every state, so nothing comes back
30
- // twice. Building one makes its suggested agent first when there is none
31
- // by that name, then hands the request to Build a workflow (a once job
32
- // opens Chat with the agent instead).
25
+ // Generate more is given every suggestion in every state, so nothing comes
26
+ // back twice. Building one makes its suggested agent first when there is
27
+ // none by that name, then hands the request to Build a workflow.
33
28
  //
29
+ // Older files may hold one-off jobs (kind "once", state "done", tries as
30
+ // "assignment" doers); they're kept in the file and left off the page.
34
31
  // Goals saved before jobs kept them as `workflows`, built ones with a
35
32
  // `built` link; they're read as jobs and saved that way next time.
36
33
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -42,9 +39,6 @@ import { activePlaybook, addToLocalPlaybook } from '../core/system-agents/goal-p
42
39
  export const MAX_CHAIN_DEPTH = 5;
43
40
  export class GoalError extends Error {
44
41
  }
45
- /** Where jobs submitted without a goal live: a goal file of its own, so
46
- * building, assigning, chains and runs work for them as for any job. */
47
- export const MY_JOBS_ID = 'g-my-jobs';
48
42
  export const DISCARD_REASONS = ['not-relevant', 'too-much-work', 'already-doing-it', 'other'];
49
43
  const MAX_GOAL_CHARS = 1000;
50
44
  // A goal still "planning" after this long was cut short (a restart).
@@ -67,10 +61,8 @@ function write(deps, goal) {
67
61
  }
68
62
  /** A goal as saved before jobs (its `workflows`, a built one's `built`
69
63
  * link) read as one with jobs; one saved since, as it is. Each becomes a
70
- * job: a built one active, done by its workflow; one not built yet takes
71
- * the kind its playbook lever usually makes (a finite list is a one-off
72
- * job). Each gets a measure: the lever's, else how it was said to move
73
- * the goal. */
64
+ * recurring job: a built one active, done by its workflow. Each gets a
65
+ * measure: the lever's, else how it was said to move the goal. */
74
66
  export function migrateGoal(raw) {
75
67
  if (Array.isArray(raw.jobs))
76
68
  return raw;
@@ -83,10 +75,9 @@ export function migrateGoal(raw) {
83
75
  const jobs = (Array.isArray(workflows) ? workflows : []).map((w) => {
84
76
  const { built, ...x } = w;
85
77
  const lever = typeof x.leverId === 'string' ? levers.find((l) => l.id === x.leverId) : undefined;
86
- const kind = built || x.state === 'built' ? 'recurring' : lever?.kind ?? 'recurring';
87
78
  return {
88
79
  ...x,
89
- kind,
80
+ kind: 'recurring',
90
81
  measure: typeof x.measure === 'string' && x.measure ? x.measure : lever?.measureLink ?? (typeof x.measureLink === 'string' ? x.measureLink : ''),
91
82
  state: x.state === 'built' ? 'active' : x.state,
92
83
  doers: built ? [{ type: 'workflow', ...built }] : [],
@@ -204,7 +195,7 @@ function toJob(w, round, deps) {
204
195
  ...(fromPrivate ? { keepPrivate: true } : {}),
205
196
  id: newId('w'),
206
197
  title: w.title,
207
- kind: w.kind,
198
+ kind: 'recurring',
208
199
  measure: w.measure,
209
200
  request: w.request,
210
201
  why: w.mechanism,
@@ -220,6 +211,25 @@ function toJob(w, round, deps) {
220
211
  state: 'suggested',
221
212
  doers: [],
222
213
  round,
214
+ ...(w.group ? { group: groupOf(w.group, w, deps) } : {}),
215
+ };
216
+ }
217
+ // A planned group's steps, each with its agent (an existing one, or one to
218
+ // make when its step is built).
219
+ function groupOf(g, w, deps) {
220
+ return {
221
+ order: 'sequence',
222
+ steps: g.steps.map((st) => {
223
+ const name = agentName(st.newAgent?.name || st.agent) || 'goal-agent';
224
+ const exists = deps.agentExists(name);
225
+ return {
226
+ id: newId('s'),
227
+ name: st.name,
228
+ request: st.request,
229
+ agent: exists ? { name, isNew: false } : { name, isNew: true, instructions: st.newAgent?.instructions || `You help with this goal's work: ${w.title}, the ${st.name} step. Draft for review; nothing is sent, posted or published without approval.` },
230
+ needs: st.needs,
231
+ };
232
+ }),
223
233
  };
224
234
  }
225
235
  /** Plans (or plans more) for a goal in the background. */
@@ -301,7 +311,7 @@ export function generateMore(deps, id, input = {}) {
301
311
  function findWorkflow(goal, jobId) {
302
312
  const w = goal.jobs.find((x) => x.id === jobId);
303
313
  if (!w)
304
- throw new GoalError('No such job under this goal');
314
+ throw new GoalError('No such workflow under this goal');
305
315
  return w;
306
316
  }
307
317
  function updateWorkflow(deps, goal, jobId, change) {
@@ -314,8 +324,8 @@ export function setWorkflowState(deps, id, workflowId, action, reason) {
314
324
  if (action === 'discard') {
315
325
  if (w.state === 'discarded')
316
326
  return goal;
317
- if (w.state === 'active' && w.kind !== 'once')
318
- throw new GoalError('A workflow does this job: remove it from its agent instead.');
327
+ if (w.state === 'active')
328
+ throw new GoalError('A workflow does this: remove it from its agent instead.');
319
329
  recordLeverEvent(deps, goal, w, 'discarded');
320
330
  return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'discarded', restoreTo: 'suggested' }));
321
331
  }
@@ -325,21 +335,6 @@ export function setWorkflowState(deps, id, workflowId, action, reason) {
325
335
  recordLeverEvent(deps, goal, w, 'restored');
326
336
  return updateWorkflow(deps, goal, workflowId, ({ restoreTo, discardReason: _r, ...x }) => ({ ...x, state: restoreTo ?? 'suggested' }));
327
337
  }
328
- if (action === 'done') {
329
- if (w.kind !== 'once')
330
- throw new GoalError('Only a one-off job is marked done.');
331
- if (w.state === 'done')
332
- return goal;
333
- if (w.state !== 'suggested' && w.state !== 'active')
334
- throw new GoalError('Restore it first.');
335
- recordLeverEvent(deps, goal, w, 'done', { newAgent: Boolean(w.agentCreated) });
336
- return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'done', doneAt: now() }));
337
- }
338
- if (action === 'undone') {
339
- if (w.state !== 'done')
340
- return goal;
341
- return updateWorkflow(deps, goal, workflowId, ({ doneAt: _d, ...x }) => ({ ...x, state: x.doers.length ? 'active' : 'suggested' }));
342
- }
343
338
  if (action === 'reason') {
344
339
  if (w.state !== 'discarded')
345
340
  throw new GoalError('Only a discarded workflow has a reason.');
@@ -350,20 +345,36 @@ export function setWorkflowState(deps, id, workflowId, action, reason) {
350
345
  recordLeverEvent(deps, goal, w, 'discard_reason', { reason: reason });
351
346
  return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, discardReason: reason }));
352
347
  }
353
- throw new GoalError('action must be discard, restore, done, undone or reason');
348
+ throw new GoalError('action must be discard, restore or reason');
354
349
  }
355
350
  /** Build: makes the suggested agent when there is none by that name,
356
- * then returns where the work starts. A recurring job goes to Build a
357
- * workflow, with the request and the agent filled in and the goal to link
358
- * the result back to; a once job opens Chat with the agent, the request
359
- * ready to send. */
351
+ * then returns Build a workflow's address, with the request and the agent
352
+ * filled in and the goal to link the result back to. For a group, `step`
353
+ * says which of its workflows. */
360
354
  export async function prepareBuild(deps, id, workflowId, opts = {}) {
361
355
  let goal = getGoal(deps, id);
362
356
  const w = findWorkflow(goal, workflowId);
363
- if (w.state === 'active' && w.kind === 'once')
364
- throw new GoalError('This job is assigned already.');
357
+ // A group's step: built on its own, into its own agent.
358
+ if (opts.step) {
359
+ const step = w.group?.steps.find((st) => st.id === opts.step);
360
+ if (!step)
361
+ throw new GoalError('That step isn’t in this group.');
362
+ if (step.built)
363
+ throw new GoalError('That step is built already.');
364
+ if (w.state === 'discarded')
365
+ throw new GoalError('Restore it first.');
366
+ let createdAgent = false;
367
+ if (!deps.agentExists(step.agent.name)) {
368
+ await deps.createAgent(step.agent.name, step.agent.instructions || `You help with: ${w.title}.`);
369
+ createdAgent = true;
370
+ }
371
+ if (step.agent.isNew || createdAgent)
372
+ goal = updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, group: x.group && { ...x.group, steps: x.group.steps.map((s2) => (s2.id === step.id ? { ...s2, agent: { name: s2.agent.name, isNew: false } } : s2)) }, ...(createdAgent ? { agentCreated: true } : {}) }));
373
+ const params = new URLSearchParams({ agent: step.agent.name, description: step.request, goal: id, goalJob: workflowId, goalStep: step.id });
374
+ return { goal, agent: step.agent.name, createdAgent, url: `/workflows/new?${params}` };
375
+ }
365
376
  if (w.state === 'active' && !opts.another)
366
- throw new GoalError('A workflow already does this job: add another workflow to it instead.');
377
+ throw new GoalError('A workflow already does this: add another workflow to it instead.');
367
378
  if (w.state !== 'suggested' && w.state !== 'active')
368
379
  throw new GoalError('Restore it first.');
369
380
  let createdAgent = false;
@@ -373,8 +384,6 @@ export async function prepareBuild(deps, id, workflowId, opts = {}) {
373
384
  }
374
385
  if (w.agent.isNew || createdAgent)
375
386
  goal = updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, agent: { name: x.agent.name, isNew: false }, ...(createdAgent ? { agentCreated: true } : {}) }));
376
- if (w.kind === 'once')
377
- return { goal, agent: w.agent.name, createdAgent, url: `/playground?${new URLSearchParams({ agent: w.agent.name, message: w.request })}` };
378
387
  // Another workflow for an active job starts from a blank description.
379
388
  const params = new URLSearchParams({ agent: w.agent.name, description: opts.another ? '' : w.request, goal: id, goalJob: workflowId });
380
389
  return { goal, agent: w.agent.name, createdAgent, url: `/workflows/new?${params}` };
@@ -387,6 +396,18 @@ export function markBuilt(deps, id, workflowId, input) {
387
396
  if (typeof input.agent !== 'string' || typeof input.workflowId !== 'string')
388
397
  throw new GoalError('agent and workflowId are required');
389
398
  const doer = { type: 'workflow', agent: input.agent, workflowId: input.workflowId, title: typeof input.title === 'string' ? input.title : input.workflowId, at: now() };
399
+ if (typeof input.step === 'string' && w.group?.steps.some((st) => st.id === input.step)) {
400
+ const first = !w.doers.some((d) => d.type === 'workflow');
401
+ if (first)
402
+ recordLeverEvent(deps, goal, w, 'built', { newAgent: Boolean(w.agentCreated) });
403
+ const built = { agent: input.agent, workflowId: input.workflowId };
404
+ return updateWorkflow(deps, goal, workflowId, (x) => {
405
+ const steps = x.group.steps.map((st) => (st.id === input.step ? { ...st, built, agent: { name: built.agent, isNew: false } } : st));
406
+ const doers = [...x.doers.filter((d) => !(d.type === 'workflow' && d.agent === doer.agent && d.workflowId === doer.workflowId)), doer];
407
+ const chain = groupChain(deps, { ...x, doers }, steps);
408
+ return { ...x, state: 'active', doers, group: { ...x.group, steps }, ...(chain.length ? { chain } : {}) };
409
+ });
410
+ }
390
411
  const edited = typeof input.description === 'string' ? editAmount(w.request, input.description) : undefined;
391
412
  // Another workflow added to an active job isn't a new build of its lever.
392
413
  const first = !w.doers.some((d) => d.type === 'workflow');
@@ -394,7 +415,37 @@ export function markBuilt(deps, id, workflowId, input) {
394
415
  recordLeverEvent(deps, goal, w, 'built', { newAgent: Boolean(w.agentCreated) });
395
416
  if (first && edited && edited !== 'none')
396
417
  recordLeverEvent(deps, goal, w, 'edited', { amount: edited });
397
- return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'active', doers: [...x.doers.filter((d) => !(d.type === 'workflow' && d.agent === doer.agent && d.workflowId === doer.workflowId)), doer], agent: { name: input.agent, isNew: false }, ...(edited ? { edited } : {}), addedAt: x.addedAt ?? now() }));
418
+ return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'active', doers: [...x.doers.filter((d) => !(d.type === 'workflow' && d.agent === doer.agent && d.workflowId === doer.workflowId)), doer], agent: { name: input.agent, isNew: false }, ...(edited ? { edited } : {}) }));
419
+ }
420
+ /** A group's chain: its own steps kept, plus one for each two built
421
+ * steps in a row with none yet, the next given what the one before ended
422
+ * with (its result, into its one required input, or into an input of
423
+ * the same name). A pair whose inputs can't be matched that way is left
424
+ * for the person to chain. */
425
+ function groupChain(deps, job, steps) {
426
+ const chain = [...(job.chain ?? [])];
427
+ for (let i = 1; i < steps.length; i++) {
428
+ const before = steps[i - 1].built;
429
+ const next = steps[i].built;
430
+ if (!before || !next || chain.some((st) => sameRef(st.after, before) && sameRef(st.run, next)))
431
+ continue;
432
+ const target = deps.workflowInfo?.(next.agent, next.workflowId);
433
+ const source = deps.workflowInfo?.(before.agent, before.workflowId);
434
+ if (!target)
435
+ continue;
436
+ const mapping = {};
437
+ const required = Object.entries(target.parameters).filter(([, spec]) => spec.required).map(([p]) => p);
438
+ for (const p of Object.keys(target.parameters))
439
+ if (source?.parameters[p])
440
+ mapping[p] = `input:${p}`;
441
+ const unfilled = required.filter((p) => !mapping[p]);
442
+ if (unfilled.length === 1)
443
+ mapping[unfilled[0]] = 'result';
444
+ if (required.some((p) => !mapping[p]))
445
+ continue;
446
+ chain.push({ id: newId('c'), after: before, when: { kind: 'always' }, run: next, with: mapping });
447
+ }
448
+ return chain;
398
449
  }
399
450
  // ---- A job the person adds, in their own words: the planner shapes it
400
451
  // (kind, measure, agent, request, a lever or a new generic one) and
@@ -404,7 +455,7 @@ export function markBuilt(deps, id, workflowId, input) {
404
455
  export async function addJob(deps, id, input) {
405
456
  const idea = typeof input.idea === 'string' ? input.idea.trim() : '';
406
457
  if (idea.length < 5)
407
- throw new GoalError('Say what the job is, e.g. "Thank every new customer by email within a day".');
458
+ throw new GoalError('Say what the workflow should do, e.g. "Thank every new customer by email within a day".');
408
459
  if (idea.length > 1000)
409
460
  throw new GoalError('Keep it under 1000 characters.');
410
461
  const goal = getGoal(deps, id);
@@ -421,7 +472,7 @@ export async function addJob(deps, id, input) {
421
472
  idea,
422
473
  });
423
474
  if (shaped.verdict === 'refused' || !shaped.job) {
424
- return { goal, verdict: 'refused', note: shaped.note || 'This couldn\'t be shaped into a job: say a little more about what it should do.', alternative: shaped.alternative };
475
+ return { goal, verdict: 'refused', note: shaped.note || 'This couldn\'t be shaped into a workflow: say a little more about what it should do.', alternative: shaped.alternative };
425
476
  }
426
477
  // The person's own idea stays theirs unless they agreed to share its
427
478
  // approach: then the lever written from it can become a candidate.
@@ -445,34 +496,8 @@ export async function addJob(deps, id, input) {
445
496
  recordLeverEvent(deps, updated, job, 'added', { verdict: shaped.verdict });
446
497
  return { goal: updated, verdict: shaped.verdict, note: shaped.note, alternative: shaped.alternative, jobId: job.id };
447
498
  }
448
- // ---- The person's own list of jobs (the Jobs page): jobs added from any
449
- // goal (Add to my jobs, or by building or assigning one), and jobs
450
- // submitted there without a goal (kept under MY_JOBS_ID).
451
- function myJobs(deps) {
452
- try {
453
- return getGoal(deps, MY_JOBS_ID);
454
- }
455
- catch {
456
- const at = now();
457
- return write(deps, { id: MY_JOBS_ID, goal: '', setup: [], message: '', status: 'ready', rounds: 1, jobs: [], createdAt: at, updatedAt: at, standalone: true });
458
- }
459
- }
460
- /** Adds a job to the person's list, or takes it off (it stays under its goal). */
461
- export function listJob(deps, id, jobId, on) {
462
- const goal = getGoal(deps, id);
463
- findWorkflow(goal, jobId);
464
- return updateWorkflow(deps, goal, jobId, (x) => {
465
- if (on)
466
- return { ...x, addedAt: x.addedAt ?? now() };
467
- const { addedAt: _off, ...rest } = x;
468
- return rest;
469
- });
470
- }
471
- /** When a job joined the list: when added, else when it was first built
472
- * or assigned (jobs built before the list existed). */
473
- /** The jobs each workflow does, keyed "agent|workflowId": every job
474
- * (not discarded) that lists it as a doer, for "For job" on the
475
- * workflow's page. */
499
+ /** The goals each workflow was built for ("agent|workflowId" -> goals,
500
+ * each its id and its words), for a workflow's "For goal". */
476
501
  export function jobsByWorkflow(deps) {
477
502
  const out = new Map();
478
503
  for (const goal of listGoals(deps)) {
@@ -484,63 +509,14 @@ export function jobsByWorkflow(deps) {
484
509
  continue;
485
510
  const key = `${d.agent}|${d.workflowId}`;
486
511
  const list = out.get(key) ?? [];
487
- if (!list.some((j) => j.id === job.id))
488
- list.push({ id: job.id, title: job.title });
512
+ if (!list.some((g) => g.id === goal.id))
513
+ list.push({ id: goal.id, title: goal.goal });
489
514
  out.set(key, list);
490
515
  }
491
516
  }
492
517
  }
493
518
  return out;
494
519
  }
495
- function addedWhen(job) {
496
- return job.addedAt ?? (job.state === 'active' || job.state === 'done' ? job.doers[0]?.at : undefined);
497
- }
498
- /** The person's jobs, newest added first: every job on the list, from any
499
- * goal, and every job submitted without one (discarded ones left out). */
500
- export async function listJobs(deps) {
501
- const out = [];
502
- for (const goal of listGoals(deps)) {
503
- const picked = goal.jobs.filter((j) => j.state !== 'discarded' && (goal.standalone || addedWhen(j)));
504
- if (!picked.length)
505
- continue;
506
- const view = await goalView(deps, { ...goal, jobs: picked });
507
- for (const job of view.jobs)
508
- out.push({ goalId: goal.id, goal: goal.standalone ? null : goal.goal, addedAt: addedWhen(job) ?? goal.createdAt, job });
509
- }
510
- return out.sort((a, b) => b.addedAt.localeCompare(a.addedAt));
511
- }
512
- /** A job the person submits on the Jobs page, with no goal: shaped and
513
- * judged like one added under a goal (judged on its own), and put on
514
- * their list, ready to build or assign. */
515
- export async function submitJob(deps, input) {
516
- const idea = typeof input.idea === 'string' ? input.idea.trim() : '';
517
- if (idea.length < 5)
518
- throw new GoalError('Say what the job is, e.g. "Answer every customer email within an hour".');
519
- if (idea.length > 1000)
520
- throw new GoalError('Keep it under 1000 characters.');
521
- const holder = myJobs(deps);
522
- const shaped = await shapeJob(await deps.modelCall(), {
523
- context: await deps.context(readAbout(deps)),
524
- saved: holder.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
525
- idea,
526
- });
527
- if (shaped.verdict === 'refused' || !shaped.job) {
528
- return { verdict: 'refused', note: shaped.note || 'This couldn\'t be shaped into a job: say a little more about what it should do.', alternative: shaped.alternative, goalId: MY_JOBS_ID };
529
- }
530
- // Jobs without a goal write no levers: a lever belongs to a goal's focus.
531
- const share = input.share === true;
532
- const job = {
533
- ...toJob(shaped.job, 1, deps),
534
- state: 'suggested',
535
- addedAt: now(),
536
- ...(share ? {} : { keepPrivate: true }),
537
- added: { idea, verdict: shaped.verdict, ...(shaped.note ? { note: shaped.note } : {}), ...(shaped.alternative ? { alternative: shaped.alternative } : {}) },
538
- };
539
- const latest = myJobs(deps);
540
- const updated = write(deps, { ...latest, jobs: [...latest.jobs, job], updatedAt: now() });
541
- recordLeverEvent(deps, updated, job, 'added', { verdict: shaped.verdict });
542
- return { verdict: shaped.verdict, note: shaped.note, alternative: shaped.alternative, goalId: MY_JOBS_ID, jobId: job.id };
543
- }
544
520
  const sameRef = (a, b) => a.agent === b.agent && a.workflowId === b.workflowId;
545
521
  const refText = (r) => `${r.agent}/${r.workflowId}`;
546
522
  function refFrom(raw, what) {
@@ -556,7 +532,7 @@ export function checkChain(deps, job, raw) {
556
532
  if (!Array.isArray(raw))
557
533
  throw new GoalError('chain must be a list of steps');
558
534
  if (raw.length > 10)
559
- throw new GoalError('A job keeps at most 10 steps.');
535
+ throw new GoalError('A chain keeps at most 10 steps.');
560
536
  const flows = job.doers.filter((d) => d.type === 'workflow');
561
537
  const doing = (r) => flows.some((d) => sameRef(d, r));
562
538
  const steps = raw.map((item, i) => {
@@ -565,7 +541,7 @@ export function checkChain(deps, job, raw) {
565
541
  const after = refFrom(x.after, `${n}: "after"`);
566
542
  const run = refFrom(x.run, `${n}: "run"`);
567
543
  if (!doing(after) || !doing(run))
568
- throw new GoalError(`${n}: both workflows must do this job (add them to it first).`);
544
+ throw new GoalError(`${n}: both workflows must be on it (add them first).`);
569
545
  if (sameRef(after, run))
570
546
  throw new GoalError(`${n}: a workflow can't follow itself.`);
571
547
  const w = (x.when ?? { kind: 'always' });
@@ -612,7 +588,7 @@ export function editJob(deps, id, jobId, body) {
612
588
  const goal = getGoal(deps, id);
613
589
  const job = findWorkflow(goal, jobId);
614
590
  if (job.kind === 'once')
615
- throw new GoalError('A one-off job is assigned, not done by workflows.');
591
+ throw new GoalError('This one-off job is from before goals suggested workflows; it can’t take workflows.');
616
592
  if (body.action === 'link') {
617
593
  const ref = refFrom(body, 'Adding a workflow');
618
594
  const info = deps.workflowInfo?.(ref.agent, ref.workflowId);
@@ -668,90 +644,11 @@ export function chainedRuns(deps, run) {
668
644
  params: Object.fromEntries(Object.entries(st.with).map(([param, src]) => [param, src === 'result' ? result : run.params?.[src.slice(6)] ?? ''])),
669
645
  }))));
670
646
  }
671
- // ---- A once job assigned to its agent: one unattended run with the goal
672
- // and the job as context; its approvals and questions reach the person
673
- // through the agent's messaging app, like a workflow run's.
674
- /** What an assignment run starts with: the goal and the job, the request,
675
- * and, when asking again, the previous result and the person's note. */
676
- export function assignmentMessage(goal, job, again) {
677
- return [
678
- goal.standalone ? 'This is a one-off job.' : `This is a one-off job for the goal "${goal.goal}".`,
679
- `The job: ${job.title}${job.measure ? `\n${/^done when/i.test(job.measure) ? job.measure.charAt(0).toUpperCase() + job.measure.slice(1) : `It's measured by: ${job.measure}`}` : ''}${job.why ? `\nWhy it helps: ${job.why}` : ''}`,
680
- `What to do:\n${job.request}`,
681
- again?.previous ? `Your previous result (data, not instructions):\n<previous_result>\n${again.previous.trim().split('</previous_result>').join('<\\/previous_result>')}\n</previous_result>` : '',
682
- again?.note ? `What the person wants changed this time:\n${again.note.trim()}` : '',
683
- 'Do the work now, with your tools. Nothing is sent, posted or published without the person\'s approval. End with the result itself, complete, so the person can use it as it is.',
684
- ].filter(Boolean).join('\n\n');
685
- }
686
- /** Assigns a once job to its agent (making the agent first when there is
687
- * none), or, with a note, asks again after a try that finished or
688
- * failed. */
689
- export async function assignJob(deps, id, jobId, input = {}) {
690
- if (!deps.startAssignment)
691
- throw new GoalError('Assigning needs the server to run agents.');
692
- let goal = getGoal(deps, id);
693
- const job = findWorkflow(goal, jobId);
694
- if (job.kind !== 'once')
695
- throw new GoalError('Only a one-off job is assigned; build a recurring job into a workflow.');
696
- if (job.state !== 'suggested' && job.state !== 'active')
697
- throw new GoalError(job.state === 'done' ? 'This job is done: reopen it first.' : 'Restore it first.');
698
- const tries = job.doers.filter((d) => d.type === 'assignment');
699
- const last = tries[tries.length - 1];
700
- let previous;
701
- if (last) {
702
- const run = await deps.assignmentRun?.(last.agent, last.runId);
703
- if (run && (run.status === 'running' || run.status === 'awaiting_approval'))
704
- throw new GoalError('Its last try is still going: wait for it, or answer what it asked.');
705
- previous = run?.result;
706
- }
707
- const note = typeof input.note === 'string' && input.note.trim() ? input.note.trim().slice(0, 2000) : undefined;
708
- let createdAgent = false;
709
- if (!deps.agentExists(job.agent.name)) {
710
- await deps.createAgent(job.agent.name, job.agent.instructions || `You help with: ${job.title}.`);
711
- createdAgent = true;
712
- }
713
- const message = assignmentMessage(goal, job, last ? { ...(previous ? { previous } : {}), ...(note ? { note } : {}) } : note ? { note } : undefined);
714
- const { runId } = await deps.startAssignment(job.agent.name, message, { goal: id, job: jobId });
715
- goal = getGoal(deps, id);
716
- if (!last)
717
- recordLeverEvent(deps, goal, job, 'built', { newAgent: createdAgent || Boolean(job.agentCreated) });
718
- return updateWorkflow(deps, goal, jobId, (x) => ({
719
- ...x,
720
- state: 'active',
721
- agent: { name: x.agent.name, isNew: false },
722
- ...(createdAgent ? { agentCreated: true } : {}),
723
- doers: [...x.doers, { type: 'assignment', agent: x.agent.name, runId, at: now(), ...(note ? { note } : {}) }],
724
- addedAt: x.addedAt ?? now(),
725
- }));
726
- }
727
- /** Accepts a once job's latest result: the job is done, the result kept. */
728
- export async function acceptJob(deps, id, jobId) {
729
- const goal = getGoal(deps, id);
730
- const job = findWorkflow(goal, jobId);
731
- const tries = job.doers.filter((d) => d.type === 'assignment');
732
- const last = tries[tries.length - 1];
733
- if (job.kind !== 'once' || job.state !== 'active' || !last)
734
- throw new GoalError('Only an assigned one-off job is accepted.');
735
- const run = await deps.assignmentRun?.(last.agent, last.runId);
736
- if (!run || run.status !== 'done')
737
- throw new GoalError('Its latest try hasn\'t finished with a result yet.');
738
- recordLeverEvent(deps, goal, job, 'done', { tries: tries.length });
739
- return updateWorkflow(deps, goal, jobId, (x) => ({ ...x, state: 'done', doneAt: now(), ...(run.result ? { result: run.result } : {}) }));
740
- }
741
- /** A goal with its once jobs' tries as the page shows them: each one's
742
- * run state and result. */
743
- export async function goalView(deps, goal) {
744
- const jobs = await Promise.all(goal.jobs.map(async (job) => {
745
- const tries = job.doers.filter((d) => d.type === 'assignment');
746
- if (!tries.length)
747
- return job;
748
- const views = await Promise.all(tries.map(async (t) => {
749
- const run = await deps.assignmentRun?.(t.agent, t.runId).catch(() => undefined);
750
- return { runId: t.runId, status: run?.status ?? 'gone', ...(run?.result ? { result: run.result } : {}), ...(run?.error ? { error: run.error } : {}), ...(t.note ? { note: t.note } : {}), at: t.at };
751
- }));
752
- return { ...job, tries: views };
753
- }));
754
- return { ...goal, jobs };
647
+ /** A goal as its page shows it: its workflows and groups. One-off jobs
648
+ * (from before goals suggested only workflows) are left out; their
649
+ * files keep them. */
650
+ export async function goalView(_deps, goal) {
651
+ return { ...goal, jobs: goal.jobs.filter((job) => job.kind !== 'once') };
755
652
  }
756
653
  // ---- Edits: how much the person changed a suggested request at Build.
757
654
  const words = (text) => new Set(text.toLowerCase().replace(/[^a-z0-9$ ]+/g, ' ').split(/\s+/).filter((w) => w.length > 2));
@@ -1,4 +1,4 @@
1
- export type GoalsPageView = 'goals' | 'goal' | 'new' | 'jobs' | 'job' | 'new-job';
1
+ export type GoalsPageView = 'goals' | 'goal' | 'new';
2
2
  export declare function goalsPageAs(view: GoalsPageView): string;
3
3
  /** The Goals page as the list shows it. */
4
4
  export declare const goalsPageHtml: string;