Repository navigation
Expand file tree
/
Copy pathrun-program.ts
More file actions
1425 lines (1368 loc) · 49.9 KB
/
Copy pathrun-program.ts
File metadata and controls
1425 lines (1368 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Run a registered program on a session store the caller owns. It never exits the process. */
import path from 'path';
import { randomUUID } from 'crypto';
import { DEFAULT_BINDING, runAgent, RunOutcome } from '@agent';
import type {
AgentProgress,
AgentRunDefinition,
RunHooks,
RunInput,
RunResult,
} from '@agent/types';
import {
getSkillsBaseUrl,
WIZARD_VERSIONED_SDK_SKILLS_FLAG_KEY,
type Integration,
} from '@shared/constants';
import { listSkillFolders, removeRunSkills } from '@shared/skill-install';
import { classifyRunFailure, ErrorCodes, type ErrorCode } from '@shared/errors';
import {
backupAndFixClaudeSettings,
checkAllSettingsConflicts,
classifySettingsConflicts,
restoreClaudeSettings,
} from '@shared/claude-settings';
import {
evaluateWizardReadiness,
getBlockingServiceKeys,
SERVICE_LABELS,
WizardReadiness,
} from '@shared/health-checks/readiness';
import { OutroKind } from '@shared/outro';
import { RunPhase } from '@shared/run-state';
import {
configureOAuthSession,
currentCredentials,
} from '@shared/oauth-session';
import { analytics } from '@utils/analytics';
import { registerCleanup } from '@utils/cleanup';
import { logToFile } from '@utils/debug';
import { removeAuditLedger, startAuditLedgerWatcher } from '@programs/audit';
import { FRAMEWORK_REGISTRY } from '@services/frameworks';
import {
buildProjectSelection,
getTraits,
maySendDiscovery,
picksProject,
askUserToSelectProject,
reportDiscovery,
reportProjectsDiscovered,
reportProjectsSelected,
sdkFeatureGaps,
settleProjects,
toMatchKeys,
toTraitKeys,
type PickedBy,
type ProjectPick,
type ProjectSelection,
VERSIONED_SDK_SKILLS_ENABLED_KEY,
whyNothingToSetUp,
} from '@services/project-discovery';
import { findProgramConfig, getProgramConfig } from './program-registry';
import { nothingToSetUp, ProgramAbort } from '@programs/program-contract';
import { detectionFailure, detectProgram } from './detect-program';
import {
rotateCredentials,
type ResolvedProgramCredentials,
} from './credentials';
import {
DECISIONS_USE_KEY,
decisionsUse,
questionFacts,
runDecisionsSource,
type QuestionKey,
} from '@services/detection/decisions';
import { logIn } from './login';
import { applyAgentProgress, type SessionStore } from '@services/session';
import type { WizardSession } from '@services/session';
import type { ProgramConfig, ProgramRunStep } from '@programs/program-contract';
import type { ProgramRun } from '@programs/program-contract';
import type { ProgramSession } from '@programs/program-contract';
import type {
CiRunnerContext,
RunnerContext,
} from '@programs/program-contract';
import type {
ProgramDiagnostic,
ProgramInput,
ProgramOptions,
ProgramProgress,
ProgramRunOutcome,
ProgramStep,
} from './program-input';
import type { WizardFlagSnapshot } from '@shared/wizard-flags';
/** The session's frameworkContext slot holding an orchestrated run's final task outcomes. */
export const TASK_OUTCOMES_KEY = 'orchestrator-task-outcomes';
/** Handed to the caller's capabilities when it supplied no signal. */
const NEVER_ABORTED = new AbortController().signal;
const MAX_DIAGNOSTICS = 10;
/** How long a run that has ended waits for a Decisions comparison call that is still in flight. */
const COMPARISON_GRACE_MS = 3_000;
type Failure = NonNullable<RunResult['failure']>;
/** What a person reads when no project was found and discovery could not check the whole repo. */
const INCOMPLETE_MESSAGE =
'Could not check the whole repo, and found no project to set up in the part that was checked.\n\n' +
"Run the wizard from your app's own directory.";
/** Fields that carry functions, class instances or the caller's store; everything else is data. */
const KEPT_BY_REFERENCE = [
'store',
'config',
'credentials',
] as const satisfies readonly (keyof ProgramInput)[];
/** Copy the caller's input, so a later caller write cannot reach the run or its hooks. */
function snapshotProgramInput(input: ProgramInput): ProgramInput {
const data: Partial<ProgramInput> = { ...input };
for (const key of KEPT_BY_REFERENCE) delete data[key];
return { ...input, ...structuredClone(data) };
}
/** One agent run of the invocation: a composed sub-run from `runSteps`, or the program's own. */
type PlannedRun = {
stepId: string; // the host's step: a `runSteps` key, or `run`
config: ProgramConfig; // the program whose agent runs
runStep?: ProgramRunStep; // the run's prep, or the program it composes
own: boolean; // the program's own run, not a composed one
};
/**
* Run a registered program: detection, readiness, login, the host's gates,
* then each agent run in order. Every write lands in `input.store`, and the
* store ends settled even when the call rejects.
*/
export async function runProgram(
programId: string,
callerInput: ProgramInput,
options: ProgramOptions = {},
): Promise<ProgramRunOutcome> {
try {
return await invokeProgram(programId, callerInput, options);
} catch (error) {
recordThrown(callerInput.store, error);
throw error;
}
}
/** The reason of a nothing-to-set-up stop that names none. */
const SHARED_NOTHING_REASON = 'not-applicable';
async function invokeProgram(
programId: string,
callerInput: ProgramInput,
options: ProgramOptions,
): Promise<ProgramRunOutcome> {
const input = snapshotProgramInput(callerInput);
const { store } = input;
analytics.setProgramTags();
// An unregistered id runs on input.config alone.
const config = {
...findProgramConfig(programId),
...input.config,
id: programId,
} as ProgramConfig;
const signal = options.signal ?? NEVER_ABORTED;
const runId = input.runId ?? randomUUID();
const progress = createProgress(options.onProgress);
const runResults: RunResult[] = [];
const artifacts: ProgramRunOutcome['artifacts'] = {};
const settle = (
outcome: RunOutcome,
failure?: Failure,
): ProgramRunOutcome => {
// A caller cancel through the signal is not a run failure, so no host shows a failure screen for it.
if (failure && signal.aborted) recordCancel(store, failure);
else if (failure) recordFailure(store, failure);
else recordSuccess(store);
// Nothing to set up is an ending, not a failure, so it is counted under its own name.
if (failure?.code === ErrorCodes.DetectNothingToSetUp && !signal.aborted) {
analytics.wizardCapture('nothing to set up', {
program_id: programId,
...failure.detail,
});
}
// A throwing progress handler is kept as a diagnostic, so log it.
const diagnostics = progress.diagnostics();
for (const diagnostic of diagnostics) {
logToFile(
`[agent-runner] progress diagnostic (${diagnostic.eventKind} run=${diagnostic.runId}): ${diagnostic.message}`,
);
}
// A discovery-only run that stopped with nothing to set up still carries the selection that says why.
const stoppedDiscovery =
input.discoveryOnly && failure?.code === ErrorCodes.DetectNothingToSetUp
? {
projectSelection: picksProject(config)
? buildProjectSelection(store.session, config, input.project)
: null,
// The run stopped before any model source was asked.
rankedBy: null,
nothingToSetUp: {
reason:
typeof failure.detail?.reason === 'string'
? failure.detail.reason
: SHARED_NOTHING_REASON,
message: failure.message,
},
}
: undefined;
return {
programId,
outcome,
runResults,
artifacts,
diagnostics,
...(failure && { failure }),
...(stoppedDiscovery && { discovery: stoppedDiscovery }),
};
};
const fail = (
message: string,
code: ErrorCode = ErrorCodes.InternalUnhandled,
) => settle(RunOutcome.Failed, { code, message });
const abort = (message: string) =>
settle(RunOutcome.Aborted, { code: ErrorCodes.AgentAbort, message });
const cancelled = () => abort('Run cancelled by the caller.');
/** A program's decided stop. Nothing to set up ends the run aborted, with its reason and outro; any other stop ends it as `otherwise`. */
const stopOn = (
stop: ProgramAbort,
otherwise: RunOutcome,
): ProgramRunOutcome =>
stop.code === ErrorCodes.DetectNothingToSetUp
? settle(RunOutcome.Aborted, {
code: stop.code,
message: stop.message,
detail: stop.detail,
outroData: stop.outroData,
})
: settle(otherwise, { code: stop.code, message: stop.message });
/**
* The stop of a run with no project to work in, or null when it has one.
* With `picked`, a pick the program cannot run in stops the run too.
* Discovery that could not check the whole repo fails the run instead,
* since the project to work in may be the part it missed.
*/
const nothingToWorkIn = (
projectSelection: ProjectSelection,
picked?: string,
): ProgramRunOutcome | null => {
const why = whyNothingToSetUp(
store.session,
config,
projectSelection,
picked,
);
if (!why) return null;
if (!projectSelection.isDiscoveryComplete) {
return fail(INCOMPLETE_MESSAGE, ErrorCodes.DetectIncomplete);
}
return stopOn(nothingToSetUp(why), RunOutcome.Aborted);
};
/** The stop of a run that stays where its program stopped it: in a repo with other projects the selection's reason, else the program's own. */
const stopWhereDetected = (
stop: ProgramAbort,
otherwise: RunOutcome,
): ProgramRunOutcome => {
if (stop.code === ErrorCodes.DetectNothingToSetUp && picksProject(config)) {
const projectSelection = buildProjectSelection(
store.session,
config,
input.project,
);
if (projectSelection.projects.length > 1) {
const nothing = nothingToWorkIn(projectSelection);
if (nothing) return nothing;
} else if (!projectSelection.isDiscoveryComplete) {
return fail(INCOMPLETE_MESSAGE, ErrorCodes.DetectIncomplete);
}
}
return stopOn(stop, otherwise);
};
/** What detection found that stops the run: a missing prerequisite is nothing to set up, anything else a failure. */
const settleDetection = (failure: Failure): ProgramRunOutcome =>
settle(
failure.code === ErrorCodes.DetectNothingToSetUp
? RunOutcome.Aborted
: RunOutcome.Failed,
failure,
);
if (signal.aborted) return cancelled();
if (!config.run)
return fail(`Program "${programId}" has no run configuration.`);
/** Await a caller capability; a caller abort wins over its answer. */
const park = <T>(work: Promise<T>): Promise<T> => parkOn(signal, work);
// Log lines and the spinner from program code arrive as the program's own run's progress.
const emit = (event: AgentProgress) => progress.deliver(runId, event);
const runner = storeRunner(store, emit);
const login = () =>
park(
logIn(programId, store, {
credentials: input.credentials,
provider: options.credentials,
signal,
completionScopeOptional: config.completionScopeOptional,
}),
);
/**
* The picker can still move the run: no caller named a project, and the
* selection has an eligible one other than the project the run started in.
* What stops the run in that first project then waits for the pick, so a
* workspace root with no framework of its own still reaches the picker.
*/
const mayMove = (): boolean =>
picksProject(config) &&
input.project === undefined &&
buildProjectSelection(store.session, config).projects.some(
(project) =>
project.eligible && project.path !== store.session.runProject,
);
/** What stopped the run in the project it started in, kept while the picker can move it. */
let stopped: (() => ProgramRunOutcome) | null = null;
try {
// A pair's project the store is not scoped to yet needs its own detection.
if (
!store.session.detectionComplete ||
(input.project !== undefined &&
input.project !== store.session.runProject)
) {
await detectProgram(
config,
store,
{
log: runner.log,
authenticate: async () => {
await login();
},
onProgress: emit,
} satisfies CiRunnerContext,
input.project,
);
}
} catch (error) {
// A decided stop ends the run cancelled, as main's wizardAbort({ code, message }) did.
if (error instanceof ProgramAbort) {
const stop = () => stopWhereDetected(error, RunOutcome.Aborted);
if (!mayMove()) return stop();
stopped = stop;
} else if (signal.aborted) return cancelled();
else {
// A crash keeps its error, so the host reports its stack.
const { code, message } = classifyRunFailure(error);
return settle(RunOutcome.Crashed, {
code,
message,
error: error instanceof Error ? error : new Error(message),
});
}
}
const blocked = stopped ? null : detectionFailure(config, store.session);
if (blocked) {
const stop = () => settleDetection(blocked);
if (!mayMove()) return stop();
stopped = stop;
}
// A program no model source ranks for has its answer before login: no project is eligible.
if (
!stopped &&
!input.discoveryOnly &&
picksProject(config) &&
!config.rankWith?.includes('decisions')
) {
const nothing = nothingToWorkIn(
buildProjectSelection(store.session, config, input.project),
);
if (nothing) return nothing;
}
// The run is one (program, project) pair: its skills resolve for its own project.
const pair = {
program: programId,
project: { path: store.session.runProject },
};
logToFile(
`[agent-runner] pair program=${pair.program} project=${
pair.project.path
} applies=${String(
config.appliesTo?.(getTraits(store.session, pair.project.path)) ?? true,
)}`,
);
// Started before the run resolves: an audit seeds the ledger from inside its recipe.
const installDir = store.session.installDir;
// A discovery-only run changes no file, and the ledger is one.
const ledgerFile = input.discoveryOnly ? undefined : config.auditLedgerFile;
let ledgerDir = installDir;
let ledger = ledgerFile
? startAuditLedgerWatcher(ledgerDir, ledgerFile, runner)
: null;
let ledgerReleased = false;
const releaseLedger = () => {
if (ledgerReleased || !ledgerFile) return;
ledgerReleased = true;
// Read a last write the watch debounce hasn't picked up before stopping.
ledger?.refresh();
ledger?.stop();
removeAuditLedger(ledgerDir, ledgerFile);
};
/** The ledger follows a run the pick moved: the old directory's is removed and the new one's is watched. */
const moveLedger = (dir: string): void => {
if (!ledgerFile) return;
releaseLedger();
ledgerDir = dir;
ledger = startAuditLedgerWatcher(ledgerDir, ledgerFile, runner);
ledgerReleased = false;
};
const unregisterLedger = ledger ? registerCleanup(releaseLedger) : undefined;
let plainSettings: { backedUp: boolean } | undefined;
/** A Decisions call that runs beside the agent run, for comparison only. */
let comparing: Promise<unknown> | undefined;
try {
let run: ProgramRun | undefined;
/** The run is resolved: tag the analytics, name the skill and report the start, once. */
const started = (resolved: ProgramRun, report: boolean): void => {
analytics.setProgramTags(resolved.analyticsTags);
store.setSkillId(resolved.skillId ?? resolved.integrationLabel);
if (!report) return;
analytics.wizardCapture('agent started', {
integration: resolved.integrationLabel,
program_id: programId,
skill_id: resolved.skillId ?? null,
});
};
// A discovery-only run starts no agent, so it resolves no run.
if (!stopped && !input.discoveryOnly) {
try {
run = await resolveRun(config, store, runner);
} catch (error) {
if (!(error instanceof ProgramAbort)) throw error;
const stop = () => stopWhereDetected(error, RunOutcome.Failed);
if (!mayMove()) return stop();
stopped = stop;
}
}
const plannedRuns = planRuns(config, options);
const outage = await checkReadiness(programId, config, store, {
workflow: options.workflow,
park,
signal,
emit,
});
if (outage) return settle(RunOutcome.Failed, outage);
// A run whose start waits for the pick reports it once the pick resolves it.
const reportedStart = run !== undefined;
if (run) started(run, true);
// Everything before the first agent run: a rejection fails the run, unless the caller aborted.
let credentials: ResolvedProgramCredentials;
let flags: WizardFlagSnapshot = {
flags: { ...input.wizardFlags },
payloads: { ...input.wizardFlagPayloads },
};
try {
// A plain run's settings are checked before login. A prepared or composed run checks its own after its prep.
if (
!input.discoveryOnly &&
plannedRuns.some((planned) => !planned.runStep)
) {
const settings = await checkSettingsConflicts(programId, installDir, {
workflow: options.workflow,
park,
signal,
});
if ('failure' in settings) {
return settle(RunOutcome.Failed, settings.failure);
}
plainSettings = settings;
}
credentials = await login();
// The run that follows a discovery-only one sends the report.
if (!input.discoveryOnly) reportDiscovery(store);
if (needsAiApproval(store.session, credentials)) {
if (!options.workflow) {
return fail(
'AI processing approval is required before this program can run.',
);
}
const approved = await park(
options.workflow.confirmStep(
{ kind: 'ai-approval', programId, installDir },
{ signal },
),
);
if (!approved) return abort('AI processing approval declined.');
}
if (!input.wizardFlags && options.featureFlags) {
flags = await park(options.featureFlags());
}
const gate = config.rolloutGate;
if (gate && flags.flags[gate.flagKey] !== 'true') {
return fail(gate.unavailableMessage, ErrorCodes.CliFlagUnavailable);
}
} catch (error) {
if (signal.aborted) return cancelled();
if (error instanceof ProgramAbort) return fail(error.message, error.code);
return fail(error instanceof Error ? error.message : String(error));
}
// Logged in, AI approved and flags known: Decisions answers for a program that ranks with it, when its flag allows.
const use = config.rankWith?.includes('decisions')
? decisionsUse(flags.flags)
: 'off';
// Every Decisions request reads this, so `off` stops them all.
store.setFrameworkContext(DECISIONS_USE_KEY, use);
const versionedSdkSkills =
flags.flags[WIZARD_VERSIONED_SDK_SKILLS_FLAG_KEY] === 'true';
store.setFrameworkContext(
VERSIONED_SDK_SKILLS_ENABLED_KEY,
versionedSdkSkills,
);
if (versionedSdkSkills) settleProjects(store.readyContext());
// The answers become traits only when the flag says so.
const decisionsAsTraits = use === 'traits';
/** Whether the Decisions ranking got an answer; undefined until it is asked. */
let ranked: boolean | undefined;
/** One Decisions call about the project the run works in now. */
const askDecisions = (rankProjects: boolean) =>
runDecisionsSource(decisionKeys(config, plannedRuns), {
session: store.session,
setFrameworkContext: (key, value) =>
store.setFrameworkContext(key, value),
programId,
...(decisionsAsTraits && { sink: store.readyContext() }),
rankProjects,
onRanked: (answered) => {
ranked = answered;
},
});
// A comparison waits for the pick, so it describes the project the run works in.
const compareAfterPick =
use !== 'off' && !decisionsAsTraits && picksProject(config);
if (use !== 'off' && !compareAfterPick) {
// Only a program that picks its project reads a ranking of them.
const asking = askDecisions(picksProject(config));
if (decisionsAsTraits) {
// The run waits for the answers it will read as traits.
try {
await park(asking);
} catch (error) {
if (signal.aborted) return cancelled();
logToFile(`[decisions] skipped: ${String(error)}`);
}
} else {
// Otherwise the call runs beside the agent run, and its answers reach only the log.
comparing = asking;
}
}
// A discovery-only run stops here: every source has answered, and nothing has run or changed.
if (input.discoveryOnly) {
const projectSelection = picksProject(config)
? buildProjectSelection(store.session, config, input.project)
: null;
// The selection reads the ranking, so one built without it would pass for the real one.
if (projectSelection && decisionsAsTraits && ranked !== true) {
return fail(
'Decisions could not rank the projects of this repo, so the project selection was not built. The log has the cause.',
ErrorCodes.DetectIncomplete,
);
}
const why =
projectSelection &&
whyNothingToSetUp(
store.session,
config,
projectSelection,
input.project,
);
// As in a run: a repo discovery could not check in full may hold the project it missed.
if (why && !projectSelection.isDiscoveryComplete) {
return fail(INCOMPLETE_MESSAGE, ErrorCodes.DetectIncomplete);
}
return {
programId,
outcome: RunOutcome.Success,
runResults,
artifacts,
diagnostics: progress.diagnostics(),
discovery: {
projectSelection,
rankedBy: projectSelection && decisionsAsTraits ? 'decisions' : null,
nothingToSetUp: why && {
reason: why.reason,
message: nothingToSetUp(why).message,
},
},
};
}
/** The pick the run made, for a program that picks its project. */
let projectPick: ProjectPick | null = null;
// One project per run: the host picks among the projects the program is offered.
if (picksProject(config)) {
const ciRunner = {
log: runner.log,
authenticate: async () => {
await login();
},
onProgress: emit,
} satisfies CiRunnerContext;
try {
const pick = await park(
pickProject(config, store, {
requestedProjectPath: input.project,
workflow: options.workflow,
signal,
}),
);
if (pick === null) return abort('Project selection cancelled.');
// Every source has answered: no project is eligible, or the pick is one the program cannot run in.
// A default is no one's choice, so only a person's or a caller's pick is read as one.
const nothing = nothingToWorkIn(
pick.projectSelection,
pick.pickedBy === 'default' ? undefined : pick.selected,
);
if (nothing) {
// No project was picked, so the report goes out without a selection.
reportDiscovery(store, null);
return nothing;
}
projectPick = pick;
const target = pick.selected;
// Nobody picked and the run leaves where it started: say where it works.
if (
pick.pickedBy === 'default' &&
target !== store.session.runProject
) {
runner.log.info(
`Working in ./${target}. Pass --project to work in another project.`,
);
}
// A pick elsewhere moves the run.
if (target !== store.session.runProject) {
// The settings were checked for the directory the run started in.
if (plainSettings?.backedUp) restoreClaudeSettings(installDir);
plainSettings = undefined;
// What stopped the run where it was first detected no longer applies.
stopped = null;
await detectProgram(config, store, ciRunner, target);
moveLedger(store.session.installDir);
const unmet = detectionFailure(config, store.session);
if (unmet) return settleDetection(unmet);
run = await resolveRun(config, store, runner);
started(run, !reportedStart);
pair.project.path = target;
// The questions were asked of the project the run started in; the pair's project gets its own answers.
if (decisionsAsTraits) await park(askDecisions(false));
}
} catch (error) {
if (signal.aborted) return cancelled();
if (error instanceof ProgramAbort) {
return stopOn(error, RunOutcome.Failed);
}
throw error;
}
}
// The project is settled and its detection has run: the report and the run's row take the discovery data.
reportDiscovery(store, projectPick);
// The run stayed in the project it started in, so what stopped it there stands.
if (stopped) return stopped();
if (!run) return fail(`Program "${programId}" resolved no run.`);
const ownRunDefinition = run;
// The pick is settled, so the comparison runs beside the agent run for the project it works in.
if (compareAfterPick) comparing = askDecisions(false);
// Every rotation of this login, before or during a run, lands in the store.
configureOAuthSession(credentials.posthog, {
rotate: (held) => rotateCredentials(held, store.session.baseUrl),
onRefreshed: (refreshed) => {
const current = store.session.credentials;
// A refresh replaces only the token fields; the login keeps its host.
store.setAccessToken(
current
? {
...current,
accessToken: refreshed.accessToken,
refreshToken: refreshed.refreshToken,
expiresAt: refreshed.expiresAt,
}
: refreshed,
);
},
});
/** One agent run in its own directory; a settled outcome when it can't start. */
const runOne = async (
planned: PlannedRun,
ownRun: AgentRunDefinition | undefined,
checked: { backedUp: boolean } | undefined,
): Promise<RunResult | ProgramRunOutcome> => {
// A prepared run works on its own copy of the session; its writes don't leak into later runs.
const scoped = planned.runStep
? await scopeSession(planned.runStep, store.session, runner)
: null;
if (
scoped?.detectedFrameworkLabel &&
scoped.detectedFrameworkLabel !== store.session.detectedFrameworkLabel
) {
store.setDetectedFramework(scoped.detectedFrameworkLabel);
}
const session = (): WizardSession => scoped ?? store.session;
const sdkGap = planned.config.sdkFeature
? sdkFeatureGaps(session(), [planned.config.sdkFeature]).find(
(gap) => gap.blocking,
)
: undefined;
if (sdkGap) {
return settle(RunOutcome.Failed, {
code: ErrorCodes.DetectSdkTooOld,
message: sdkGap.message,
});
}
const runDir = session().installDir;
// A run with prep resolves on the session its prep wrote to, so it reads what the prep found.
const agentRun =
ownRun && !(scoped && typeof planned.config.run === 'function')
? ownRun
: await resolveRun(planned.config, store, runner, scoped);
if (!ownRun) {
analytics.wizardCapture('agent started', {
integration: agentRun.integrationLabel,
program_id: planned.config.id,
skill_id: agentRun.skillId ?? null,
});
}
const settings =
checked ??
(await checkSettingsConflicts(programId, runDir, {
workflow: options.workflow,
park,
signal,
}));
if ('failure' in settings) {
return settle(RunOutcome.Failed, settings.failure);
}
// The skills a run installs are for its agent only; remove them when it ends, however it ends.
const skillsBefore = listSkillFolders(runDir);
const removeSkills = () => removeRunSkills(runDir, skillsBefore);
const unregisterSkills = registerCleanup(removeSkills);
try {
// Not parked: a rotation spends the old refresh token, so the new one is kept before a cancel returns.
const posthog = await currentCredentials(credentials.posthog);
if (signal.aborted) return cancelled();
if (planned.own) {
artifacts.reportFile = path.resolve(runDir, agentRun.reportFile);
}
const agentRunId = planned.own ? runId : randomUUID();
const observer = progress.beginRun(
agentRunId,
planned.own ? undefined : planned.stepId,
);
const current = session();
const result = await runAgent(
{
programId: planned.config.id,
run: agentRun,
composed: planned.own ? input.composed ?? false : true,
// The agent resolves CLI, then flag, then this binding, and reports the pick.
routing: {
binding: planned.config.binding ?? DEFAULT_BINDING,
overrides: {
harness: current.harness,
sequence: current.sequence,
model: current.model,
},
},
skillsBaseUrl: getSkillsBaseUrl(),
wizardFlags: { ...flags.flags },
wizardFlagPayloads: { ...flags.payloads },
allowedTools: planned.config.allowedTools,
disallowedTools: planned.config.disallowedTools,
posthogTools: planned.config.posthogTools,
handoffNotebook:
agentRun.handoffNotebook ?? planned.config.handoffNotebook,
agentFlow: planned.config.agentFlow,
accountOwnerContext: planned.config.accountOwnerContext,
agentPrompts: planned.config.agentPrompts,
excludedTaskTypes: planned.config.excludedTaskTypes
? (runFlags) =>
planned.config.excludedTaskTypes!(runFlags, session())
: undefined,
seedTasks: planned.config.seedTasks
? () => planned.config.seedTasks!(session())
: undefined,
matchKeys: () => toMatchKeys(getTraits(session())),
traitKeys: () => toTraitKeys(getTraits(session())),
reportDiscoveryTelemetry: () => maySendDiscovery(session()),
projectFacts:
planned.config.decisions || planned.config.detectedFacts
? () => [
...(planned.config.decisions
? questionFacts(session(), planned.config.decisions)
: []),
...(planned.config.detectedFacts?.(
flags.flags,
session(),
) ?? []),
]
: undefined,
hooks: sessionHooks(agentRun, session, (outcomes) => {
if (scoped) scoped.frameworkContext[TASK_OUTCOMES_KEY] = outcomes;
else store.setFrameworkContext(TASK_OUTCOMES_KEY, outcomes);
}),
},
{
installDir: runDir,
credentials: posthog,
project: credentials.project,
apiUser: credentials.apiUser,
skillId: agentRun.skillId ?? agentRun.integrationLabel,
integration: current.integration,
frameworkDocsUrl: frameworkDocsUrl(current),
flags: runFlags(current),
host: {
projectId: current.projectId,
apiKey: current.apiKey,
baseUrl: current.baseUrl,
region: current.region,
},
},
{
interaction: options.interaction,
onProgress: (event) =>
observer.onEvent(event, () => applyAgentProgress(store, event)),
signal: options.signal,
},
);
observer.finish();
return result;
} finally {
// The run neutralized its directory's settings; put them back whatever happened.
if (settings.backedUp) restoreClaudeSettings(runDir);
unregisterSkills();
removeSkills();
}
};
for (const planned of plannedRuns) {
const step: Extract<ProgramStep, { kind: 'run' }> = {
kind: 'run',
stepId: planned.stepId,
programId: planned.config.id,
};
let result: RunResult | ProgramRunOutcome;
try {
if (options.workflow) {
const go = await park(options.workflow.confirmStep(step, { signal }));
if (!go) continue;
}
result = await runOne(
planned,
planned.own ? ownRunDefinition : undefined,
planned.runStep ? undefined : plainSettings,
);
} catch (error) {
if (signal.aborted) return cancelled();
if (error instanceof ProgramAbort) {
return stopOn(error, RunOutcome.Failed);
}
throw error;
}
if ('programId' in result) return result;
runResults.push(result);
options.workflow?.finishStep?.(step, result);
if (result.outcome !== RunOutcome.Success) {
return settle(result.outcome, result.failure);
}
}
return settle(RunOutcome.Success);
} finally {
// A run that ends before the comparison call does gives it a moment to log.
if (comparing) {
await Promise.race([
comparing,
new Promise((resolve) =>
setTimeout(resolve, COMPARISON_GRACE_MS).unref(),
),
]);
}
// A plain run's settings were neutralized before login; put them back if the run never started.
if (plainSettings?.backedUp) restoreClaudeSettings(installDir);
releaseLedger();
unregisterLedger?.();
}
}
/**
* The project the run works in. Asks the host when there is a choice. A run
* with no host to ask takes the selection's default. Reports the list and the
* pick, and returns the pick with the selection it was made from. Null when
* the host declined.
*/
async function pickProject(
config: ProgramConfig,
store: SessionStore,
context: {
requestedProjectPath?: string;
workflow?: ProgramOptions['workflow'];
signal: AbortSignal;
},
): Promise<ProjectPick | null> {
const { requestedProjectPath, workflow, signal } = context;
const projectSelection: ProjectSelection = buildProjectSelection(
store.session,
config,
requestedProjectPath,
);
let picked = projectSelection.selectedProjectPath;
let pickedBy: PickedBy =
requestedProjectPath === undefined ? 'default' : 'caller';
const asks =
workflow !== undefined &&
askUserToSelectProject(
store.session,
config,
projectSelection,
requestedProjectPath,
);
if (asks) {
const go = await workflow.confirmStep(
{
kind: 'project-selection',
programId: config.id,
installDir: store.session.installDir,
projectSelection,
selectProject: (projectPath) => {
picked = projectPath;
pickedBy = 'person';
},
},
{ signal },
);
if (!go) return null;
}
reportProjectsDiscovered(store.session, projectSelection, config.id);
reportProjectsSelected(
store.session,
projectSelection,
picked,
config.id,
pickedBy,
);
return {
programId: config.id,
projectSelection,
selected: picked,
pickedBy,
};
}
/** The program's own run, and before it every composed sub-run a host workflow can confirm. */
function planRuns(
config: ProgramConfig,
options: ProgramOptions,
): PlannedRun[] {
const own: PlannedRun = { stepId: 'run', config, own: true };
// Run steps are the host's flow: with no workflow to confirm them, only the program's own run runs.
if (!options.workflow) return [own];
const composed: PlannedRun[] = [];
for (const [stepId, runStep] of Object.entries(config.runSteps ?? {})) {
if (runStep.runProgramId) {
composed.push({
stepId,
config: getProgramConfig(runStep.runProgramId),
runStep,
own: false,
});
} else {
own.stepId = stepId;
own.runStep = runStep;
}
}
return [...composed, own];
}