@yesod/core 0.0.2 → 0.1.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/index.js CHANGED
@@ -1,15 +1,25 @@
1
1
  // src/events.ts
2
2
  var EventType = /* @__PURE__ */ ((EventType2) => {
3
3
  EventType2["OrchestrationStarted"] = "orchestration.started";
4
+ EventType2["OrchestrationCompleted"] = "orchestration.completed";
5
+ EventType2["WorkflowStarted"] = "workflow.started";
6
+ EventType2["WorkflowCompleted"] = "workflow.completed";
7
+ EventType2["WorkflowFailed"] = "workflow.failed";
8
+ EventType2["WorkflowStepStarted"] = "workflow.step.started";
9
+ EventType2["WorkflowStepCompleted"] = "workflow.step.completed";
10
+ EventType2["WorkflowStepFailed"] = "workflow.step.failed";
4
11
  EventType2["TaskCreated"] = "task.created";
5
12
  EventType2["TaskDependency"] = "task.dependency";
13
+ EventType2["TaskCompleted"] = "task.completed";
6
14
  EventType2["SessionSpawned"] = "session.spawned";
15
+ EventType2["SessionMessage"] = "session.message";
7
16
  EventType2["SessionEvent"] = "session.event";
8
17
  EventType2["SessionSteered"] = "session.steered";
9
18
  EventType2["SessionArtifact"] = "session.artifact";
10
19
  EventType2["SessionCompleted"] = "session.completed";
11
- EventType2["TaskCompleted"] = "task.completed";
12
- EventType2["OrchestrationCompleted"] = "orchestration.completed";
20
+ EventType2["SessionFailed"] = "session.failed";
21
+ EventType2["SessionKilled"] = "session.killed";
22
+ EventType2["CostIncurred"] = "cost.incurred";
13
23
  EventType2["SubscriptionTriggered"] = "subscription.triggered";
14
24
  return EventType2;
15
25
  })(EventType || {});
@@ -23,6 +33,9 @@ var EventBus = class {
23
33
  this.handlers.set(id, { filter, handler });
24
34
  return id;
25
35
  }
36
+ subscribeAll(handler) {
37
+ return this.subscribe({}, handler);
38
+ }
26
39
  unsubscribe(id) {
27
40
  this.handlers.delete(id);
28
41
  }
@@ -39,9 +52,18 @@ var EventBus = class {
39
52
  await Promise.all(promises);
40
53
  }
41
54
  matches(event, filter) {
42
- if (filter.type && event.type !== filter.type) return false;
55
+ if (filter.type) {
56
+ if (Array.isArray(filter.type)) {
57
+ if (!filter.type.includes(event.type)) return false;
58
+ } else {
59
+ if (event.type !== filter.type) return false;
60
+ }
61
+ }
43
62
  if (filter.sessionId && event.sessionId !== filter.sessionId) return false;
44
- if (filter.orchestrationId && event.orchestrationId !== filter.orchestrationId) return false;
63
+ if (filter.orchestrationId && event.orchestrationId !== filter.orchestrationId)
64
+ return false;
65
+ if (filter.workflowId && event.workflowId !== filter.workflowId)
66
+ return false;
45
67
  return true;
46
68
  }
47
69
  };
@@ -49,15 +71,50 @@ var EventBus = class {
49
71
  // src/vantage.ts
50
72
  var VantageEngine = class {
51
73
  subscriptions = /* @__PURE__ */ new Map();
74
+ barrierState = /* @__PURE__ */ new Map();
52
75
  register(subscription) {
53
- this.subscriptions.set(subscription.id, subscription);
76
+ const sub = { ...subscription, registeredAt: subscription.registeredAt ?? Date.now() };
77
+ this.subscriptions.set(sub.id, sub);
78
+ if (sub.mode === "all") {
79
+ this.barrierState.set(sub.id, /* @__PURE__ */ new Map());
80
+ }
54
81
  }
55
82
  remove(subscriptionId) {
56
83
  this.subscriptions.delete(subscriptionId);
84
+ this.barrierState.delete(subscriptionId);
57
85
  }
58
- /** Evaluate an incoming event against all subscriptions. Returns notifications for any triggered subscriptions. */
59
- evaluate(_event) {
60
- return [];
86
+ evaluate(event) {
87
+ const notifications = [];
88
+ const toRemove = [];
89
+ for (const [id, sub] of this.subscriptions) {
90
+ if (sub.ttl && sub.registeredAt) {
91
+ if (Date.now() - sub.registeredAt > sub.ttl) {
92
+ toRemove.push(id);
93
+ continue;
94
+ }
95
+ }
96
+ if (sub.mode === "any") {
97
+ const matched = this.matchAny(event, sub);
98
+ if (matched) {
99
+ notifications.push({
100
+ type: "subscription.triggered",
101
+ subscriptionId: id,
102
+ matchedEvents: [event]
103
+ });
104
+ if (sub.once) toRemove.push(id);
105
+ }
106
+ } else {
107
+ const notification = this.matchBarrier(event, sub);
108
+ if (notification) {
109
+ notifications.push(notification);
110
+ if (sub.once) toRemove.push(id);
111
+ }
112
+ }
113
+ }
114
+ for (const id of toRemove) {
115
+ this.remove(id);
116
+ }
117
+ return notifications;
61
118
  }
62
119
  getSubscription(id) {
63
120
  return this.subscriptions.get(id);
@@ -65,6 +122,48 @@ var VantageEngine = class {
65
122
  listSubscriptions() {
66
123
  return Array.from(this.subscriptions.values());
67
124
  }
125
+ activeCount() {
126
+ return this.subscriptions.size;
127
+ }
128
+ matchAny(event, sub) {
129
+ return sub.conditions.some((cond) => this.matchCondition(event, cond));
130
+ }
131
+ matchBarrier(event, sub) {
132
+ let barrier = this.barrierState.get(sub.id);
133
+ if (!barrier) {
134
+ barrier = /* @__PURE__ */ new Map();
135
+ this.barrierState.set(sub.id, barrier);
136
+ }
137
+ for (let i = 0; i < sub.conditions.length; i++) {
138
+ if (barrier.has(i)) continue;
139
+ if (this.matchCondition(event, sub.conditions[i])) {
140
+ barrier.set(i, [event]);
141
+ }
142
+ }
143
+ if (barrier.size === sub.conditions.length) {
144
+ const allEvents = [];
145
+ for (const events of barrier.values()) {
146
+ allEvents.push(...events);
147
+ }
148
+ this.barrierState.delete(sub.id);
149
+ return {
150
+ type: "subscription.triggered",
151
+ subscriptionId: sub.id,
152
+ matchedEvents: allEvents
153
+ };
154
+ }
155
+ return null;
156
+ }
157
+ matchCondition(event, cond) {
158
+ if (event.type !== cond.eventType) return false;
159
+ if (cond.sessionId && event.sessionId !== cond.sessionId) return false;
160
+ if (cond.filter) {
161
+ for (const [key, value] of Object.entries(cond.filter)) {
162
+ if (event.payload[key] !== value) return false;
163
+ }
164
+ }
165
+ return true;
166
+ }
68
167
  };
69
168
 
70
169
  // src/storage.ts
@@ -83,10 +182,468 @@ var InMemoryStorageAdapter = class {
83
182
  return this.store.delete(key);
84
183
  }
85
184
  };
185
+
186
+ // src/scheduler.ts
187
+ var SimpleScheduler = class {
188
+ stepStates = /* @__PURE__ */ new Map();
189
+ stepMap = /* @__PURE__ */ new Map();
190
+ constructor(steps) {
191
+ for (const step of steps) {
192
+ this.stepMap.set(step.id, step);
193
+ this.stepStates.set(step.id, "pending");
194
+ }
195
+ }
196
+ getReadySteps() {
197
+ const ready = [];
198
+ for (const [id, state] of this.stepStates) {
199
+ if (state !== "pending") continue;
200
+ const step = this.stepMap.get(id);
201
+ const deps = step.dependsOn ?? [];
202
+ const allDepsCompleted = deps.every(
203
+ (depId) => this.stepStates.get(depId) === "completed"
204
+ );
205
+ if (allDepsCompleted) {
206
+ const reason = deps.length === 0 ? "No dependencies" : `Dependencies satisfied: ${deps.join(", ")}`;
207
+ ready.push({ step, reason });
208
+ }
209
+ }
210
+ return ready;
211
+ }
212
+ markRunning(stepId) {
213
+ this.stepStates.set(stepId, "running");
214
+ }
215
+ markCompleted(stepId) {
216
+ this.stepStates.set(stepId, "completed");
217
+ }
218
+ markFailed(stepId) {
219
+ this.stepStates.set(stepId, "failed");
220
+ }
221
+ getState(stepId) {
222
+ return this.stepStates.get(stepId);
223
+ }
224
+ isComplete() {
225
+ for (const state of this.stepStates.values()) {
226
+ if (state !== "completed" && state !== "failed") return false;
227
+ }
228
+ return true;
229
+ }
230
+ allSucceeded() {
231
+ for (const state of this.stepStates.values()) {
232
+ if (state !== "completed") return false;
233
+ }
234
+ return true;
235
+ }
236
+ /**
237
+ * Mark any pending step whose dependencies include a failed step as failed.
238
+ * Returns IDs of newly failed steps.
239
+ */
240
+ markUnreachable() {
241
+ const failed = [];
242
+ let changed = true;
243
+ while (changed) {
244
+ changed = false;
245
+ for (const [id, state] of this.stepStates) {
246
+ if (state !== "pending") continue;
247
+ const step = this.stepMap.get(id);
248
+ const deps = step.dependsOn ?? [];
249
+ const hasFailedDep = deps.some(
250
+ (depId) => this.stepStates.get(depId) === "failed"
251
+ );
252
+ if (hasFailedDep) {
253
+ this.stepStates.set(id, "failed");
254
+ failed.push(id);
255
+ changed = true;
256
+ }
257
+ }
258
+ }
259
+ return failed;
260
+ }
261
+ };
262
+
263
+ // src/engine.ts
264
+ var idCounter = 0;
265
+ function uid() {
266
+ return `evt-${Date.now()}-${++idCounter}`;
267
+ }
268
+ var OrchestrationEngine = class {
269
+ constructor(adapter, bus, storage) {
270
+ this.adapter = adapter;
271
+ this.bus = bus;
272
+ this.storage = storage;
273
+ this.adapter.onEvent((event) => this.handleAdapterEvent(event));
274
+ }
275
+ adapter;
276
+ bus;
277
+ storage;
278
+ executions = /* @__PURE__ */ new Map();
279
+ createWorkflow(def) {
280
+ const workflow = {
281
+ ...def,
282
+ id: def.id || uid(),
283
+ state: "created",
284
+ createdAt: Date.now()
285
+ };
286
+ const scheduler = new SimpleScheduler(workflow.steps);
287
+ this.executions.set(workflow.id, {
288
+ workflow,
289
+ state: "created",
290
+ scheduler,
291
+ stepResults: /* @__PURE__ */ new Map(),
292
+ activeSessions: /* @__PURE__ */ new Map(),
293
+ startedAt: 0
294
+ });
295
+ return workflow;
296
+ }
297
+ async startWorkflow(workflowId) {
298
+ const exec = this.executions.get(workflowId);
299
+ if (!exec) throw new Error(`Unknown workflow: ${workflowId}`);
300
+ if (exec.state !== "created") {
301
+ throw new Error(`Workflow ${workflowId} is already ${exec.state}`);
302
+ }
303
+ exec.state = "running";
304
+ exec.startedAt = Date.now();
305
+ await this.bus.emit({
306
+ id: uid(),
307
+ type: "workflow.started" /* WorkflowStarted */,
308
+ source: "engine",
309
+ timestamp: Date.now(),
310
+ workflowId,
311
+ payload: { name: exec.workflow.name }
312
+ });
313
+ await this.advanceWorkflow(workflowId);
314
+ }
315
+ async cancelWorkflow(workflowId) {
316
+ const exec = this.executions.get(workflowId);
317
+ if (!exec) throw new Error(`Unknown workflow: ${workflowId}`);
318
+ for (const [stepId, handle] of exec.activeSessions) {
319
+ try {
320
+ await this.adapter.kill(handle);
321
+ } catch {
322
+ }
323
+ exec.scheduler.markFailed(stepId);
324
+ }
325
+ exec.activeSessions.clear();
326
+ exec.state = "failed";
327
+ exec.completedAt = Date.now();
328
+ await this.bus.emit({
329
+ id: uid(),
330
+ type: "workflow.failed" /* WorkflowFailed */,
331
+ source: "engine",
332
+ timestamp: Date.now(),
333
+ workflowId,
334
+ payload: { reason: "cancelled" }
335
+ });
336
+ }
337
+ getWorkflowStatus(workflowId) {
338
+ const exec = this.executions.get(workflowId);
339
+ if (!exec) throw new Error(`Unknown workflow: ${workflowId}`);
340
+ return {
341
+ workflowId,
342
+ state: exec.state,
343
+ steps: exec.workflow.steps.map((step) => ({
344
+ stepId: step.id,
345
+ state: exec.scheduler.getState(step.id) ?? "pending",
346
+ result: exec.stepResults.get(step.id)
347
+ })),
348
+ startedAt: exec.startedAt,
349
+ completedAt: exec.completedAt
350
+ };
351
+ }
352
+ getCostSummary(workflowId) {
353
+ let results = [];
354
+ if (workflowId) {
355
+ const exec = this.executions.get(workflowId);
356
+ if (exec) {
357
+ results = Array.from(exec.stepResults.values());
358
+ }
359
+ } else {
360
+ for (const exec of this.executions.values()) {
361
+ results.push(...exec.stepResults.values());
362
+ }
363
+ }
364
+ let totalUsd = 0;
365
+ let totalInput = 0;
366
+ let totalOutput = 0;
367
+ const perStep = [];
368
+ for (const r of results) {
369
+ totalUsd += r.meta.cost.usd;
370
+ totalInput += r.meta.cost.tokens.input;
371
+ totalOutput += r.meta.cost.tokens.output;
372
+ perStep.push({
373
+ stepId: r.stepId,
374
+ cost: r.meta.cost,
375
+ durationMs: r.meta.durationMs
376
+ });
377
+ }
378
+ return {
379
+ totalUsd,
380
+ totalTokens: { input: totalInput, output: totalOutput },
381
+ perStep
382
+ };
383
+ }
384
+ // --- Internal ---
385
+ async advanceWorkflow(workflowId) {
386
+ const exec = this.executions.get(workflowId);
387
+ if (!exec || exec.state !== "running") return;
388
+ const readySteps = exec.scheduler.getReadySteps();
389
+ for (const { step } of readySteps) {
390
+ exec.scheduler.markRunning(step.id);
391
+ try {
392
+ await this.spawnStep(exec, step, workflowId);
393
+ } catch (err) {
394
+ exec.scheduler.markFailed(step.id);
395
+ await this.bus.emit({
396
+ id: uid(),
397
+ type: "workflow.step.failed" /* WorkflowStepFailed */,
398
+ source: "engine",
399
+ timestamp: Date.now(),
400
+ workflowId,
401
+ stepId: step.id,
402
+ payload: {
403
+ error: err instanceof Error ? err.message : String(err)
404
+ }
405
+ });
406
+ }
407
+ }
408
+ exec.scheduler.markUnreachable();
409
+ if (exec.scheduler.isComplete()) {
410
+ exec.state = exec.scheduler.allSucceeded() ? "completed" : "failed";
411
+ exec.completedAt = Date.now();
412
+ const eventType = exec.state === "completed" ? "workflow.completed" /* WorkflowCompleted */ : "workflow.failed" /* WorkflowFailed */;
413
+ await this.bus.emit({
414
+ id: uid(),
415
+ type: eventType,
416
+ source: "engine",
417
+ timestamp: Date.now(),
418
+ workflowId,
419
+ payload: {
420
+ duration: exec.completedAt - exec.startedAt
421
+ }
422
+ });
423
+ }
424
+ }
425
+ async spawnStep(exec, step, workflowId) {
426
+ const priorContext = [];
427
+ for (const depId of step.dependsOn ?? []) {
428
+ const depResult = exec.stepResults.get(depId);
429
+ if (depResult) priorContext.push(depResult);
430
+ }
431
+ const taskSpec = {
432
+ instruction: step.task,
433
+ expectedResult: step.expectedResult,
434
+ priorContext: priorContext.length > 0 ? priorContext : void 0
435
+ };
436
+ const spawnOpts = {
437
+ task: taskSpec,
438
+ runtime: step.runtime,
439
+ decision: step.decision,
440
+ timeout: step.timeout,
441
+ context: { workflowId, stepId: step.id, attempt: 1 }
442
+ };
443
+ await this.bus.emit({
444
+ id: uid(),
445
+ type: "workflow.step.started" /* WorkflowStepStarted */,
446
+ source: "engine",
447
+ timestamp: Date.now(),
448
+ workflowId,
449
+ stepId: step.id,
450
+ payload: { runtime: step.runtime }
451
+ });
452
+ const handle = await this.adapter.spawn(spawnOpts);
453
+ exec.activeSessions.set(step.id, handle);
454
+ }
455
+ async handleAdapterEvent(event) {
456
+ await this.bus.emit(event);
457
+ if (event.type === "session.completed" /* SessionCompleted */ && event.stepId) {
458
+ await this.handleStepCompleted(event);
459
+ } else if (event.type === "session.failed" /* SessionFailed */ && event.stepId) {
460
+ await this.handleStepFailed(event);
461
+ }
462
+ }
463
+ async handleStepCompleted(event) {
464
+ const workflowId = event.workflowId;
465
+ const stepId = event.stepId;
466
+ if (!workflowId || !stepId) return;
467
+ const exec = this.executions.get(workflowId);
468
+ if (!exec) return;
469
+ const stepResult = event.payload.stepResult;
470
+ if (stepResult) {
471
+ exec.stepResults.set(stepId, stepResult);
472
+ }
473
+ exec.activeSessions.delete(stepId);
474
+ exec.scheduler.markCompleted(stepId);
475
+ await this.bus.emit({
476
+ id: uid(),
477
+ type: "workflow.step.completed" /* WorkflowStepCompleted */,
478
+ source: "engine",
479
+ timestamp: Date.now(),
480
+ workflowId,
481
+ stepId,
482
+ payload: { result: stepResult }
483
+ });
484
+ await this.advanceWorkflow(workflowId);
485
+ }
486
+ async handleStepFailed(event) {
487
+ const workflowId = event.workflowId;
488
+ const stepId = event.stepId;
489
+ if (!workflowId || !stepId) return;
490
+ const exec = this.executions.get(workflowId);
491
+ if (!exec) return;
492
+ exec.activeSessions.delete(stepId);
493
+ exec.scheduler.markFailed(stepId);
494
+ await this.bus.emit({
495
+ id: uid(),
496
+ type: "workflow.step.failed" /* WorkflowStepFailed */,
497
+ source: "engine",
498
+ timestamp: Date.now(),
499
+ workflowId,
500
+ stepId,
501
+ payload: { error: event.payload.error }
502
+ });
503
+ await this.advanceWorkflow(workflowId);
504
+ }
505
+ };
506
+
507
+ // src/tools.ts
508
+ var YESOD_TOOLS = {
509
+ yesod_create_workflow: {
510
+ name: "yesod_create_workflow",
511
+ description: "Create and start a multi-step workflow. Define the steps, their dependencies, and expected output formats. Yesod will orchestrate execution, spawn child agents, and chain results automatically.",
512
+ inputSchema: {
513
+ type: "object",
514
+ properties: {
515
+ name: {
516
+ type: "string",
517
+ description: "Human-readable name for the workflow"
518
+ },
519
+ steps: {
520
+ type: "array",
521
+ description: "Workflow steps to execute",
522
+ items: {
523
+ type: "object",
524
+ properties: {
525
+ id: {
526
+ type: "string",
527
+ description: "Unique step identifier"
528
+ },
529
+ name: {
530
+ type: "string",
531
+ description: "Human-readable step name"
532
+ },
533
+ task: {
534
+ type: "string",
535
+ description: "Instruction for the agent performing this step"
536
+ },
537
+ expectedResult: {
538
+ type: "object",
539
+ description: "Expected output format",
540
+ properties: {
541
+ format: {
542
+ type: "string",
543
+ enum: ["summary", "structured", "diff", "review", "test"]
544
+ },
545
+ fields: {
546
+ type: "array",
547
+ items: { type: "string" },
548
+ description: "Fields to include (for structured format)"
549
+ },
550
+ maxLength: {
551
+ type: "number",
552
+ description: "Max output length in characters"
553
+ }
554
+ },
555
+ required: ["format"]
556
+ },
557
+ runtime: {
558
+ type: "string",
559
+ description: "Runtime to use (e.g. claude-code, codex)"
560
+ },
561
+ decision: {
562
+ type: "object",
563
+ description: "Why this runtime was chosen",
564
+ properties: {
565
+ reason: { type: "string" },
566
+ considered: {
567
+ type: "array",
568
+ items: { type: "string" }
569
+ },
570
+ chosen: { type: "string" }
571
+ },
572
+ required: ["reason", "considered", "chosen"]
573
+ },
574
+ dependsOn: {
575
+ type: "array",
576
+ items: { type: "string" },
577
+ description: "Step IDs this step depends on"
578
+ },
579
+ timeout: {
580
+ type: "number",
581
+ description: "Timeout in milliseconds"
582
+ }
583
+ },
584
+ required: [
585
+ "id",
586
+ "name",
587
+ "task",
588
+ "expectedResult",
589
+ "runtime",
590
+ "decision"
591
+ ]
592
+ }
593
+ }
594
+ },
595
+ required: ["name", "steps"]
596
+ }
597
+ },
598
+ yesod_workflow_status: {
599
+ name: "yesod_workflow_status",
600
+ description: "Check the current status of a running workflow, including per-step progress and results.",
601
+ inputSchema: {
602
+ type: "object",
603
+ properties: {
604
+ workflowId: {
605
+ type: "string",
606
+ description: "ID of the workflow to check"
607
+ }
608
+ },
609
+ required: ["workflowId"]
610
+ }
611
+ },
612
+ yesod_cancel_workflow: {
613
+ name: "yesod_cancel_workflow",
614
+ description: "Cancel a running workflow. Kills all active sessions and marks the workflow as failed.",
615
+ inputSchema: {
616
+ type: "object",
617
+ properties: {
618
+ workflowId: {
619
+ type: "string",
620
+ description: "ID of the workflow to cancel"
621
+ }
622
+ },
623
+ required: ["workflowId"]
624
+ }
625
+ },
626
+ yesod_cost_summary: {
627
+ name: "yesod_cost_summary",
628
+ description: "Get a cost breakdown showing token usage and USD cost, optionally filtered to a specific workflow.",
629
+ inputSchema: {
630
+ type: "object",
631
+ properties: {
632
+ workflowId: {
633
+ type: "string",
634
+ description: "Optional: filter to a specific workflow"
635
+ }
636
+ }
637
+ }
638
+ }
639
+ };
86
640
  export {
87
641
  EventBus,
88
642
  EventType,
89
643
  InMemoryStorageAdapter,
90
- VantageEngine
644
+ OrchestrationEngine,
645
+ SimpleScheduler,
646
+ VantageEngine,
647
+ YESOD_TOOLS
91
648
  };
92
649
  //# sourceMappingURL=index.js.map