@nathanstephenson/flow 0.1.10-beta.5 → 0.1.10-beta.6
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/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
- package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
- package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
- package/build/backend-worker.mjs +7 -3
- package/dist/backend/claude/index.js +6 -0
- package/dist/backend/fake/index.js +6 -0
- package/dist/backend/pi/index.js +34 -2
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/worker/entry.js +4 -1
- package/dist/backend/worker/index.js +5 -0
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/context-usage.js +1 -1
- package/dist/client/markdown.js +3 -2
- package/dist/daemon/config-store.js +1 -0
- package/dist/daemon/config.js +31 -2
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/host.js +147 -6
- package/dist/daemon/runtime.js +1 -1
- package/dist/daemon/server.js +26 -0
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/summariser.js +11 -4
- package/dist/daemon/tour.js +42 -0
- package/dist/daemon/workflow-builder.js +3 -1
- package/dist/daemon/workflow-execution-resources.js +1 -1
- package/dist/daemon/workflow-routes.js +19 -0
- package/dist/daemon/workflow-schedules.js +6 -5
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/workflows/scheduler.js +26 -14
- package/dist/workflows/store.js +16 -2
- package/package.json +1 -1
- package/web/dist/assets/index-BhfJhrVJ.js +51 -0
- package/web/dist/assets/index-BvkM2cWL.css +2 -0
- package/web/dist/assets/{settings-mcp-BwOPXAfH.js → settings-mcp-3cgqQB28.js} +1 -1
- package/web/dist/assets/{settings-workflows-DocTa31_.js → settings-workflows-Cutm8isB.js} +1 -1
- package/web/dist/assets/{workflows-DJqUuGyg.js → workflows-D6oEUUhj.js} +3 -3
- package/web/dist/assets/{workflows-pane-oM1fO_BC.js → workflows-pane-KIdSDKJB.js} +1 -1
- package/web/dist/index.html +3 -3
- package/web/dist/assets/index-BqZ_iUmY.css +0 -2
- package/web/dist/assets/index-CxdSb7k0.js +0 -51
package/dist/daemon/host.js
CHANGED
|
@@ -12,6 +12,7 @@ import { changes, changesText, commitContext, diff } from "./changes.js";
|
|
|
12
12
|
import { commit } from "./commit.js";
|
|
13
13
|
import { push, pushState } from "./push.js";
|
|
14
14
|
import { GitStates, readStatus } from "./git-state.js";
|
|
15
|
+
import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, tourInput, tourText } from "./tour.js";
|
|
15
16
|
import { resolveDefaultBackend } from "../protocol/settings.js";
|
|
16
17
|
import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
|
|
17
18
|
import { deriveStatus, railGroupRank } from "../client/status.js";
|
|
@@ -22,10 +23,11 @@ import { SessionLog } from "./log.js";
|
|
|
22
23
|
import { probeModels } from "./models.js";
|
|
23
24
|
import { PiModelProbeCache } from "./pi-model-cache.js";
|
|
24
25
|
import { ScheduleValidationError } from "../workflows/schedule-errors.js";
|
|
25
|
-
import { probeSkills } from "./skills.js";
|
|
26
|
+
import { probePlanLimits, probeSkills } from "./skills.js";
|
|
26
27
|
import { recordTiming } from "./timings.js";
|
|
27
28
|
import { SharedSandbox } from "../isolation/shared-sandbox.js";
|
|
28
29
|
import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
|
|
30
|
+
import { SpendLedger } from "./spend-ledger.js";
|
|
29
31
|
/**
|
|
30
32
|
* A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
|
|
31
33
|
* Scope that is not a repository, a checkout git itself refused.
|
|
@@ -59,6 +61,7 @@ export class SessionHost {
|
|
|
59
61
|
* one dimension.
|
|
60
62
|
*/
|
|
61
63
|
skillProbes = new Map();
|
|
64
|
+
planLimitProbe;
|
|
62
65
|
/**
|
|
63
66
|
* One Summary Model session, booted before a naming needs it (ADR 0020).
|
|
64
67
|
*
|
|
@@ -66,10 +69,12 @@ export class SessionHost {
|
|
|
66
69
|
* `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
|
|
67
70
|
*/
|
|
68
71
|
summarySpare = new SummaryModelSpare();
|
|
72
|
+
spendLedger;
|
|
69
73
|
stackReviews = new Map();
|
|
70
74
|
gitOperations = new Set();
|
|
71
75
|
gitStates = new GitStates();
|
|
72
76
|
closingScopes = new Set();
|
|
77
|
+
tours = new Map();
|
|
73
78
|
refuseGitOperation(scope) {
|
|
74
79
|
if (this.gitOperations.has(scopeKey(scope)))
|
|
75
80
|
throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
|
|
@@ -236,9 +241,79 @@ export class SessionHost {
|
|
|
236
241
|
throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
|
|
237
242
|
return this.readGit(async () => {
|
|
238
243
|
const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
|
|
239
|
-
return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind
|
|
244
|
+
return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind,
|
|
245
|
+
spent: (spend) => this.recordSpend("publish", randomUUID(), this.spendScope(this.record(sessionId)), spend) });
|
|
240
246
|
});
|
|
241
247
|
}
|
|
248
|
+
tour(sessionId) {
|
|
249
|
+
this.record(sessionId);
|
|
250
|
+
return this.tours.get(sessionId)?.view ?? { state: "idle" };
|
|
251
|
+
}
|
|
252
|
+
startTour(sessionId) {
|
|
253
|
+
const record = this.record(sessionId);
|
|
254
|
+
this.dropTour(sessionId);
|
|
255
|
+
const tour = { id: randomUUID(), view: { state: "running" } };
|
|
256
|
+
this.tours.set(sessionId, tour);
|
|
257
|
+
void this.runTour(record, tour);
|
|
258
|
+
return tour.view;
|
|
259
|
+
}
|
|
260
|
+
cancelTour(sessionId) {
|
|
261
|
+
this.record(sessionId);
|
|
262
|
+
this.dropTour(sessionId);
|
|
263
|
+
return { state: "idle" };
|
|
264
|
+
}
|
|
265
|
+
dropTour(sessionId) {
|
|
266
|
+
const tour = this.tours.get(sessionId);
|
|
267
|
+
this.tours.delete(sessionId);
|
|
268
|
+
void tour?.handle?.cancel().catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
async runTour(record, tour) {
|
|
271
|
+
const current = () => this.tours.get(record.id) === tour;
|
|
272
|
+
let made;
|
|
273
|
+
try {
|
|
274
|
+
const { input, ...found } = await tourInput(record.scope);
|
|
275
|
+
made = found;
|
|
276
|
+
if (!current())
|
|
277
|
+
return;
|
|
278
|
+
tour.view = { state: "running", branch: made.branch, head: made.head };
|
|
279
|
+
if (!record.session)
|
|
280
|
+
await this.revive(record.id);
|
|
281
|
+
const session = record.session;
|
|
282
|
+
if (!current())
|
|
283
|
+
return;
|
|
284
|
+
if (!session?.startWorkflowSubagent)
|
|
285
|
+
throw new Error("This Backend Adapter cannot run a tour.");
|
|
286
|
+
const log = record.log.since(0);
|
|
287
|
+
const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
|
|
288
|
+
const effort = log.findLast(({ event }) => event.type === "effort_changed")?.event;
|
|
289
|
+
const chosen = this.tourModel?.(record.backendName);
|
|
290
|
+
const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
|
|
291
|
+
if (!modelId)
|
|
292
|
+
throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
|
|
293
|
+
tour.handle = session.startWorkflowSubagent({
|
|
294
|
+
id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId,
|
|
295
|
+
effort: chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off",
|
|
296
|
+
permissionMode: "ask",
|
|
297
|
+
emit: ({ event }) => {
|
|
298
|
+
if (event.type === "permission" && event.state === "asked") {
|
|
299
|
+
queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
|
|
300
|
+
}
|
|
301
|
+
if (event.type === "enquiry" && event.state === "asked") {
|
|
302
|
+
queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
|
|
303
|
+
}
|
|
304
|
+
if (event.type === "spend")
|
|
305
|
+
this.workflowSpend(record.id, `tour:${tour.id}`, event.spend);
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
const text = tourText(await tour.handle.done);
|
|
309
|
+
if (current())
|
|
310
|
+
tour.view = { state: "done", text, ...made };
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
if (current())
|
|
314
|
+
tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
242
317
|
store;
|
|
243
318
|
retention;
|
|
244
319
|
standingAuthorisations;
|
|
@@ -250,6 +325,7 @@ export class SessionHost {
|
|
|
250
325
|
defaultEffort;
|
|
251
326
|
defaultPermissionMode;
|
|
252
327
|
summaryModel;
|
|
328
|
+
tourModel;
|
|
253
329
|
closedListeners = new Set();
|
|
254
330
|
backendFailures = new Set();
|
|
255
331
|
keptListeners = new Set();
|
|
@@ -269,6 +345,7 @@ export class SessionHost {
|
|
|
269
345
|
this.mcpAuth = options.mcpAuth;
|
|
270
346
|
this.resolveSecret = options.resolveSecret;
|
|
271
347
|
this.store = options.store;
|
|
348
|
+
this.spendLedger = options.store ? new SpendLedger(options.store.root) : undefined;
|
|
272
349
|
this.retention = options.retention ?? "never";
|
|
273
350
|
this.standingAuthorisations = options.standingAuthorisations;
|
|
274
351
|
this.allowTool = options.allowTool;
|
|
@@ -279,6 +356,7 @@ export class SessionHost {
|
|
|
279
356
|
this.defaultEffort = options.defaultEffort;
|
|
280
357
|
this.defaultPermissionMode = options.defaultPermissionMode;
|
|
281
358
|
this.summaryModel = options.summaryModel;
|
|
359
|
+
this.tourModel = options.tourModel;
|
|
282
360
|
}
|
|
283
361
|
/**
|
|
284
362
|
* Notified when an Agent Session stops being something its owner is working in — Settled, Ended
|
|
@@ -398,6 +476,27 @@ export class SessionHost {
|
|
|
398
476
|
}
|
|
399
477
|
return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
|
|
400
478
|
}
|
|
479
|
+
async planLimits(scope) {
|
|
480
|
+
this.planLimitProbe ??= Promise.all([...this.backends.values()].map(async (backend) => (await this.askPlanLimits(backend, scope)).map((windows) => ({ backend: backend.name, ...windows }))))
|
|
481
|
+
.then((answers) => answers.flat())
|
|
482
|
+
.finally(() => { this.planLimitProbe = undefined; });
|
|
483
|
+
return await this.planLimitProbe;
|
|
484
|
+
}
|
|
485
|
+
async askPlanLimits(backend, scope) {
|
|
486
|
+
const warm = this.skillSessions.get(backend.name);
|
|
487
|
+
if (warm && !warm.dead) {
|
|
488
|
+
if (!warm.session.planLimits)
|
|
489
|
+
return [];
|
|
490
|
+
try {
|
|
491
|
+
return await this.timed("planLimits", backend, true, () => warm.session.planLimits());
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
this.skillSessions.delete(backend.name);
|
|
495
|
+
void warm.session.dispose().catch(() => { });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return await this.timed("planLimits", backend, false, (timed) => probePlanLimits(timed, scope, (held) => this.holdSkillSession(backend.name, held, false)));
|
|
499
|
+
}
|
|
401
500
|
/** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
|
|
402
501
|
holdSkillSession(name, held, replace) {
|
|
403
502
|
const old = this.skillSessions.get(name);
|
|
@@ -570,6 +669,8 @@ export class SessionHost {
|
|
|
570
669
|
if (!meta || this.sessions.has(id))
|
|
571
670
|
continue;
|
|
572
671
|
const entries = this.store.readEntries(id);
|
|
672
|
+
if (this.spendLedger?.needsBackfill)
|
|
673
|
+
this.backfillSpend(id, scopeKey(meta.worktree?.repo ?? meta.scope), entries);
|
|
573
674
|
const record = {
|
|
574
675
|
id: meta.id,
|
|
575
676
|
scope: meta.scope,
|
|
@@ -636,8 +737,29 @@ export class SessionHost {
|
|
|
636
737
|
}
|
|
637
738
|
this.persist(record);
|
|
638
739
|
}
|
|
740
|
+
this.spendLedger?.finishBackfill();
|
|
639
741
|
await this.reap();
|
|
640
742
|
}
|
|
743
|
+
backfillSpend(sessionId, scope, entries) {
|
|
744
|
+
for (const { event, at } of entries.slice(entries.findLastIndex(({ event }) => event.type === "forked") + 1)) {
|
|
745
|
+
if (event.type === "context_usage" && event.spend)
|
|
746
|
+
this.spendLedger.record("session", sessionId, scope, event.spend, at);
|
|
747
|
+
if (event.type === "workflow_spend")
|
|
748
|
+
this.spendLedger.record("workflow", JSON.stringify([sessionId, event.executionId]), scope, event.spend, at);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
recordSpend(source, key, scope, spend) {
|
|
752
|
+
this.spendLedger?.record(source, key, scope, spend);
|
|
753
|
+
}
|
|
754
|
+
spendSummary() {
|
|
755
|
+
return this.spendLedger?.summary();
|
|
756
|
+
}
|
|
757
|
+
namingSpent(record) {
|
|
758
|
+
return (spend) => this.recordSpend("naming", randomUUID(), this.spendScope(record), spend);
|
|
759
|
+
}
|
|
760
|
+
spendScope(record) {
|
|
761
|
+
return scopeKey(record.worktree?.repo ?? record.scope);
|
|
762
|
+
}
|
|
641
763
|
scheduledAttachments = new Map();
|
|
642
764
|
/** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
|
|
643
765
|
* The caller has already journaled the intended identity before entering this operation. */
|
|
@@ -1457,8 +1579,13 @@ export class SessionHost {
|
|
|
1457
1579
|
/** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
|
|
1458
1580
|
appendForkPrefix(record, sourceId, userMessageId, prefix) {
|
|
1459
1581
|
for (const { event, at } of prefix) {
|
|
1460
|
-
if (event.type === "session_started" || event.type === "queue_changed")
|
|
1582
|
+
if (event.type === "session_started" || event.type === "queue_changed" || event.type === "workflow_spend")
|
|
1461
1583
|
continue;
|
|
1584
|
+
if (event.type === "context_usage" && event.spend) {
|
|
1585
|
+
const { spend: _, ...rest } = event;
|
|
1586
|
+
record.log.append(rest, at);
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1462
1589
|
if (event.type === "revived") {
|
|
1463
1590
|
record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
|
|
1464
1591
|
continue;
|
|
@@ -1906,6 +2033,7 @@ export class SessionHost {
|
|
|
1906
2033
|
if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
|
|
1907
2034
|
return;
|
|
1908
2035
|
record.log.append({ type: 'workflow_spend', executionId, spend });
|
|
2036
|
+
this.recordSpend("workflow", JSON.stringify([sessionId, executionId]), this.spendScope(record), spend);
|
|
1909
2037
|
}
|
|
1910
2038
|
authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
|
|
1911
2039
|
workflowNamingAllowed(sessionId) {
|
|
@@ -1917,6 +2045,7 @@ export class SessionHost {
|
|
|
1917
2045
|
if (!record)
|
|
1918
2046
|
return;
|
|
1919
2047
|
this.refuseGitOperation(record.scope);
|
|
2048
|
+
this.dropTour(sessionId);
|
|
1920
2049
|
const session = record.session;
|
|
1921
2050
|
record.session = undefined;
|
|
1922
2051
|
record.lifecycle = "ended";
|
|
@@ -1943,6 +2072,7 @@ export class SessionHost {
|
|
|
1943
2072
|
throw new Error(`Session ${sessionId} has ended`);
|
|
1944
2073
|
if (record.lifecycle === "settled")
|
|
1945
2074
|
return;
|
|
2075
|
+
this.dropTour(sessionId);
|
|
1946
2076
|
const session = record.session;
|
|
1947
2077
|
record.session = undefined;
|
|
1948
2078
|
record.lifecycle = "settled";
|
|
@@ -2010,6 +2140,7 @@ export class SessionHost {
|
|
|
2010
2140
|
await this.releaseWorktree(record);
|
|
2011
2141
|
record.log.closeSubscribers();
|
|
2012
2142
|
this.sessions.delete(record.id);
|
|
2143
|
+
this.dropTour(record.id);
|
|
2013
2144
|
this.store?.deleteSession(record.id);
|
|
2014
2145
|
reaped.push(record.id);
|
|
2015
2146
|
}
|
|
@@ -2089,7 +2220,7 @@ export class SessionHost {
|
|
|
2089
2220
|
}
|
|
2090
2221
|
const generation = (record.titleGeneration += 1);
|
|
2091
2222
|
let reason;
|
|
2092
|
-
const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
|
|
2223
|
+
const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; }, this.namingSpent(record));
|
|
2093
2224
|
if (name === undefined)
|
|
2094
2225
|
throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
|
|
2095
2226
|
// Refused rather than applied when something newer has already been asked for. A human who
|
|
@@ -2123,7 +2254,7 @@ export class SessionHost {
|
|
|
2123
2254
|
const generation = (record.titleGeneration += 1);
|
|
2124
2255
|
let name;
|
|
2125
2256
|
try {
|
|
2126
|
-
name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
|
|
2257
|
+
name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input, undefined, undefined, this.namingSpent(record));
|
|
2127
2258
|
}
|
|
2128
2259
|
catch {
|
|
2129
2260
|
return;
|
|
@@ -2268,6 +2399,12 @@ export class SessionHost {
|
|
|
2268
2399
|
return await this.withGitOperation(this.gitScope(command.sessionId), () => this.afterPullRequestWrite(this.record(command.sessionId).scope, createPullRequest(this.record(command.sessionId).scope, { head: command.head, title: command.title, body: command.body, draft: command.draft === true })));
|
|
2269
2400
|
case "suggest_git_text":
|
|
2270
2401
|
return await this.suggestGitText(command.sessionId, command.kind, command.paths);
|
|
2402
|
+
case "start_tour":
|
|
2403
|
+
return this.startTour(command.sessionId);
|
|
2404
|
+
case "tour":
|
|
2405
|
+
return this.tour(command.sessionId);
|
|
2406
|
+
case "cancel_tour":
|
|
2407
|
+
return this.cancelTour(command.sessionId);
|
|
2271
2408
|
case "switch_branch":
|
|
2272
2409
|
return await this.switchBranch(command.sessionId, command.branch);
|
|
2273
2410
|
case "switch_scope_branch":
|
|
@@ -2925,8 +3062,10 @@ export class SessionHost {
|
|
|
2925
3062
|
void this.workflowOwner?.stop(sessionId).catch(() => { });
|
|
2926
3063
|
// Kept current so a Revive can hand the running total back to the next Backend Session, which
|
|
2927
3064
|
// counts only its own run.
|
|
2928
|
-
if (event.type === "context_usage" && event.spend)
|
|
3065
|
+
if (event.type === "context_usage" && event.spend) {
|
|
2929
3066
|
record.spend = event.spend;
|
|
3067
|
+
this.recordSpend("session", sessionId, this.spendScope(record), event.spend);
|
|
3068
|
+
}
|
|
2930
3069
|
/*
|
|
2931
3070
|
* Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
|
|
2932
3071
|
* for the race the field's own comment describes. It matters for the turn nobody asked for: a
|
|
@@ -3378,6 +3517,8 @@ function spendFrom(entries) {
|
|
|
3378
3517
|
const event = entry.event;
|
|
3379
3518
|
if (event.type === "context_usage" && event.spend)
|
|
3380
3519
|
spend = event.spend;
|
|
3520
|
+
if (event.type === "forked")
|
|
3521
|
+
spend = undefined;
|
|
3381
3522
|
}
|
|
3382
3523
|
return spend;
|
|
3383
3524
|
}
|
package/dist/daemon/runtime.js
CHANGED
|
@@ -52,7 +52,7 @@ export async function startRuntime(options) {
|
|
|
52
52
|
sandboxSharing: config.sandboxSharing, projectRoot: config.projectRoot,
|
|
53
53
|
standingAuthorisations: config.standingAuthorisations, allowTool: config.allowTool,
|
|
54
54
|
defaultBackend: config.defaultBackend, defaultModel: config.defaultModel,
|
|
55
|
-
defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
|
|
55
|
+
defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel, tourModel: config.tourModel,
|
|
56
56
|
});
|
|
57
57
|
const shells = new ShellRegistry();
|
|
58
58
|
let workflowSchedules;
|
package/dist/daemon/server.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { createServer } from "node:http";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
import { homedir } from "node:os";
|
|
2
4
|
import { mediaTypeOf } from "../protocol/attachments.js";
|
|
3
5
|
import { ConfigError } from "./config.js";
|
|
6
|
+
import { gh } from "./github.js";
|
|
7
|
+
import { githubImage } from "./github-image.js";
|
|
4
8
|
import { workflowRoutes } from './workflow-routes.js';
|
|
5
9
|
import { workflowScheduleRoutes } from './workflow-schedule-routes.js';
|
|
6
10
|
import { workflowBuilderRoutes } from './workflow-builder-routes.js';
|
|
@@ -367,6 +371,14 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
|
|
|
367
371
|
send(response, 200, options.host.list());
|
|
368
372
|
return;
|
|
369
373
|
}
|
|
374
|
+
if (request.method === "GET" && url.pathname === "/api/spend") {
|
|
375
|
+
send(response, 200, options.host.spendSummary());
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (request.method === "GET" && url.pathname === "/api/plan-limits") {
|
|
379
|
+
send(response, 200, await options.host.planLimits(options.config?.projectRoot() ?? options.scope ?? process.cwd()));
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
370
382
|
if (request.method === "GET" && url.pathname === "/api/config") {
|
|
371
383
|
send(response, 200, {
|
|
372
384
|
// The Project Root first: it is the directory this deployment is anchored to, and a client
|
|
@@ -559,6 +571,20 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
|
|
|
559
571
|
sendAttachment(response, options.store, attachmentMatch[1] ?? "", attachmentMatch[2] ?? "");
|
|
560
572
|
return;
|
|
561
573
|
}
|
|
574
|
+
if (request.method === "GET" && url.pathname === "/api/github-image") {
|
|
575
|
+
const image = await githubImage(url.searchParams.get("url") ?? "", () => gh(homedir(), ["auth", "token"])).catch(() => null);
|
|
576
|
+
if (!image?.body) {
|
|
577
|
+
send(response, 404, { error: "Image not found." });
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
response.writeHead(200, {
|
|
581
|
+
"content-type": image.headers.get("content-type") ?? "",
|
|
582
|
+
"x-content-type-options": "nosniff",
|
|
583
|
+
"cache-control": "private, max-age=300",
|
|
584
|
+
});
|
|
585
|
+
Readable.fromWeb(image.body).pipe(response);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
562
588
|
if (request.method === "POST" && url.pathname === "/api/command") {
|
|
563
589
|
const command = JSON.parse(await readBody(request));
|
|
564
590
|
try {
|
package/dist/daemon/skills.js
CHANGED
|
@@ -83,6 +83,30 @@ export async function probeSkills(backend, scope, keep) {
|
|
|
83
83
|
await release(held, answered ? keep : undefined);
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
|
+
export async function probePlanLimits(backend, scope, keep) {
|
|
87
|
+
const { held, options } = probeSession(scope);
|
|
88
|
+
const started = backend.create(options);
|
|
89
|
+
const session = await within(started, PROBE_TIMEOUT_MS);
|
|
90
|
+
if (session === undefined) {
|
|
91
|
+
void started.then((late) => void late.dispose().catch(() => { }), () => { });
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
if (session instanceof Error)
|
|
95
|
+
return [];
|
|
96
|
+
held.session = session;
|
|
97
|
+
let answered = false;
|
|
98
|
+
try {
|
|
99
|
+
const limits = await session.planLimits?.() ?? [];
|
|
100
|
+
answered = true;
|
|
101
|
+
return limits;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await release(held, answered ? keep : undefined);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
86
110
|
function message(error) {
|
|
87
111
|
return error instanceof Error ? error.message : String(error);
|
|
88
112
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, truncateSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
const HOUR = 60 * 60 * 1000;
|
|
4
|
+
const DAY = 24 * HOUR;
|
|
5
|
+
const WINDOWS = {
|
|
6
|
+
day: { span: DAY, bucket: HOUR }, week: { span: 7 * DAY, bucket: 6 * HOUR }, month: { span: 30 * DAY, bucket: DAY }, lifetime: { span: Infinity, bucket: 0 },
|
|
7
|
+
};
|
|
8
|
+
const LIFETIME_BUCKETS = [DAY, 7 * DAY, 30 * DAY];
|
|
9
|
+
const MAX_BARS = 60;
|
|
10
|
+
export class SpendLedger {
|
|
11
|
+
path;
|
|
12
|
+
backfill;
|
|
13
|
+
last = new Map();
|
|
14
|
+
deltas = [];
|
|
15
|
+
constructor(root) {
|
|
16
|
+
this.path = join(root, "spend-ledger.jsonl");
|
|
17
|
+
if (!existsSync(this.path)) {
|
|
18
|
+
this.backfill = [];
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const raw = readFileSync(this.path, "utf8");
|
|
22
|
+
const complete = raw.slice(0, raw.lastIndexOf("\n") + 1);
|
|
23
|
+
if (complete.length < raw.length)
|
|
24
|
+
truncateSync(this.path, Buffer.byteLength(complete));
|
|
25
|
+
for (const line of complete.split("\n"))
|
|
26
|
+
if (line)
|
|
27
|
+
this.apply(JSON.parse(line));
|
|
28
|
+
}
|
|
29
|
+
get needsBackfill() {
|
|
30
|
+
return this.backfill !== undefined;
|
|
31
|
+
}
|
|
32
|
+
record(source, key, scope, spend, at = new Date().toISOString()) {
|
|
33
|
+
const readings = spend.models.flatMap(({ id, tokens, cached, costUSD }) => {
|
|
34
|
+
const previous = this.last.get(JSON.stringify([key, id]));
|
|
35
|
+
if (previous?.tokens === tokens && previous.cached === cached && previous.costUSD === costUSD)
|
|
36
|
+
return [];
|
|
37
|
+
return [{ at, source, key, ...(scope === undefined ? {} : { scope }), model: id, tokens, cached, costUSD }];
|
|
38
|
+
});
|
|
39
|
+
if (readings.length === 0)
|
|
40
|
+
return;
|
|
41
|
+
if (this.backfill)
|
|
42
|
+
this.backfill.push(...readings);
|
|
43
|
+
else
|
|
44
|
+
write(this.path, "a", readings);
|
|
45
|
+
for (const reading of readings)
|
|
46
|
+
this.apply(reading);
|
|
47
|
+
}
|
|
48
|
+
finishBackfill() {
|
|
49
|
+
if (!this.backfill)
|
|
50
|
+
return;
|
|
51
|
+
mkdirSync(dirname(this.path), { recursive: true });
|
|
52
|
+
write(`${this.path}.tmp`, "w", this.backfill);
|
|
53
|
+
renameSync(`${this.path}.tmp`, this.path);
|
|
54
|
+
this.backfill = undefined;
|
|
55
|
+
}
|
|
56
|
+
summary(now = Date.now()) {
|
|
57
|
+
const entries = Object.entries(WINDOWS).map(([name, { span, bucket }]) => [name, this.window(now, span, bucket)]);
|
|
58
|
+
return Object.fromEntries(entries);
|
|
59
|
+
}
|
|
60
|
+
apply(reading) {
|
|
61
|
+
const id = JSON.stringify([reading.key, reading.model]);
|
|
62
|
+
const previous = this.last.get(id);
|
|
63
|
+
const counted = previous && reading.tokens >= previous.tokens && reading.costUSD >= previous.costUSD ? previous : undefined;
|
|
64
|
+
this.last.set(id, { tokens: reading.tokens, cached: reading.cached, costUSD: reading.costUSD });
|
|
65
|
+
this.deltas.push({
|
|
66
|
+
at: Date.parse(reading.at), source: reading.source, model: reading.model,
|
|
67
|
+
tokens: reading.tokens - (counted?.tokens ?? 0),
|
|
68
|
+
cached: reading.cached - (counted?.cached ?? 0),
|
|
69
|
+
costUSD: reading.costUSD - (counted?.costUSD ?? 0),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
window(now, span, bucket) {
|
|
73
|
+
const since = now - span;
|
|
74
|
+
const start = Number.isFinite(since) ? since : this.deltas.reduce((earliest, delta) => Math.min(earliest, delta.at), now);
|
|
75
|
+
const size = bucket || LIFETIME_BUCKETS.find(size => (now - start) / size <= MAX_BARS) || LIFETIME_BUCKETS.at(-1);
|
|
76
|
+
const count = Math.max(1, Math.ceil((now - start) / size));
|
|
77
|
+
const first = now - count * size;
|
|
78
|
+
const result = {
|
|
79
|
+
tokens: 0, cached: 0, costUSD: 0, models: [], sources: [],
|
|
80
|
+
buckets: Array.from({ length: count }, (_, index) => ({ start: new Date(first + index * size).toISOString(), models: [] })),
|
|
81
|
+
};
|
|
82
|
+
for (const delta of this.deltas) {
|
|
83
|
+
if (delta.at < since)
|
|
84
|
+
continue;
|
|
85
|
+
add(result, delta);
|
|
86
|
+
const { models } = result.buckets[Math.min(count - 1, Math.max(0, Math.floor((delta.at - first) / size)))];
|
|
87
|
+
add(find(models, model => model.id === delta.model, () => ({ id: delta.model, tokens: 0, cached: 0, costUSD: 0 })), delta);
|
|
88
|
+
add(find(result.models, model => model.id === delta.model, () => ({ id: delta.model, tokens: 0, cached: 0, costUSD: 0 })), delta);
|
|
89
|
+
add(find(result.sources, source => source.source === delta.source, () => ({ source: delta.source, tokens: 0, cached: 0, costUSD: 0 })), delta);
|
|
90
|
+
}
|
|
91
|
+
result.models.sort((a, b) => b.costUSD - a.costUSD || b.tokens - a.tokens);
|
|
92
|
+
result.sources.sort((a, b) => b.costUSD - a.costUSD || b.tokens - a.tokens);
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function write(path, flags, readings) {
|
|
97
|
+
const fd = openSync(path, flags, 0o600);
|
|
98
|
+
try {
|
|
99
|
+
writeFileSync(fd, readings.map(reading => JSON.stringify(reading) + "\n").join(""));
|
|
100
|
+
fsyncSync(fd);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
closeSync(fd);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function add(total, delta) {
|
|
107
|
+
total.tokens += delta.tokens;
|
|
108
|
+
total.cached += delta.cached;
|
|
109
|
+
total.costUSD += delta.costUSD;
|
|
110
|
+
}
|
|
111
|
+
function find(items, match, create) {
|
|
112
|
+
const found = items.find(match);
|
|
113
|
+
if (found)
|
|
114
|
+
return found;
|
|
115
|
+
const item = create();
|
|
116
|
+
items.push(item);
|
|
117
|
+
return item;
|
|
118
|
+
}
|
|
@@ -98,6 +98,8 @@ export async function suggestGitText(request) {
|
|
|
98
98
|
finally {
|
|
99
99
|
if (timer)
|
|
100
100
|
clearTimeout(timer);
|
|
101
|
+
if (session?.spend)
|
|
102
|
+
request.spent?.(session.spend);
|
|
101
103
|
if (session)
|
|
102
104
|
await session.dispose().catch(() => { });
|
|
103
105
|
}
|
|
@@ -242,13 +244,13 @@ export class SummaryModelSpare {
|
|
|
242
244
|
* tick, before any await. Two namings that both saw the same spare would prompt one Backend
|
|
243
245
|
* Session twice and take each other's answers.
|
|
244
246
|
*/
|
|
245
|
-
async name(backend, model, text, timeoutMs, problem) {
|
|
247
|
+
async name(backend, model, text, timeoutMs, problem, spent) {
|
|
246
248
|
const claimed = this.claim(model);
|
|
247
249
|
try {
|
|
248
250
|
const spare = claimed ? await claimed.session : undefined;
|
|
249
251
|
if (claimed && spare && !claimed.sink.dead) {
|
|
250
252
|
try {
|
|
251
|
-
return await nameWith(spare, claimed.sink, text, timeoutMs ?? SUMMARY_TIMEOUT_MS, problem);
|
|
253
|
+
return await nameWith(spare, claimed.sink, text, timeoutMs ?? SUMMARY_TIMEOUT_MS, problem, spent);
|
|
252
254
|
}
|
|
253
255
|
finally {
|
|
254
256
|
await spare.dispose().catch(() => { });
|
|
@@ -264,6 +266,7 @@ export class SummaryModelSpare {
|
|
|
264
266
|
text,
|
|
265
267
|
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
266
268
|
...(problem === undefined ? {} : { problem }),
|
|
269
|
+
...(spent === undefined ? {} : { spent }),
|
|
267
270
|
});
|
|
268
271
|
}
|
|
269
272
|
finally {
|
|
@@ -373,7 +376,7 @@ export async function summariseToName(request) {
|
|
|
373
376
|
return undefined;
|
|
374
377
|
}
|
|
375
378
|
try {
|
|
376
|
-
return await nameWith(session, sink, text, request.timeoutMs ?? SUMMARY_TIMEOUT_MS, request.problem);
|
|
379
|
+
return await nameWith(session, sink, text, request.timeoutMs ?? SUMMARY_TIMEOUT_MS, request.problem, request.spent);
|
|
377
380
|
}
|
|
378
381
|
finally {
|
|
379
382
|
// Every path: answered, junk, timed out, or the prompt itself throwing. A leaked adapter is a
|
|
@@ -390,7 +393,7 @@ export async function summariseToName(request) {
|
|
|
390
393
|
*
|
|
391
394
|
* Never throws, like everything else here.
|
|
392
395
|
*/
|
|
393
|
-
async function nameWith(session, sink, text, timeoutMs, problem) {
|
|
396
|
+
async function nameWith(session, sink, text, timeoutMs, problem, spent) {
|
|
394
397
|
/*
|
|
395
398
|
* Latest-wins per id, because `message` events are snapshots of one message as it streams rather
|
|
396
399
|
* than pieces of it — appending them would give a name repeated once per token.
|
|
@@ -423,6 +426,10 @@ async function nameWith(session, sink, text, timeoutMs, problem) {
|
|
|
423
426
|
problem?.(message(error));
|
|
424
427
|
return undefined;
|
|
425
428
|
}
|
|
429
|
+
finally {
|
|
430
|
+
if (session.spend)
|
|
431
|
+
spent?.(session.spend);
|
|
432
|
+
}
|
|
426
433
|
const answer = [...said.values()].join("\n").trim();
|
|
427
434
|
const name = nameFrom(answer);
|
|
428
435
|
if (name === undefined) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { head, run, GIT_READ_TIMEOUT_MS } from "./git.js";
|
|
2
|
+
import { gh } from "./github.js";
|
|
3
|
+
import { changes, changesText } from "./changes.js";
|
|
4
|
+
import { resolveRepository } from "./repository.js";
|
|
5
|
+
export const TOUR_INSTRUCTIONS = [
|
|
6
|
+
"Give an in-depth tour of this branch's committed changes, with the diff shown for each change you discuss.",
|
|
7
|
+
"Step through the functional implementation in the order it runs, not file by file.",
|
|
8
|
+
"Include all important diffs. Put a short summary of the supporting changes at the bottom.",
|
|
9
|
+
"The input has the branch, its base, the commits and the diff. Read files in the Scope only when the diff is not enough.",
|
|
10
|
+
"Read only: do not edit, write, run commands or ask questions.",
|
|
11
|
+
'Write the tour as markdown and return it as {"tour":"<markdown>"}.',
|
|
12
|
+
].join("\n");
|
|
13
|
+
export const TOUR_READ_TOOLS = ["Read", "Glob", "Grep", "read", "grep", "find", "ls"];
|
|
14
|
+
export async function tourInput(scope, github = gh) {
|
|
15
|
+
const branch = await head(scope);
|
|
16
|
+
if (!branch.ok)
|
|
17
|
+
throw new Error(branch.failure.message);
|
|
18
|
+
if (branch.value.detached)
|
|
19
|
+
throw new Error("HEAD is detached. Switch to a branch before you start a tour.");
|
|
20
|
+
const sha = await run(scope, ["rev-parse", "HEAD"], GIT_READ_TIMEOUT_MS);
|
|
21
|
+
if (!sha.ok)
|
|
22
|
+
throw new Error(sha.failure.message);
|
|
23
|
+
const repository = await resolveRepository(scope, branch.value.name, github);
|
|
24
|
+
const listed = await changes(scope, "branch", undefined, github);
|
|
25
|
+
if (listed.commits.length === 0)
|
|
26
|
+
throw new Error("This branch has no committed changes to tour.");
|
|
27
|
+
return {
|
|
28
|
+
branch: branch.value.name,
|
|
29
|
+
head: sha.value.trim(),
|
|
30
|
+
repo: repository.head.repo,
|
|
31
|
+
input: `Branch: ${branch.value.name}\nBase: ${listed.base}\n${await changesText(scope, "branch", undefined, undefined, github)}`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function tourText(raw) {
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(raw);
|
|
37
|
+
if (typeof parsed === "object" && parsed !== null && typeof parsed.tour === "string")
|
|
38
|
+
return parsed.tour;
|
|
39
|
+
}
|
|
40
|
+
catch { }
|
|
41
|
+
return raw;
|
|
42
|
+
}
|
|
@@ -374,8 +374,10 @@ export class WorkflowBuilderService {
|
|
|
374
374
|
},
|
|
375
375
|
emit: event => {
|
|
376
376
|
if (event.type === 'context_usage') {
|
|
377
|
-
if (event.spend && entry.meterGeneration === generation)
|
|
377
|
+
if (event.spend && entry.meterGeneration === generation) {
|
|
378
378
|
entry.view.spend = structuredClone(event.spend);
|
|
379
|
+
this.options.host.recordSpend('builder', entry.view.id, entry.view.scope || undefined, event.spend);
|
|
380
|
+
}
|
|
379
381
|
if (!entry.closed && entry.generation === generation)
|
|
380
382
|
this.event(entry, event);
|
|
381
383
|
}
|
|
@@ -22,7 +22,7 @@ export class OccurrenceResources {
|
|
|
22
22
|
connections() { return this.host.scheduledConnections(this.environment.connectionIds); }
|
|
23
23
|
mcp(connectionId, _mode, signal) { return this.environment.client(connectionId, signal); }
|
|
24
24
|
sandbox() { return this.environment.vm(); }
|
|
25
|
-
attach() { return this.attached ??= this.attachment(); }
|
|
25
|
+
attach() { return this.attached ??= this.attachment().catch(error => { this.attached = undefined; throw error; }); }
|
|
26
26
|
restoreAttachment(attach) { this.attachment = attach; }
|
|
27
27
|
}
|
|
28
28
|
export class WorkflowExecutionResources {
|
|
@@ -32,6 +32,25 @@ function validateWorkflowContracts(definition, workflows) {
|
|
|
32
32
|
if (!selected || !isDeepStrictEqual(selected.contract, step.contract))
|
|
33
33
|
throw new Error(`Workflow step ${step.name} requires a saved host-derived contract`);
|
|
34
34
|
}
|
|
35
|
+
const path = new Set();
|
|
36
|
+
const visit = (current) => {
|
|
37
|
+
if (path.has(current.id))
|
|
38
|
+
throw new Error('Recursive Workflow call');
|
|
39
|
+
path.add(current.id);
|
|
40
|
+
for (const step of current.steps) {
|
|
41
|
+
if (step.kind !== 'workflow')
|
|
42
|
+
continue;
|
|
43
|
+
let target = step.workflowId === definition.id ? definition : undefined;
|
|
44
|
+
try {
|
|
45
|
+
target ??= workflows.getDefinition(step.workflowId);
|
|
46
|
+
}
|
|
47
|
+
catch { }
|
|
48
|
+
if (target)
|
|
49
|
+
visit(target);
|
|
50
|
+
}
|
|
51
|
+
path.delete(current.id);
|
|
52
|
+
};
|
|
53
|
+
visit(definition);
|
|
35
54
|
}
|
|
36
55
|
export function workflowRequestError(error, redact = message => message) {
|
|
37
56
|
// Redact before truncation: a credential containing ':' must not leak its prefix.
|