@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.
Files changed (57) hide show
  1. package/README.md +96 -2
  2. package/dist/fragments/approval.d.ts +83 -0
  3. package/dist/fragments/approval.d.ts.map +1 -0
  4. package/dist/fragments/approval.js +170 -0
  5. package/dist/fragments/approval.js.map +1 -0
  6. package/dist/fragments/common.d.ts +65 -0
  7. package/dist/fragments/common.d.ts.map +1 -0
  8. package/dist/fragments/common.js +138 -0
  9. package/dist/fragments/common.js.map +1 -0
  10. package/dist/fragments/deliver.d.ts +178 -0
  11. package/dist/fragments/deliver.d.ts.map +1 -0
  12. package/dist/fragments/deliver.js +232 -0
  13. package/dist/fragments/deliver.js.map +1 -0
  14. package/dist/fragments/index.d.ts +6 -0
  15. package/dist/fragments/index.d.ts.map +1 -0
  16. package/dist/fragments/index.js +6 -0
  17. package/dist/fragments/index.js.map +1 -0
  18. package/dist/fragments/validated.d.ts +64 -0
  19. package/dist/fragments/validated.d.ts.map +1 -0
  20. package/dist/fragments/validated.js +95 -0
  21. package/dist/fragments/validated.js.map +1 -0
  22. package/dist/fragments/verifier-round.d.ts +128 -0
  23. package/dist/fragments/verifier-round.d.ts.map +1 -0
  24. package/dist/fragments/verifier-round.js +295 -0
  25. package/dist/fragments/verifier-round.js.map +1 -0
  26. package/dist/index.d.ts +597 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +244 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/kit.d.ts +44 -0
  31. package/dist/kit.d.ts.map +1 -0
  32. package/dist/kit.js +32 -0
  33. package/dist/kit.js.map +1 -0
  34. package/dist/plugin.d.ts +126 -0
  35. package/dist/plugin.d.ts.map +1 -0
  36. package/dist/plugin.js +15 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/dist/prompt.d.ts +10 -0
  39. package/dist/prompt.d.ts.map +1 -0
  40. package/dist/prompt.js +34 -0
  41. package/dist/prompt.js.map +1 -0
  42. package/dist/runner.d.ts +88 -0
  43. package/dist/runner.d.ts.map +1 -0
  44. package/dist/runner.js +224 -0
  45. package/dist/runner.js.map +1 -0
  46. package/package.json +79 -3
  47. package/src/fragments/approval.ts +267 -0
  48. package/src/fragments/common.ts +195 -0
  49. package/src/fragments/deliver.ts +447 -0
  50. package/src/fragments/index.ts +57 -0
  51. package/src/fragments/validated.ts +217 -0
  52. package/src/fragments/verifier-round.ts +442 -0
  53. package/src/index.ts +890 -0
  54. package/src/kit.ts +137 -0
  55. package/src/plugin.ts +128 -0
  56. package/src/prompt.ts +29 -0
  57. package/src/runner.ts +278 -0
@@ -0,0 +1,267 @@
1
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
2
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { parseRef } from '@artieeez/cf-core';
5
+ import {
6
+ ref,
7
+ type Duration,
8
+ type HumanStep,
9
+ type NoEvents,
10
+ type PluginApis,
11
+ type Ref,
12
+ type Settings,
13
+ type TaskContext,
14
+ type TaskStep,
15
+ } from '../index.ts';
16
+ import { assertPositiveInt, assertSlug, stepId } from './common.ts';
17
+
18
+ /** Form schema of an `approval` human step: captures the approver's verbatim words. */
19
+ export const ApprovalForm = z.strictObject({
20
+ words: z.string().min(1),
21
+ });
22
+ export type ApprovalFormData = z.infer<typeof ApprovalForm>;
23
+
24
+ /** Output schema of an `approval` record task (AD-031). */
25
+ export const ApprovalRecordOutput = z.strictObject({
26
+ file: z.string(),
27
+ date: z.string(),
28
+ words: z.string(),
29
+ line: z.string(),
30
+ });
31
+ export type ApprovalRecordOutput = z.infer<typeof ApprovalRecordOutput>;
32
+
33
+ /** Information passed to a custom `record` hook in `approval`. */
34
+ export interface ApprovalRecordInfo {
35
+ file: string;
36
+ words: string;
37
+ date: string;
38
+ line: string;
39
+ }
40
+
41
+ /** Options for `approval(id, opts)`. */
42
+ export interface ApprovalOptions<
43
+ I = unknown,
44
+ P extends PluginApis = PluginApis,
45
+ S = Settings,
46
+ E = NoEvents,
47
+ > {
48
+ /** Workspace-relative path to the file being approved (static string or derived from `ctx`). */
49
+ file: string | ((ctx: TaskContext<I, P, S, E>) => string);
50
+ /** Explicit artifacts ref for hash binding (`ref('<producer>.artifacts.<glob>')`); overrides `producer`. */
51
+ bind?: Ref;
52
+ /** Producer step id shorthand when `file` is a static string (builds `ref('<producer>.artifacts.<file>')`). */
53
+ producer?: string;
54
+ /** Human prompt title; defaults to `Approve <file>` or `Approve <id>`. */
55
+ title?: string;
56
+ /** Extra `about` entries merged alongside the bound artifact ref. */
57
+ about?: Record<string, Ref>;
58
+ /** Target step after the approval is recorded. */
59
+ next: string;
60
+ /** Target step when the human rejects the approval. */
61
+ onRejected: string;
62
+ /** Optional visit cap on the human approval step. */
63
+ maxVisits?: number;
64
+ /** Target step when `maxVisits` is exhausted; defaults to `'$fail'` when `maxVisits` is set. */
65
+ onExhausted?: string;
66
+ /** Optional deadline on the human approval step. */
67
+ timeout?: { after: Duration; outcome: 'approved' | 'rejected' };
68
+ /** Optional reminder cadence on the human approval step. */
69
+ remind?: { every: Duration };
70
+ /** Optional working directory for the record task. */
71
+ wd?: string;
72
+ /** Optional clock used to format `<YYYY-MM-DD>`; defaults to `() => new Date()`. */
73
+ now?: () => Date;
74
+ /** Custom recorder replacing the default workspace disk write. */
75
+ record?: (ctx: TaskContext<I, P, S, E>, info: ApprovalRecordInfo) => Promise<void> | void;
76
+ }
77
+
78
+ /** What `approval(id, opts)` returns: entry id, step handles, and spreadable `steps`. */
79
+ export interface ApprovalFragment<
80
+ Id extends string,
81
+ I,
82
+ P extends PluginApis,
83
+ S,
84
+ E,
85
+ > {
86
+ start: Id;
87
+ ids: { approve: Id; record: `${Id}-record` };
88
+ approve: HumanStep<'approved' | 'rejected', typeof ApprovalForm>;
89
+ record: TaskStep<I, 'recorded', P, typeof ApprovalRecordOutput, S, E>;
90
+ steps: Record<Id, HumanStep<'approved' | 'rejected', typeof ApprovalForm>> &
91
+ Record<`${Id}-record`, TaskStep<I, 'recorded', P, typeof ApprovalRecordOutput, S, E>>;
92
+ }
93
+
94
+ const APPROVED_LINE_RE = /^\**\s*Approved\s*\**\s*:/i;
95
+ const FENCE_RE = /^(`{3,}|~{3,})/;
96
+
97
+ /**
98
+ * Inserts or replaces `**Approved**: <date> - user: "<words>"` in `content`:
99
+ * 1. Replaces an existing `**Approved**:` line outside fenced code blocks (idempotent).
100
+ * 2. Otherwise inserts after the first leading `# Heading` line.
101
+ * 3. Otherwise prepends at the top of the file.
102
+ */
103
+ export function applyApprovalLine(content: string, line: string): string {
104
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
105
+ const hadTrailingNewline = content.endsWith('\n');
106
+ const raw = hadTrailingNewline ? content.slice(0, content.endsWith('\r\n') ? -2 : -1) : content;
107
+ const lines = raw === '' ? [] : raw.split(/\r?\n/);
108
+
109
+ let fence: string | undefined;
110
+ for (let i = 0; i < lines.length; i++) {
111
+ const trimmed = lines[i]!.trim();
112
+ const fenceMatch = FENCE_RE.exec(trimmed);
113
+ if (fenceMatch !== null) {
114
+ const marker = fenceMatch[1]![0]!;
115
+ if (fence === undefined) fence = marker;
116
+ else if (fence === marker) fence = undefined;
117
+ continue;
118
+ }
119
+ if (fence === undefined && APPROVED_LINE_RE.test(trimmed)) {
120
+ lines[i] = line;
121
+ return lines.join(eol) + (hadTrailingNewline ? eol : '');
122
+ }
123
+ }
124
+
125
+ const firstNonEmpty = lines.findIndex((l) => l.trim() !== '');
126
+ if (firstNonEmpty !== -1 && /^#\s+/.test(lines[firstNonEmpty]!)) {
127
+ const after = firstNonEmpty + 1;
128
+ if (lines[after] === '') {
129
+ lines.splice(after + 1, 0, line, '');
130
+ } else {
131
+ lines.splice(after, 0, '', line);
132
+ }
133
+ } else if (lines.length === 0) {
134
+ lines.push(line);
135
+ } else {
136
+ lines.unshift(line, '');
137
+ }
138
+
139
+ return lines.join(eol) + (hadTrailingNewline || content === '' ? eol : '');
140
+ }
141
+
142
+ /** Ensures `filePath` is relative and resolves strictly inside `baseDir`. */
143
+ function confinePath(baseDir: string, filePath: string, id: string): string {
144
+ if (filePath.trim() === '' || isAbsolute(filePath)) {
145
+ throw new Error(`approval(${id}): file "${filePath}" must be relative to workspace "${baseDir}"`);
146
+ }
147
+ const base = resolve(baseDir);
148
+ const abs = resolve(base, filePath);
149
+ const rel = relative(base, abs);
150
+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
151
+ throw new Error(`approval(${id}): file "${filePath}" escapes workspace "${baseDir}"`);
152
+ }
153
+ return abs;
154
+ }
155
+
156
+ /**
157
+ * Builds a hash-bound human approval step `<id>` followed by `<id>-record`, which writes the
158
+ * approver's exact words into the workspace file on disk without calling `ctx.artifacts.put` on
159
+ * the bound artifact path (preventing AD-015 reopen loops).
160
+ */
161
+ export function approval<
162
+ const Id extends string,
163
+ I = unknown,
164
+ P extends PluginApis = PluginApis,
165
+ S = Settings,
166
+ E = NoEvents,
167
+ >(
168
+ id: Id,
169
+ opts: ApprovalOptions<I, P, S, E>,
170
+ ): ApprovalFragment<Id, I, P, S, E> {
171
+ assertSlug(id, 'approval');
172
+
173
+ let bindRef: Ref;
174
+ if (opts.bind !== undefined) {
175
+ bindRef = opts.bind;
176
+ } else if (opts.producer !== undefined && typeof opts.file === 'string') {
177
+ assertSlug(opts.producer, `approval(${id}) producer`);
178
+ bindRef = ref(`${opts.producer}.artifacts.${opts.file}`);
179
+ } else {
180
+ throw new Error(`approval(${id}): provide "bind" (or "producer" with a static file path)`);
181
+ }
182
+
183
+ const parsed = parseRef(bindRef.ref);
184
+ if (typeof parsed === 'string' || parsed.scope !== 'artifacts') {
185
+ throw new Error(
186
+ `approval(${id}): bind must be a valid artifacts ref (<step>.artifacts.<glob>), got "${bindRef.ref}"`,
187
+ );
188
+ }
189
+
190
+ if (opts.maxVisits !== undefined) {
191
+ assertPositiveInt(opts.maxVisits, `approval(${id}) maxVisits`);
192
+ }
193
+
194
+ const recordId = stepId(id, 'record');
195
+ const label = typeof opts.file === 'string' ? opts.file : 'artifact';
196
+
197
+ const approve: HumanStep<'approved' | 'rejected', typeof ApprovalForm> = {
198
+ kind: 'human',
199
+ title: opts.title ?? `Approve ${typeof opts.file === 'string' ? opts.file : id}`,
200
+ form: ApprovalForm,
201
+ bind: bindRef,
202
+ about: { [label]: bindRef, ...(opts.about ?? {}) },
203
+ outcomes: ['approved', 'rejected'] as const,
204
+ next: { approved: recordId, rejected: opts.onRejected },
205
+ ...(opts.maxVisits !== undefined
206
+ ? { maxVisits: opts.maxVisits, onExhausted: opts.onExhausted ?? '$fail' }
207
+ : {}),
208
+ ...(opts.timeout !== undefined ? { timeout: opts.timeout } : {}),
209
+ ...(opts.remind !== undefined ? { remind: opts.remind } : {}),
210
+ };
211
+
212
+ const record: TaskStep<I, 'recorded', P, typeof ApprovalRecordOutput, S, E> = {
213
+ kind: 'task',
214
+ outcomes: ['recorded'] as const,
215
+ next: { recorded: opts.next },
216
+ ...(opts.wd !== undefined ? { wd: opts.wd } : {}),
217
+ output: ApprovalRecordOutput,
218
+ async run(ctx) {
219
+ const answer = ctx.output(approve);
220
+ const rawWords = answer?.words;
221
+ const trimmed = typeof rawWords === 'string' ? rawWords.trim() : '';
222
+ if (trimmed === '') {
223
+ throw new Error(`approval(${id}): approver words are empty`);
224
+ }
225
+
226
+ const filePath = typeof opts.file === 'function' ? opts.file(ctx) : opts.file;
227
+ const abs = confinePath(ctx.wd, filePath, id);
228
+
229
+ const date = (opts.now?.() ?? new Date()).toISOString().slice(0, 10);
230
+ const safeWords = trimmed.replace(/\r?\n+/g, ' ').replace(/\s+/g, ' ').replace(/"/g, "'");
231
+ const line = `**Approved**: ${date} - user: "${safeWords}"`;
232
+
233
+ if (opts.record !== undefined) {
234
+ await opts.record(ctx, { file: filePath, words: trimmed, date, line });
235
+ } else {
236
+ if (!existsSync(abs)) {
237
+ throw new Error(`approval(${id}): file not found at "${abs}"`);
238
+ }
239
+ const realBase = realpathSync(resolve(ctx.wd));
240
+ const realAbs = realpathSync(abs);
241
+ const realRel = relative(realBase, realAbs);
242
+ if (realRel === '' || realRel === '..' || realRel.startsWith(`..${sep}`) || isAbsolute(realRel)) {
243
+ throw new Error(`approval(${id}): file "${filePath}" escapes workspace "${ctx.wd}"`);
244
+ }
245
+ const current = readFileSync(abs, 'utf8');
246
+ const updated = applyApprovalLine(current, line);
247
+ writeFileSync(abs, updated, 'utf8');
248
+ }
249
+
250
+ return { outcome: 'recorded', output: { file: filePath, date, words: trimmed, line } };
251
+ },
252
+ };
253
+
254
+ const steps = {
255
+ [id]: approve,
256
+ [recordId]: record,
257
+ } as Record<Id, HumanStep<'approved' | 'rejected', typeof ApprovalForm>> &
258
+ Record<`${Id}-record`, TaskStep<I, 'recorded', P, typeof ApprovalRecordOutput, S, E>>;
259
+
260
+ return {
261
+ start: id,
262
+ ids: { approve: id, record: recordId },
263
+ approve,
264
+ record,
265
+ steps,
266
+ };
267
+ }
@@ -0,0 +1,195 @@
1
+ import { z } from 'zod';
2
+ import { OUTPUT_MAX_BYTES, outputBytes } from '@artieeez/cf-core';
3
+ import type { NoEvents, PluginApis, Settings, TaskContext } from '../index.ts';
4
+
5
+ /** Matches manifest `StepId` (`packages/core/src/manifest.ts`). */
6
+ export const SLUG_RE = /^[a-z][a-z0-9-]*$/;
7
+
8
+ /** Default per-stream char cap for script output (keeps serialized ValidationOutput under AD-012). */
9
+ export const DEFAULT_MAX_OUTPUT_CHARS = 16_000;
10
+
11
+ /** Asserts that `id` is a valid manifest step slug (`/^[a-z][a-z0-9-]*$/`). */
12
+ export function assertSlug(id: string, context: string): void {
13
+ if (!SLUG_RE.test(id)) {
14
+ throw new Error(`${context}: fragment id "${id}" must be a lowercase slug (/^[a-z][a-z0-9-]*$/)`);
15
+ }
16
+ }
17
+
18
+ /** Asserts that `value` is a positive integer (>= 1). */
19
+ export function assertPositiveInt(value: number, label: string): void {
20
+ if (!Number.isInteger(value) || value < 1) {
21
+ throw new Error(`${label} must be a positive integer, got ${String(value)}`);
22
+ }
23
+ }
24
+
25
+ /** Builds a prefixed step id `<prefix>-<suffix>`. */
26
+ export function stepId<P extends string, S extends string>(prefix: P, suffix: S): `${P}-${S}` {
27
+ return `${prefix}-${suffix}`;
28
+ }
29
+
30
+ /**
31
+ * Enclosing fan-out prefix of `stepPath`: `""` at top level, `"units[u1]."` for
32
+ * `"units[u1].verify-findings"`.
33
+ */
34
+ export function scopePrefix(stepPath: string): string {
35
+ const dot = stepPath.lastIndexOf('.');
36
+ return dot === -1 ? '' : stepPath.slice(0, dot + 1);
37
+ }
38
+
39
+ /**
40
+ * Slices `text` to at most `maxChars` UTF-16 code units without splitting a surrogate pair
41
+ * (prevents lone surrogates that JSONB rejects, L-022).
42
+ */
43
+ export function sliceSurrogateSafe(text: string, maxChars: number): { text: string; truncated: boolean } {
44
+ const limit = Math.max(0, Math.floor(maxChars));
45
+ if (text.length <= limit) return { text, truncated: false };
46
+ let end = limit;
47
+ if (end > 0) {
48
+ const code = text.charCodeAt(end - 1);
49
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1;
50
+ }
51
+ return { text: text.slice(0, end), truncated: true };
52
+ }
53
+
54
+ /** Structured output of a script validation / proofs / completion gate task (AD-031). */
55
+ export const ValidationOutput = z.strictObject({
56
+ passed: z.boolean(),
57
+ code: z.number().int().nullable().optional(),
58
+ stdout: z.string(),
59
+ stderr: z.string(),
60
+ output: z.string(),
61
+ truncated: z.boolean(),
62
+ durationMs: z.number().int().nonnegative().optional(),
63
+ });
64
+ export type ValidationOutput = z.infer<typeof ValidationOutput>;
65
+
66
+ /** Command run without a shell via `ctx.exec` (AD-010). */
67
+ export interface CommandSpec {
68
+ cmd: string;
69
+ args?: readonly string[];
70
+ cwd?: string;
71
+ env?: Record<string, string>;
72
+ timeoutMs?: number;
73
+ }
74
+
75
+ /** Result returned by a custom validation callback `{ run(ctx) }`. */
76
+ export interface ValidationCheckResult {
77
+ passed: boolean;
78
+ output?: string;
79
+ stdout?: string;
80
+ stderr?: string;
81
+ code?: number | null;
82
+ }
83
+
84
+ /** A command tuple, `CommandSpec`, dynamic builder, or custom validator function. */
85
+ export type ValidationScript<
86
+ I = unknown,
87
+ P extends PluginApis = PluginApis,
88
+ S = Settings,
89
+ E = NoEvents,
90
+ > =
91
+ | readonly [cmd: string, ...args: string[]]
92
+ | CommandSpec
93
+ | ((
94
+ ctx: TaskContext<I, P, S, E>,
95
+ ) => Promise<CommandSpec | readonly [string, ...string[]]> | CommandSpec | readonly [string, ...string[]])
96
+ | {
97
+ run(ctx: TaskContext<I, P, S, E>): Promise<ValidationCheckResult> | ValidationCheckResult;
98
+ };
99
+
100
+ function combineStreams(stdout: string, stderr: string): string {
101
+ if (stdout === '') return stderr;
102
+ if (stderr === '') return stdout;
103
+ return `${stdout}\n${stderr}`;
104
+ }
105
+
106
+ /**
107
+ * Executes a `ValidationScript`, enforces surrogate-safe truncation within `maxOutputChars` and
108
+ * AD-012's `OUTPUT_MAX_BYTES`, and writes the full output log as an artifact when truncated.
109
+ */
110
+ export async function runValidationScript<
111
+ I,
112
+ P extends PluginApis,
113
+ S,
114
+ E,
115
+ >(
116
+ ctx: TaskContext<I, P, S, E>,
117
+ script: ValidationScript<I, P, S, E>,
118
+ opts: { artifactPrefix: string; maxOutputChars?: number },
119
+ ): Promise<ValidationOutput> {
120
+ const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
121
+ let passed: boolean;
122
+ let code: number | null | undefined;
123
+ let rawStdout: string;
124
+ let rawStderr: string;
125
+ let rawCombined: string;
126
+ let durationMs: number | undefined;
127
+
128
+ if (typeof script === 'object' && !Array.isArray(script) && 'run' in script) {
129
+ const started = Date.now();
130
+ const res = await script.run(ctx);
131
+ passed = res.passed;
132
+ code = res.code;
133
+ rawStdout = res.stdout ?? (res.output !== undefined && res.stderr === undefined ? res.output : '');
134
+ rawStderr = res.stderr ?? '';
135
+ rawCombined = res.output ?? combineStreams(rawStdout, rawStderr);
136
+ durationMs = Math.max(0, Date.now() - started);
137
+ } else {
138
+ const resolved = typeof script === 'function' ? await script(ctx) : script;
139
+ const spec: CommandSpec = Array.isArray(resolved)
140
+ ? { cmd: resolved[0], args: resolved.slice(1) }
141
+ : (resolved as CommandSpec);
142
+ const execOpts = {
143
+ ...(spec.cwd !== undefined ? { cwd: spec.cwd } : {}),
144
+ ...(spec.env !== undefined ? { env: spec.env } : {}),
145
+ ...(spec.timeoutMs !== undefined ? { timeoutMs: spec.timeoutMs } : {}),
146
+ };
147
+ const r = await ctx.exec(spec.cmd, [...(spec.args ?? [])], execOpts);
148
+ passed = r.code === 0 && !r.timedOut && !r.cancelled;
149
+ code = r.code;
150
+ rawStdout = r.stdout;
151
+ rawStderr = r.stderr;
152
+ rawCombined = combineStreams(rawStdout, rawStderr);
153
+ durationMs = Math.max(0, Math.round(r.durationMs));
154
+ }
155
+
156
+ let outSlice = sliceSurrogateSafe(rawStdout, maxChars);
157
+ let errSlice = sliceSurrogateSafe(rawStderr, maxChars);
158
+ const combinedFromSlices = combineStreams(outSlice.text, errSlice.text);
159
+ let combSlice =
160
+ rawCombined === combineStreams(rawStdout, rawStderr)
161
+ ? { text: combinedFromSlices, truncated: outSlice.truncated || errSlice.truncated }
162
+ : sliceSurrogateSafe(rawCombined, maxChars * 2);
163
+
164
+ let truncated = outSlice.truncated || errSlice.truncated || combSlice.truncated;
165
+
166
+ const build = (): ValidationOutput => ({
167
+ passed,
168
+ ...(code !== undefined ? { code } : {}),
169
+ stdout: outSlice.text,
170
+ stderr: errSlice.text,
171
+ output: combSlice.text,
172
+ truncated,
173
+ ...(durationMs !== undefined ? { durationMs } : {}),
174
+ });
175
+
176
+ // Guarantee serialized JSON stays within AD-012's 65,536-byte cap even with multi-byte UTF-8.
177
+ let payload = build();
178
+ let cap = maxChars;
179
+ while (outputBytes(payload) > OUTPUT_MAX_BYTES && cap > 0) {
180
+ cap = Math.floor(cap / 2);
181
+ truncated = true;
182
+ outSlice = sliceSurrogateSafe(rawStdout, cap);
183
+ errSlice = sliceSurrogateSafe(rawStderr, cap);
184
+ combSlice = sliceSurrogateSafe(rawCombined, cap);
185
+ payload = build();
186
+ }
187
+
188
+ if (truncated) {
189
+ await ctx.artifacts.put(`${opts.artifactPrefix}-visit-${ctx.visit}.log`, rawCombined, {
190
+ mediaType: 'text/plain',
191
+ });
192
+ }
193
+
194
+ return payload;
195
+ }