@artieeez/cf-sdk 0.0.0-stage → 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/README.md +96 -2
- package/dist/fragments/approval.d.ts +83 -0
- package/dist/fragments/approval.d.ts.map +1 -0
- package/dist/fragments/approval.js +170 -0
- package/dist/fragments/approval.js.map +1 -0
- package/dist/fragments/common.d.ts +65 -0
- package/dist/fragments/common.d.ts.map +1 -0
- package/dist/fragments/common.js +138 -0
- package/dist/fragments/common.js.map +1 -0
- package/dist/fragments/deliver.d.ts +178 -0
- package/dist/fragments/deliver.d.ts.map +1 -0
- package/dist/fragments/deliver.js +232 -0
- package/dist/fragments/deliver.js.map +1 -0
- package/dist/fragments/index.d.ts +6 -0
- package/dist/fragments/index.d.ts.map +1 -0
- package/dist/fragments/index.js +6 -0
- package/dist/fragments/index.js.map +1 -0
- package/dist/fragments/validated.d.ts +64 -0
- package/dist/fragments/validated.d.ts.map +1 -0
- package/dist/fragments/validated.js +95 -0
- package/dist/fragments/validated.js.map +1 -0
- package/dist/fragments/verifier-round.d.ts +128 -0
- package/dist/fragments/verifier-round.d.ts.map +1 -0
- package/dist/fragments/verifier-round.js +295 -0
- package/dist/fragments/verifier-round.js.map +1 -0
- package/dist/index.d.ts +597 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +244 -0
- package/dist/index.js.map +1 -0
- package/dist/kit.d.ts +44 -0
- package/dist/kit.d.ts.map +1 -0
- package/dist/kit.js +32 -0
- package/dist/kit.js.map +1 -0
- package/dist/plugin.d.ts +126 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +15 -0
- package/dist/plugin.js.map +1 -0
- package/dist/prompt.d.ts +10 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +34 -0
- package/dist/prompt.js.map +1 -0
- package/dist/runner.d.ts +88 -0
- package/dist/runner.d.ts.map +1 -0
- package/dist/runner.js +224 -0
- package/dist/runner.js.map +1 -0
- package/package.json +79 -3
- package/src/fragments/approval.ts +267 -0
- package/src/fragments/common.ts +195 -0
- package/src/fragments/deliver.ts +447 -0
- package/src/fragments/index.ts +57 -0
- package/src/fragments/validated.ts +217 -0
- package/src/fragments/verifier-round.ts +442 -0
- package/src/index.ts +890 -0
- package/src/kit.ts +137 -0
- package/src/plugin.ts +128 -0
- package/src/prompt.ts +29 -0
- package/src/runner.ts +278 -0
package/src/kit.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import {
|
|
3
|
+
approval,
|
|
4
|
+
deliver,
|
|
5
|
+
validated,
|
|
6
|
+
verifierRound,
|
|
7
|
+
type ApprovalFragment,
|
|
8
|
+
type ApprovalOptions,
|
|
9
|
+
type DefaultValidateOutcome,
|
|
10
|
+
type DeliverFragment,
|
|
11
|
+
type DeliverOptions,
|
|
12
|
+
type ValidatedFragment,
|
|
13
|
+
type ValidatedOptions,
|
|
14
|
+
type VerifierRoundFragment,
|
|
15
|
+
type VerifierRoundOptions,
|
|
16
|
+
} from './fragments/index.ts';
|
|
17
|
+
import {
|
|
18
|
+
defineWorkflow,
|
|
19
|
+
human,
|
|
20
|
+
map,
|
|
21
|
+
parallel,
|
|
22
|
+
wait,
|
|
23
|
+
type ApisOf,
|
|
24
|
+
type EventsOf,
|
|
25
|
+
type Hooks,
|
|
26
|
+
type HumanStep,
|
|
27
|
+
type Ref,
|
|
28
|
+
type SettingSpec,
|
|
29
|
+
type SettingsOf,
|
|
30
|
+
type TaskStep,
|
|
31
|
+
type WorkflowDefinition,
|
|
32
|
+
} from './index.ts';
|
|
33
|
+
import type { PluginSlot } from './plugin.ts';
|
|
34
|
+
|
|
35
|
+
/** What a workflow declares once and every step and hook is typed with (AD-030). */
|
|
36
|
+
export interface KitDecl<
|
|
37
|
+
S extends z.ZodType,
|
|
38
|
+
PS extends Record<string, PluginSlot>,
|
|
39
|
+
ST extends Record<string, SettingSpec>,
|
|
40
|
+
EV extends Record<string, z.ZodType>,
|
|
41
|
+
> {
|
|
42
|
+
input: S;
|
|
43
|
+
plugins?: PS;
|
|
44
|
+
settings?: ST;
|
|
45
|
+
events?: EV;
|
|
46
|
+
/** env names the workflow's code reads, hidden from `ctx.exec` children (AD-049) */
|
|
47
|
+
secrets?: readonly string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The definition `kit.define` takes: everything but what the kit declared. */
|
|
51
|
+
export type KitDefinition<
|
|
52
|
+
S extends z.ZodType,
|
|
53
|
+
PS extends Record<string, PluginSlot>,
|
|
54
|
+
ST extends Record<string, SettingSpec>,
|
|
55
|
+
EV extends Record<string, z.ZodType>,
|
|
56
|
+
> = Omit<WorkflowDefinition<S, PS, ST, EV>, 'input' | 'plugins' | 'settings' | 'events' | 'secrets'>;
|
|
57
|
+
|
|
58
|
+
export interface WorkflowKit<
|
|
59
|
+
S extends z.ZodType,
|
|
60
|
+
PS extends Record<string, PluginSlot>,
|
|
61
|
+
ST extends Record<string, SettingSpec>,
|
|
62
|
+
EV extends Record<string, z.ZodType>,
|
|
63
|
+
> {
|
|
64
|
+
/** a task whose `ctx` has this workflow's input, plugins, settings and events; outcomes inferred */
|
|
65
|
+
task<const O extends string, Sch extends z.ZodType | undefined = undefined>(
|
|
66
|
+
step: Omit<TaskStep<z.infer<S>, O, ApisOf<PS>, Sch, SettingsOf<ST>, EventsOf<EV>>, 'kind'>,
|
|
67
|
+
): TaskStep<z.infer<S>, O, ApisOf<PS>, Sch, SettingsOf<ST>, EventsOf<EV>>;
|
|
68
|
+
human<const O extends string, F extends z.ZodObject | Ref | undefined = undefined>(
|
|
69
|
+
step: Omit<HumanStep<O, F>, 'kind'>,
|
|
70
|
+
): HumanStep<O, F>;
|
|
71
|
+
wait: typeof wait;
|
|
72
|
+
map: typeof map;
|
|
73
|
+
parallel: typeof parallel;
|
|
74
|
+
/** agent + validation script loop bound to this kit's input, plugins, settings and events (AD-065) */
|
|
75
|
+
validated<
|
|
76
|
+
const Id extends string,
|
|
77
|
+
const O extends string,
|
|
78
|
+
const V extends O = DefaultValidateOutcome<O>,
|
|
79
|
+
Sch extends z.ZodType | undefined = undefined,
|
|
80
|
+
>(
|
|
81
|
+
id: Id,
|
|
82
|
+
opts: ValidatedOptions<z.infer<S>, O, V, ApisOf<PS>, Sch, SettingsOf<ST>, EventsOf<EV>>,
|
|
83
|
+
): ValidatedFragment<Id, z.infer<S>, O, ApisOf<PS>, Sch, SettingsOf<ST>, EventsOf<EV>>;
|
|
84
|
+
/** hash-bound human approval + record task bound to this kit (AD-065) */
|
|
85
|
+
approval<const Id extends string>(
|
|
86
|
+
id: Id,
|
|
87
|
+
opts: ApprovalOptions<z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>,
|
|
88
|
+
): ApprovalFragment<Id, z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>;
|
|
89
|
+
/** proofs -> review -> findings -> one fix pass -> round 2 -> escalate -> gate (AD-065) */
|
|
90
|
+
verifierRound<const Id extends string = 'verify'>(
|
|
91
|
+
opts: VerifierRoundOptions<Id, z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>,
|
|
92
|
+
): VerifierRoundFragment<Id, z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>;
|
|
93
|
+
/** approve-push -> push/PR/comments -> optional CI watch bound to this kit (AD-065) */
|
|
94
|
+
deliver<const Id extends string = 'deliver'>(
|
|
95
|
+
opts: DeliverOptions<Id, z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>,
|
|
96
|
+
): DeliverFragment<Id, z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>;
|
|
97
|
+
/** hooks typed like the kit's tasks, for a `hooks.ts` of their own */
|
|
98
|
+
hooks(h: Hooks<z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>): Hooks<z.infer<S>, ApisOf<PS>, SettingsOf<ST>, EventsOf<EV>>;
|
|
99
|
+
/** `defineWorkflow` with the kit's input, plugins, settings and events filled in */
|
|
100
|
+
define(def: KitDefinition<S, PS, ST, EV>): WorkflowDefinition<S, PS, ST, EV>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Binds a workflow's input, plugins, settings and events once, so its steps and hooks are typed
|
|
105
|
+
* without type arguments or casts:
|
|
106
|
+
*
|
|
107
|
+
* export const kit = workflowKit({ input: Input, plugins: { tracker: linear.slot() } });
|
|
108
|
+
* export const { task, human } = kit;
|
|
109
|
+
*/
|
|
110
|
+
export function workflowKit<
|
|
111
|
+
S extends z.ZodType,
|
|
112
|
+
PS extends Record<string, PluginSlot> = Record<never, never>,
|
|
113
|
+
ST extends Record<string, SettingSpec> = Record<never, never>,
|
|
114
|
+
EV extends Record<string, z.ZodType> = Record<never, never>,
|
|
115
|
+
>(decl: KitDecl<S, PS, ST, EV>): WorkflowKit<S, PS, ST, EV> {
|
|
116
|
+
return {
|
|
117
|
+
task: (step) => ({ kind: 'task', ...step }),
|
|
118
|
+
human,
|
|
119
|
+
wait,
|
|
120
|
+
map,
|
|
121
|
+
parallel,
|
|
122
|
+
validated: (id, opts) => validated(id, opts),
|
|
123
|
+
approval: (id, opts) => approval(id, opts),
|
|
124
|
+
verifierRound: (opts) => verifierRound(opts),
|
|
125
|
+
deliver: (opts) => deliver(opts),
|
|
126
|
+
hooks: (h) => h,
|
|
127
|
+
define: (def) =>
|
|
128
|
+
defineWorkflow<S, PS, ST, EV>({
|
|
129
|
+
...def,
|
|
130
|
+
input: decl.input,
|
|
131
|
+
...(decl.plugins !== undefined ? { plugins: decl.plugins } : {}),
|
|
132
|
+
...(decl.settings !== undefined ? { settings: decl.settings } : {}),
|
|
133
|
+
...(decl.events !== undefined ? { events: decl.events } : {}),
|
|
134
|
+
...(decl.secrets !== undefined ? { secrets: decl.secrets } : {}),
|
|
135
|
+
}),
|
|
136
|
+
};
|
|
137
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { ArtifactRef, RunLink, SettingType } from '@artieeez/cf-core';
|
|
3
|
+
|
|
4
|
+
/** A webhook as the plugin host hands it to a plugin: the raw body, its parsed JSON and the headers (lowercase). */
|
|
5
|
+
export interface IngressRequest {
|
|
6
|
+
headers: Record<string, string | undefined>;
|
|
7
|
+
rawBody: string;
|
|
8
|
+
body: unknown;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** One typed event a webhook becomes; `data` is checked against the plugin's `events` schema. */
|
|
12
|
+
export interface NormalizedEvent {
|
|
13
|
+
type: string;
|
|
14
|
+
data: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The run's artifacts as an action sees them (linear-issue-attachments door 1): only the calling
|
|
19
|
+
* unit's run. `put` stores the bytes and appends `artifact.created` for the unit; it throws on a bad
|
|
20
|
+
* path, a bad media type or more bytes than the server stores. `get` takes a path (the run's latest
|
|
21
|
+
* artifact there) or `{ sha256 }` (a blob the run stored); `null` when the run has none.
|
|
22
|
+
*/
|
|
23
|
+
export interface PluginArtifacts {
|
|
24
|
+
put(path: string, bytes: Uint8Array, opts?: { mediaType?: string }): Promise<ArtifactRef>;
|
|
25
|
+
get(ref: string | { sha256: string }): Promise<{ ref: ArtifactRef; bytes: Uint8Array } | null>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What a plugin's code is given to reach its system: the instance's `config`, its secrets and `fetch`. */
|
|
29
|
+
export interface PluginContext<C> {
|
|
30
|
+
config: C;
|
|
31
|
+
secrets: Record<string, string>;
|
|
32
|
+
fetch: typeof fetch;
|
|
33
|
+
/**
|
|
34
|
+
* present only while the server runs an action for a leased unit; `check`, `checkSettings` and a
|
|
35
|
+
* worker building actions to learn their names get none
|
|
36
|
+
*/
|
|
37
|
+
artifacts?: PluginArtifacts;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A setting value to check against the bound instance (linear-plugin door 7). */
|
|
41
|
+
export interface SettingValue {
|
|
42
|
+
name: string;
|
|
43
|
+
type: SettingType;
|
|
44
|
+
value: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What a check answers (health-ready door 3): `ok`, or a reason; `fatal` when no retry can fix it
|
|
49
|
+
* (a credential the system rejects). A check that throws counts as `{ ok: false, reason }`.
|
|
50
|
+
*/
|
|
51
|
+
export type CheckResult = { ok: true } | { ok: false; reason: string; fatal?: boolean };
|
|
52
|
+
|
|
53
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- an action takes and returns what its plugin says
|
|
54
|
+
export type PluginActions = Record<string, (...args: any[]) => Promise<unknown>>;
|
|
55
|
+
|
|
56
|
+
/** A plugin (linear-plugin door 9): ingress turns webhooks into typed events, actions reach the system. */
|
|
57
|
+
export interface PluginDefinition<C = unknown, A extends PluginActions = PluginActions> {
|
|
58
|
+
/** namespace of its events and its manifest name, e.g. `linear` */
|
|
59
|
+
id: string;
|
|
60
|
+
version: string;
|
|
61
|
+
/** an instance's config; the default instance reads it from env by `configEnv` (AD-089) */
|
|
62
|
+
config: z.ZodType<C>;
|
|
63
|
+
/**
|
|
64
|
+
* config key → env name the server reads it from (AD-089): when any is set, the server makes one
|
|
65
|
+
* instance of the plugin from them, named `CF_<PLUGIN>_INSTANCE` (default its id). A value is a
|
|
66
|
+
* string; the schema turns it into the key's type, e.g. a comma list into an array. None: no env instance.
|
|
67
|
+
*/
|
|
68
|
+
configEnv?: Readonly<Record<string, string>>;
|
|
69
|
+
/** env names the server reads for this plugin: its webhook secret and its actions' key (AD-047); workers read none */
|
|
70
|
+
secrets: readonly string[];
|
|
71
|
+
/** contracts of the events `normalize` returns */
|
|
72
|
+
events: Record<string, z.ZodType>;
|
|
73
|
+
ingress: {
|
|
74
|
+
/** whether the request is signed by the system */
|
|
75
|
+
verify(req: IngressRequest, ctx: { secrets: Record<string, string>; config: C }): boolean;
|
|
76
|
+
/** the time the system says it sent the request (ms), for the replay window; none skips the check */
|
|
77
|
+
timestamp?(req: IngressRequest): number | undefined;
|
|
78
|
+
/** 0..n typed events; `[]` for a webhook nobody consumes */
|
|
79
|
+
normalize(req: IngressRequest, ctx: { config: C }): NormalizedEvent[];
|
|
80
|
+
/** the delivery id the system repeats on a retry */
|
|
81
|
+
dedupKey(req: IngressRequest): string | undefined;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* The curated actions the server runs for workers (AD-048). Building them must not reach the
|
|
85
|
+
* system: the worker builds them with no secret only to learn their names.
|
|
86
|
+
*/
|
|
87
|
+
actions(ctx: PluginContext<C>): A;
|
|
88
|
+
/** problems with setting values in the bound instance, e.g. a state the team does not have (door 7) */
|
|
89
|
+
checkSettings?(ctx: PluginContext<C>, values: SettingValue[]): Promise<string[]>;
|
|
90
|
+
/**
|
|
91
|
+
* whether the server's credential works and the system answers; the server runs it (AD-054)
|
|
92
|
+
* and aborts `signal` past `CF_CHECK_TIMEOUT_MS`: pass it to the requests the check makes
|
|
93
|
+
*/
|
|
94
|
+
check?(ctx: PluginContext<C> & { signal: AbortSignal }): Promise<CheckResult>;
|
|
95
|
+
/**
|
|
96
|
+
* What one of its events says about the runs it reaches (AD-085): the title of a run it starts,
|
|
97
|
+
* when the trigger reads none, and links the server adds to every active run the event reaches,
|
|
98
|
+
* once per url. Pure and synchronous; a throw counts as nothing.
|
|
99
|
+
*/
|
|
100
|
+
describe?(event: NormalizedEvent): RunDescription | undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A plugin's description of a run from one event (AD-085). */
|
|
104
|
+
export interface RunDescription {
|
|
105
|
+
title?: string;
|
|
106
|
+
links?: RunLink[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Checks the shape and returns the plugin as given. */
|
|
110
|
+
export function definePlugin<C, A extends PluginActions>(def: PluginDefinition<C, A>): PluginDefinition<C, A> {
|
|
111
|
+
if (!/^[a-z][a-z0-9-]*$/.test(def.id)) throw new Error(`plugin id "${def.id}" must be a lowercase slug`);
|
|
112
|
+
for (const type of Object.keys(def.events)) {
|
|
113
|
+
if (!type.startsWith(`${def.id}.`)) throw new Error(`plugin ${def.id}: event "${type}" is outside its namespace`);
|
|
114
|
+
}
|
|
115
|
+
return def;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A workflow's need for one connection of a plugin: the factory binds it to an instance. */
|
|
119
|
+
export interface PluginSlot<A extends PluginActions = PluginActions> {
|
|
120
|
+
kind: 'slot';
|
|
121
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the slot only needs the plugin's code
|
|
122
|
+
plugin: PluginDefinition<any, A>;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the slot only needs the plugin's code
|
|
126
|
+
export function slot<A extends PluginActions>(plugin: PluginDefinition<any, A>): PluginSlot<A> {
|
|
127
|
+
return { kind: 'slot', plugin };
|
|
128
|
+
}
|
package/src/prompt.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const PLACEHOLDER = /\{\{([A-Za-z0-9_]+)\}\}/g;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Loads a prompt template (AD-030): reads `<dir>/<file>` once, now, and returns a render function
|
|
8
|
+
* that replaces each `{{name}}` with `vars.name` verbatim and drops the file's final newline.
|
|
9
|
+
* Rendering throws for a variable the file names but `vars` lacks, and for one it does not name.
|
|
10
|
+
*
|
|
11
|
+
* const greets = prompt(import.meta.dirname, '../prompts/greets.md');
|
|
12
|
+
* greets({ name: 'Ada' });
|
|
13
|
+
*/
|
|
14
|
+
export function prompt(dir: string, file: string): (vars: Record<string, string>) => string {
|
|
15
|
+
const path = resolve(dir, file);
|
|
16
|
+
let text: string;
|
|
17
|
+
try {
|
|
18
|
+
text = readFileSync(path, 'utf8');
|
|
19
|
+
} catch (err) {
|
|
20
|
+
throw new Error(`prompt ${file}: cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
21
|
+
}
|
|
22
|
+
if (text.endsWith('\n')) text = text.slice(0, -1);
|
|
23
|
+
const names = new Set([...text.matchAll(PLACEHOLDER)].map((m) => m[1]!));
|
|
24
|
+
return (vars) => {
|
|
25
|
+
for (const name of names) if (!Object.hasOwn(vars, name)) throw new Error(`prompt ${file}: missing ${name}`);
|
|
26
|
+
for (const name of Object.keys(vars)) if (!names.has(name)) throw new Error(`prompt ${file}: unused ${name}`);
|
|
27
|
+
return text.replace(PLACEHOLDER, (_m, name: string) => vars[name]!);
|
|
28
|
+
};
|
|
29
|
+
}
|
package/src/runner.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import type { AgentContext, AgentRequest, AgentResult, AgentUsage } from './index.ts';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* What every CLI agent runner shares (`@artieeez/cf-runner-claude-code`, `-agy`, `-pi`): the child's env,
|
|
8
|
+
* the process with its timeout and stop, JSONL framing, and the attempt loop with the output
|
|
9
|
+
* contract, the facts check, one retry and the transcript. A runner keeps its argv and how it
|
|
10
|
+
* reads its CLI's stream.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Worker env names every agent gets when they are set; anything else needs `envPassthrough`. */
|
|
14
|
+
export const ENV_ALLOWLIST = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TERM', 'TMPDIR', 'USER', 'SHELL'] as const;
|
|
15
|
+
|
|
16
|
+
/** How long a child has between SIGTERM and SIGKILL. */
|
|
17
|
+
export const KILL_GRACE_MS = 5000;
|
|
18
|
+
|
|
19
|
+
/** A failed tool result whose text matches this was refused by the agent's permissions. */
|
|
20
|
+
export const DENIED = /denied|not allowed|permission/i;
|
|
21
|
+
|
|
22
|
+
export const ZERO_USAGE: AgentUsage = { inputTokens: 0, outputTokens: 0 };
|
|
23
|
+
|
|
24
|
+
type JsonSchema = Record<string, unknown>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* JSON Schema (draft-07) of the output contract, without `$schema`. Its root is always
|
|
28
|
+
* `type: "object"`: CLIs pass it on as a tool's `input_schema`, which the Claude API refuses
|
|
29
|
+
* without `type` or with `oneOf`/`anyOf` at the top. A union of objects (`z.discriminatedUnion`)
|
|
30
|
+
* is merged into one object (every property, required only where all branches require it); the
|
|
31
|
+
* runner's `safeParse` against the zod contract still enforces the exact union.
|
|
32
|
+
*/
|
|
33
|
+
export function outputSchema(output: z.ZodType): JsonSchema {
|
|
34
|
+
const { $schema: _ignored, ...schema } = z.toJSONSchema(output, { target: 'draft-7', io: 'output' }) as JsonSchema;
|
|
35
|
+
if (schema['type'] === 'object') return schema;
|
|
36
|
+
const branches = (schema['oneOf'] ?? schema['anyOf']) as JsonSchema[] | undefined;
|
|
37
|
+
if (branches === undefined || !branches.every((b) => b['type'] === 'object')) {
|
|
38
|
+
throw new Error('an agent output contract must be a zod object, or a union of objects');
|
|
39
|
+
}
|
|
40
|
+
const { oneOf: _o, anyOf: _a, ...rest } = schema;
|
|
41
|
+
const variants = new Map<string, JsonSchema[]>();
|
|
42
|
+
for (const b of branches) {
|
|
43
|
+
for (const [key, s] of Object.entries((b['properties'] ?? {}) as Record<string, JsonSchema>)) {
|
|
44
|
+
const seen = variants.get(key) ?? [];
|
|
45
|
+
if (!seen.some((x) => JSON.stringify(x) === JSON.stringify(s))) seen.push(s);
|
|
46
|
+
variants.set(key, seen);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const properties = Object.fromEntries([...variants].map(([k, v]) => [k, v.length === 1 ? v[0] : { anyOf: v }]));
|
|
50
|
+
const required = [...variants.keys()].filter((k) =>
|
|
51
|
+
branches.every((b) => ((b['required'] ?? []) as string[]).includes(k)),
|
|
52
|
+
);
|
|
53
|
+
const closed = branches.every((b) => b['additionalProperties'] === false);
|
|
54
|
+
return {
|
|
55
|
+
...rest,
|
|
56
|
+
type: 'object',
|
|
57
|
+
properties,
|
|
58
|
+
...(required.length > 0 ? { required } : {}),
|
|
59
|
+
...(closed ? { additionalProperties: false } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The child's whole env: the `allowlist` and the request's passthrough names that are set, then `fixed`. */
|
|
64
|
+
export function pickEnv(
|
|
65
|
+
request: Pick<AgentRequest<unknown>, 'envPassthrough'>,
|
|
66
|
+
env: NodeJS.ProcessEnv,
|
|
67
|
+
allowlist: readonly string[] = ENV_ALLOWLIST,
|
|
68
|
+
fixed: Record<string, string> = {},
|
|
69
|
+
): Record<string, string> {
|
|
70
|
+
const out: Record<string, string> = {};
|
|
71
|
+
for (const name of [...allowlist, ...(request.envPassthrough ?? [])]) {
|
|
72
|
+
const value = env[name];
|
|
73
|
+
if (value !== undefined) out[name] = value;
|
|
74
|
+
}
|
|
75
|
+
return { ...out, ...fixed };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The text of a message's `content`: a string, or the `text` of each block joined by newlines. */
|
|
79
|
+
export function contentText(content: unknown): string {
|
|
80
|
+
if (typeof content === 'string') return content;
|
|
81
|
+
if (Array.isArray(content)) {
|
|
82
|
+
return content
|
|
83
|
+
.map((c: Record<string, unknown>) => (typeof c['text'] === 'string' ? c['text'] : ''))
|
|
84
|
+
.filter((t) => t !== '')
|
|
85
|
+
.join('\n');
|
|
86
|
+
}
|
|
87
|
+
return '';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** How a zod parse failed, one `path: message` per issue. */
|
|
91
|
+
export function issues(list: readonly { path: PropertyKey[]; message: string }[]): string {
|
|
92
|
+
return list.map((i) => `${i.path.map(String).join('.') || '(output)'}: ${i.message}`).join('; ');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Splits a stream into lines on LF only (a trailing CR is dropped), decoding UTF-8 across chunks.
|
|
97
|
+
* Not readline: it also breaks on U+2028/U+2029, which JSON strings may hold raw.
|
|
98
|
+
*/
|
|
99
|
+
function eachLine(stream: NodeJS.ReadableStream, onLine: (line: string) => void): void {
|
|
100
|
+
const decoder = new StringDecoder('utf8');
|
|
101
|
+
let buf = '';
|
|
102
|
+
const emit = (line: string) => onLine(line.endsWith('\r') ? line.slice(0, -1) : line);
|
|
103
|
+
stream.on('data', (chunk: Buffer) => {
|
|
104
|
+
buf += decoder.write(chunk);
|
|
105
|
+
for (let nl = buf.indexOf('\n'); nl !== -1; nl = buf.indexOf('\n')) {
|
|
106
|
+
emit(buf.slice(0, nl));
|
|
107
|
+
buf = buf.slice(nl + 1);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
stream.on('end', () => {
|
|
111
|
+
const tail = buf + decoder.end();
|
|
112
|
+
buf = '';
|
|
113
|
+
if (tail.length > 0) emit(tail);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface AgentProcessOptions {
|
|
118
|
+
bin: string;
|
|
119
|
+
args: string[];
|
|
120
|
+
cwd: string;
|
|
121
|
+
env: Record<string, string>;
|
|
122
|
+
timeoutSec: number;
|
|
123
|
+
/** aborting it stops the child: SIGTERM, then SIGKILL after `KILL_GRACE_MS` */
|
|
124
|
+
signal: AbortSignal;
|
|
125
|
+
/** each stdout line, in order, as it arrives */
|
|
126
|
+
onLine: (line: string) => void;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** How an agent process ended. */
|
|
130
|
+
export interface AgentProcessEnd {
|
|
131
|
+
/** every stdout line, unchanged: the transcript (artifact-store door 7) */
|
|
132
|
+
lines: string[];
|
|
133
|
+
exitCode: number | null;
|
|
134
|
+
/** the last non-empty stderr line, trimmed */
|
|
135
|
+
lastStderr: string;
|
|
136
|
+
/** bounded non-empty stderr lines joined by `\n` (up to 4096 chars) */
|
|
137
|
+
stderr: string;
|
|
138
|
+
spawnError?: string;
|
|
139
|
+
timedOut: boolean;
|
|
140
|
+
cancelled: boolean;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const STDERR_MAX = 4096;
|
|
144
|
+
|
|
145
|
+
/** Spawns one agent CLI session; `kill` stops it early (e.g. a runner's own turn or budget limit). */
|
|
146
|
+
export function spawnAgent(opts: AgentProcessOptions): { kill: () => void; done: Promise<AgentProcessEnd> } {
|
|
147
|
+
const end: AgentProcessEnd = { lines: [], exitCode: null, lastStderr: '', stderr: '', timedOut: false, cancelled: false };
|
|
148
|
+
const child = spawn(opts.bin, opts.args, { cwd: opts.cwd, env: opts.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
149
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
150
|
+
const kill = () => {
|
|
151
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
152
|
+
child.kill('SIGTERM');
|
|
153
|
+
killTimer = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);
|
|
154
|
+
};
|
|
155
|
+
const timer = setTimeout(() => {
|
|
156
|
+
end.timedOut = true;
|
|
157
|
+
kill();
|
|
158
|
+
}, opts.timeoutSec * 1000);
|
|
159
|
+
const onAbort = () => {
|
|
160
|
+
end.cancelled = true;
|
|
161
|
+
kill();
|
|
162
|
+
};
|
|
163
|
+
opts.signal.addEventListener('abort', onAbort, { once: true });
|
|
164
|
+
|
|
165
|
+
eachLine(child.stderr, (line) => {
|
|
166
|
+
const trimmed = line.trim();
|
|
167
|
+
if (trimmed !== '') {
|
|
168
|
+
end.lastStderr = trimmed;
|
|
169
|
+
if (end.stderr.length < STDERR_MAX) {
|
|
170
|
+
const next = end.stderr === '' ? trimmed : `${end.stderr}\n${trimmed}`;
|
|
171
|
+
end.stderr = next.length <= STDERR_MAX ? next : next.slice(0, STDERR_MAX);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
eachLine(child.stdout, (line) => {
|
|
176
|
+
end.lines.push(line);
|
|
177
|
+
opts.onLine(line);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
const done = new Promise<AgentProcessEnd>((resolve) => {
|
|
181
|
+
const finish = () => {
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
clearTimeout(killTimer);
|
|
184
|
+
opts.signal.removeEventListener('abort', onAbort);
|
|
185
|
+
resolve(end);
|
|
186
|
+
};
|
|
187
|
+
child.on('error', (err) => {
|
|
188
|
+
end.spawnError = err.message;
|
|
189
|
+
finish();
|
|
190
|
+
});
|
|
191
|
+
child.on('close', (code) => {
|
|
192
|
+
end.exitCode = code;
|
|
193
|
+
// the last stdout lines are read before close resolves the session
|
|
194
|
+
setImmediate(finish);
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
return { kill, done };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** What one session of a runner came to, read from its CLI's stream. */
|
|
201
|
+
export type AttemptEnd = { usage: AgentUsage; turns: number; lines: string[] } & (
|
|
202
|
+
| { kind: 'fail'; status: 'limit' | 'error' | 'cancelled'; reason: string }
|
|
203
|
+
/** `value` undefined: the session gave no output, `missing` says why */
|
|
204
|
+
| { kind: 'output'; value: unknown; missing: string; sessionId?: string; resumed?: boolean }
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Runs a session per attempt until one ends: stores its transcript, emits `agent.finished`, checks
|
|
209
|
+
* the output against the contract and `request.validate`, and retries once with the problems
|
|
210
|
+
* appended to the prompt.
|
|
211
|
+
*/
|
|
212
|
+
export async function runAttempts<T>(
|
|
213
|
+
ctx: AgentContext,
|
|
214
|
+
request: AgentRequest<T>,
|
|
215
|
+
session: (attempt: number, prompt: string) => Promise<AttemptEnd>,
|
|
216
|
+
): Promise<AgentResult<T>> {
|
|
217
|
+
if (ctx.signal.aborted) return { status: 'cancelled', reason: 'cancelled', usage: ZERO_USAGE, turns: 0 };
|
|
218
|
+
|
|
219
|
+
const finish = (status: 'completed' | 'limit' | 'error' | 'cancelled', turns: number, reason?: string, transcriptRef?: string) =>
|
|
220
|
+
ctx.emit('agent.finished', {
|
|
221
|
+
status,
|
|
222
|
+
turns,
|
|
223
|
+
...(reason !== undefined ? { reason } : {}),
|
|
224
|
+
...(transcriptRef !== undefined ? { transcriptRef } : {}),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
/** Puts the session's stdout lines as its transcript; undefined when there is none to put (door 7). */
|
|
228
|
+
async function transcript(attempt: number, lines: string[]): Promise<string | undefined> {
|
|
229
|
+
if (ctx.artifacts === undefined || lines.length === 0) return undefined;
|
|
230
|
+
try {
|
|
231
|
+
const ref = await ctx.artifacts.put(`transcripts/${request.role}-${attempt}.jsonl`, lines.join('\n'), {
|
|
232
|
+
mediaType: 'application/x-ndjson',
|
|
233
|
+
});
|
|
234
|
+
return ref.sha256;
|
|
235
|
+
} catch (err) {
|
|
236
|
+
ctx.emit('log', { level: 'warn', msg: `transcript not stored: ${err instanceof Error ? err.message : String(err)}` });
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let prompt = request.prompt;
|
|
242
|
+
for (let attempt = 1; ; attempt++) {
|
|
243
|
+
const s = await session(attempt, prompt);
|
|
244
|
+
const { usage, turns } = s;
|
|
245
|
+
const ref = await transcript(attempt, s.lines);
|
|
246
|
+
const fail = (status: 'limit' | 'error' | 'cancelled', reason: string): AgentResult<T> => {
|
|
247
|
+
finish(status, turns, reason, ref);
|
|
248
|
+
return { status, reason, usage, turns };
|
|
249
|
+
};
|
|
250
|
+
if (s.kind === 'fail') return fail(s.status, s.reason);
|
|
251
|
+
|
|
252
|
+
const parsed = s.value === undefined ? undefined : request.output.safeParse(s.value);
|
|
253
|
+
// the facts check (boss-sdd-gaps door 9): its problems share the contract's one retry; a throw ends here
|
|
254
|
+
let facts: string[] = [];
|
|
255
|
+
if (parsed?.success === true && request.validate !== undefined) {
|
|
256
|
+
try {
|
|
257
|
+
facts = await request.validate(parsed.data);
|
|
258
|
+
} catch (err) {
|
|
259
|
+
return fail('error', `output facts: ${err instanceof Error ? err.message : String(err)}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (parsed?.success === true && facts.length === 0) {
|
|
263
|
+
finish('completed', turns, undefined, ref);
|
|
264
|
+
return {
|
|
265
|
+
status: 'completed',
|
|
266
|
+
output: parsed.data,
|
|
267
|
+
usage,
|
|
268
|
+
turns,
|
|
269
|
+
...(s.sessionId !== undefined ? { sessionId: s.sessionId } : {}),
|
|
270
|
+
...(s.resumed !== undefined ? { resumed: s.resumed } : {}),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const problems = parsed === undefined ? s.missing : parsed.success ? facts.join('; ') : issues(parsed.error.issues);
|
|
274
|
+
const result = fail('error', `${parsed?.success === true ? 'output facts' : 'output contract'}: ${problems}`);
|
|
275
|
+
if (attempt >= 2) return result;
|
|
276
|
+
prompt = `${request.prompt}\n\nYour previous answer did not match the required output: ${problems}`;
|
|
277
|
+
}
|
|
278
|
+
}
|