This repository was archived by the owner on May 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathaction.ts
More file actions
638 lines (574 loc) · 18.2 KB
/
action.ts
File metadata and controls
638 lines (574 loc) · 18.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { resolve } from "node:path";
import { snakeCase } from "es-toolkit";
import {
CORE_VERSION,
GENAI_ANY_REGEX,
GENAI_SRC,
GitHubClient,
YAMLStringify,
YAMLTryParse,
createScript as coreCreateScript,
dedent,
deleteEmptyValues,
deleteUndefinedValues,
genaiscriptDebug,
isCI,
logInfo,
logVerbose,
nodeTryReadPackage,
runtimeHost,
templateIdFromFileName,
titleize,
tryReadText,
tryStat,
writeText,
} from "@genaiscript/core";
import { buildProject } from "@genaiscript/core";
import type { JSONSchemaDescribed, JSONSchemaObject, JSONSchemaString } from "@genaiscript/core";
import { shellConfirm, shellSelect } from "@genaiscript/runtime";
const dbg = genaiscriptDebug("cli:action");
const github = GitHubClient.default();
interface GitHubActionFieldType {
description: string;
required?: boolean;
default?: string;
}
/**
* Generates GitHub Action files for a given script, including action.yml, Dockerfile, package.json, README.md, and .gitignore, using script metadata and provided options.
*
* If scriptId is not provided, prompts the user for the script name and initializes a new script. If scriptId is given, attempts to load the script from the project.
*
* Parameters:
* scriptId: The identifier or filename of the script for which action files will be generated. If falsy, user will be prompted to enter a name and a new script will be created.
* options: Configuration object with the following optional properties:
* force: If true, overwrite existing files without prompting.
* out: Output directory for generated files. Defaults to action/<script.id> under the genaiscript workspace.
* ffmpeg: If true, install ffmpeg in the Docker image.
* python: If true, install python3 and py3-pip in the Docker image.
* playwright: If true, use Playwright Docker image and install Playwright dependencies.
* packageLock: If true, generate a package-lock.json file using npm ci or npm install.
* image: Base Docker image to use. Defaults to Playwright image if playwright flag is set, otherwise node:lts-alpine.
* apks: Additional Alpine packages to install in the Docker image.
* provider: Name of the GenAI provider to use in the start command.
*
* Throws:
* Error if the script cannot be found when scriptId is provided.
*
* Side Effects:
* Writes or overwrites files in the output directory.
* Executes npm or node commands to generate lock files if packageLock is set.
*/
export async function actionConfigure(
scriptId: string,
options: {
force?: boolean;
out?: string;
ffmpeg?: boolean;
python?: boolean;
playwright?: boolean;
image?: string;
apks?: string[];
provider?: string;
pullRequestComment?: string | boolean;
pullRequestDescription?: string | boolean;
pullRequestReviews?: boolean;
event?: string;
interactive?: boolean;
},
) {
options = options || {};
const { owner, repo } = (await github.info()) || {};
if (!owner || !repo) throw new Error("GitHub repository information not found.");
const {
force,
out = resolve("."),
provider,
pullRequestComment,
pullRequestDescription,
pullRequestReviews,
interactive,
} = options;
scriptId = scriptId || "action";
dbg(`owner: %s`, owner);
dbg(`repo: %s`, repo);
dbg(`script: %s`, scriptId);
const writeFile = async (name: string, content: string) => {
const filePath = resolve(out, name);
if (!force && (await tryStat(filePath))) {
logInfo(`skipping ${filePath} (file already exists), use --force to overwrite`);
} else {
logVerbose(`writing ${filePath}`);
await writeText(filePath, content);
}
};
if (!isCI && interactive) {
options.event =
options.event ||
(await shellSelect("What event will trigger the action?", [
"push",
"pull_request",
"issue_comment",
"issue",
]));
options.python =
options.python === undefined
? await shellConfirm("Will you use Python?", {
default: false,
})
: options.python;
if (options.event === "pull_request") {
options.pullRequestDescription =
options.pullRequestDescription === undefined
? await shellConfirm("Will you publish the output as a pull request description?", {
default: false,
})
: options.pullRequestDescription;
options.pullRequestComment =
options.pullRequestComment === undefined
? await shellConfirm("Will you publish the output as a pull request comment?", {
default: false,
})
: options.pullRequestComment;
options.pullRequestReviews =
options.pullRequestReviews === undefined
? await shellConfirm("Will you publish diagnostics as a pull request review comments?", {
default: false,
})
: options.pullRequestReviews;
}
options.playwright =
options.playwright === undefined
? await shellConfirm("Will you use Playwright? (host.browser...)", {
default: false,
})
: options.playwright;
options.ffmpeg =
options.ffmpeg === undefined
? await shellConfirm("Will you use ffmpeg?", {
default: false,
})
: options.ffmpeg;
}
const event: "push" | "pull_request" | "issue_comment" | "issue" =
(options.event as "push" | "pull_request" | "issue_comment" | "issue" | undefined) ??
(pullRequestComment || pullRequestDescription || pullRequestReviews ? "pull_request" : "push");
const issue = event === "issue" || event === "issue_comment";
const pullRequest = event === "pull_request";
logVerbose(`event: ${event}`);
const prj = await buildProject(); // Build the project to get script templates
let script = prj.scripts.find(
(t) =>
t.id === scriptId ||
(t.filename && GENAI_ANY_REGEX.test(scriptId) && resolve(t.filename) === resolve(scriptId)),
);
if (!script) {
script = coreCreateScript(scriptId);
script.id = scriptId;
script.filename = resolve(out, GENAI_SRC, templateIdFromFileName(scriptId) + ".genai.mts");
// Write the prompt script to the determined path
await writeFile(script.filename, script.jsSource);
}
const accept = script.accept;
const ffmpeg = options.ffmpeg || /ffmpeg$/.test(script.jsSource);
const playwright = options.playwright || /host\.browser/.test(script.jsSource);
const python = options.python;
const image =
options.image ||
(playwright ? "mcr.microsoft.com/playwright:v1.52.0-noble" : "node:lts-alpine");
const alpine = /alpine$/.test(image);
logVerbose(`script: ${script.filename}`);
logVerbose(`docker image: ${image}`);
logVerbose(`ffmpeg: ${ffmpeg}`);
logVerbose(`python: ${python}`);
logVerbose(`playwright: ${playwright}`);
const { inputSchema, branding } = script;
const scriptSchema = (inputSchema?.properties.script as JSONSchemaObject) || {
type: "object",
properties: {},
required: [],
};
const inputs: Record<string, GitHubActionFieldType> = deleteUndefinedValues({
...Object.fromEntries(
Object.entries(scriptSchema.properties).map(([key, value]) => {
return [
snakeCase(key),
{
description: (value as JSONSchemaDescribed).description || "",
required: scriptSchema.required?.includes(key) || false,
default: (value as JSONSchemaString).default ?? undefined,
} satisfies GitHubActionFieldType,
];
}),
),
files:
accept === "none"
? undefined
: {
description: `Files to process, separated by semi columns (;). ${accept || ""}`,
required: false,
},
github_token: {
description:
"GitHub token with `models: read` permission at least (https://microsoft.github.io/genaiscript/reference/github-actions/#github-models-permissions).",
required: true,
},
github_issue:
issue || pullRequest
? {
description: `GitHub ${issue ? "issue" : "pull request"} number to use when generating comments (https://microsoft.github.io/genaiscript/reference/scripts/github/).`,
}
: undefined,
debug: {
description:
"Enable debug logging (https://microsoft.github.io/genaiscript/reference/scripts/logging/).",
required: false,
},
});
let outputs: Record<string, GitHubActionFieldType> = deleteUndefinedValues({
text: {
description: "The generated text output.",
},
data: script.responseSchema
? {
description: "The generated data output, parsed and stringified as JSON.",
}
: undefined,
});
if (!Object.keys(outputs).length) outputs = undefined;
const pkg = await nodeTryReadPackage();
const apks = [
"git",
"github-cli",
python ? "python3" : undefined,
python ? "py3-pip" : undefined,
ffmpeg ? "ffmpeg" : undefined,
...(options.apks || []),
].filter(Boolean);
const actionYmlFilename = resolve(out, "action.yml");
const action = YAMLTryParse(await tryReadText(actionYmlFilename)) as {
description?: string;
inputs?: Record<string, GitHubActionFieldType>;
outputs?: Record<string, GitHubActionFieldType>;
branding?: Record<string, unknown>;
};
if (action && !force) {
logVerbose(`updating action.yml`);
action.description = script.description || pkg?.description;
action.inputs = inputs;
action.outputs = outputs;
action.branding = branding;
await writeText(actionYmlFilename, YAMLStringify(action));
} else
await writeFile(
"action.yml",
YAMLStringify(
deleteEmptyValues({
name: repo,
author: pkg?.author,
description: script.title || pkg?.description,
inputs,
outputs,
branding,
runs: {
using: "docker",
image: "Dockerfile",
},
}),
),
);
await writeFile(
"Dockerfile",
dedent`# For additional guidance on containerized actions, see https://docs.github.com/en/actions/sharing-automations/creating-actions/creating-a-docker-container-action
FROM ${image}
# Install packages
${alpine ? `RUN apk add --no-cache ${apks.join(" ")}` : `RUN apt-get update && apt-get install -y ${apks.join(" ")}`}
# Set working directory
WORKDIR /genaiscript/action
# Copy source code
COPY . .
# Install dependencies
RUN npm ci
${
playwright
? dedent`# Install playwright dependencies
RUN npx --yes playwright install --with-deps chromium
`
: ""
}
# GitHub Action forces the WORKDIR to GITHUB_WORKSPACE
ENTRYPOINT ["npm", "--prefix", "/genaiscript/action", "start"]
`,
);
await writeFile(
"README.md",
dedent`# ${script.title || titleize(repo)}
${script.description || ""}
## Inputs
${Object.entries(inputs || {})
.map(
([key, value]) =>
`- \`${key}\`: ${value.description}${
value.required ? " (required)" : ""
}${value.default ? ` (default: \`${value.default}\`)` : ""}`,
)
.join("\n")}
${
outputs
? `## Outputs
${Object.entries(outputs)
.map(([key, value]) => `- \`${key}\`: ${value.description || ""}`)
.join("\n")}
`
: ""
}
## Usage
Add the following to your step in your workflow file:
\`\`\`yaml
uses: ${owner}/${repo}@main
with:
${Object.entries(inputs || {})
.filter(([, value]) => value.required)
.map(([key]) => ` ${key}: \${{ ${key === "github_token" ? "secrets.GITHUB_TOKEN" : "..."} }}`)
.join("\n")}
\`\`\`
## Example
Save this file in your \`.github/workflows/\` directory as \`${script.id}.yml\`:
\`\`\`yaml
name: ${titleize(repo)}
on:
${event}:
permissions:
contents: read
${!issue ? "# " : ""}issues: write
${event !== "pull_request" ? "# " : ""}pull-requests: write
models: read
concurrency:
group: \${{ github.workflow }}-\${{ github.ref }}
cancel-in-progress: true
jobs:
${snakeCase(repo)}:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ${owner}/${repo}@main
with:
${Object.entries(inputs || {})
.filter(([, value]) => value.required)
.map(
([key]) =>
` ${key}: \${{ ${key === "github_token" ? "secrets.GITHUB_TOKEN" : "..."} }}`,
)
.join("\n")}
\`\`\`
## Development
This action was automatically generated by GenAIScript from the script metadata.
We recommend updating the script metadata instead of editing the action files directly.
- the action inputs are inferred from the script parameters
- the action outputs are inferred from the script output schema
- the action description is the script description
- the readme description is the script description
- the action branding is the script branding
To **regenerate** the action files (\`action.yml\`), run:
\`\`\`bash
npm run configure
\`\`\`
To lint script files, run:
\`\`\`bash
npm run lint
\`\`\`
To typecheck the scripts, run:
\`\`\`bash
npm run typecheck
\`\`\`
To build the Docker image locally, run:
\`\`\`bash
npm run docker:build
\`\`\`
To run the action locally in Docker (build it first), use:
\`\`\`bash
npm run docker:start
\`\`\`
To run the action using [act](https://nektosact.com/), first install the act CLI:
\`\`\`bash
npm run act:install
\`\`\`
Then, you can run the action with:
\`\`\`bash
npm run act
\`\`\`
## Upgrade
The GenAIScript version is pinned in the \`package.json\` file. To upgrade it, run:
\`\`\`bash
npm run upgrade
\`\`\`
## Release
To release a new version of this action, run the release script on a clean working directory.
\`\`\`bash
npm run release
\`\`\`
`,
);
await writeFile(
".devcontainer/devcontainer.json",
JSON.stringify(
{
name: "GenAIScript GitHub Action Dev Container",
build: {
dockerfile: "Dockerfile",
},
features: {},
customizations: {
vscode: {
settings: {
"terminal.integrated.defaultProfile.linux": "ash",
"terminal.integrated.profiles.linux": {
ash: {
path: "/bin/ash",
args: ["-l"],
},
},
},
extensions: [
"GitHub.vscode-github-actions",
"esbenp.prettier-vscode",
"GitHub.copilot-chat",
"genaiscript.genaiscript-vscode",
],
},
},
postCreateCommand: 'git config --global --add safe.directory "$(pwd)" && npm ci',
},
null,
2,
),
);
await writeFile(
".devcontainer/Dockerfile",
dedent`# Keep this Dockerfile in sync with the main Dockerfile
FROM ${image}
# Install packages
${alpine ? `RUN apk add --no-cache ${apks.join(" ")}` : `RUN apt-get update && apt-get install -y ${apks.join(" ")}`}
`,
);
await writeFile(".nvmrc", "lts/*");
await writeFile(
"release.sh",
dedent`#!/bin/bash
set -e # exit immediately if a command exits with a non-zero status
# make sure there's no other changes
git pull
# re-generate action.yml
npm run configure
# Lint and build
npm run lint
# Step 0: ensure we're in sync
if [ "$(git status --porcelain)" ]; then
echo "❌ Pending changes detected. Commit or stash them first."
exit 1
fi
# typecheck test
npm run typecheck
# Step 1: Bump patch version using npm
NEW_VERSION=$(npm version patch -m "chore: bump version to %s")
echo "version: $NEW_VERSION"
# Step 2: Push commit and tag
git push origin HEAD --tags
# Step 3: Create GitHub release
gh release create "$NEW_VERSION" --title "$NEW_VERSION" --notes "Patch release $NEW_VERSION"
# Step 4: update major tag if any
MAJOR=$(echo "$NEW_VERSION" | cut -d. -f1)
echo "major: $MAJOR"
git tag -f $MAJOR $NEW_VERSION
git push origin $MAJOR --force
echo "✅ GitHub release $NEW_VERSION created successfully."
`,
);
await writeFile(
".github/workflows/ci.yml",
`name: Continuous Integration
on:
pull_request:
branches:
- main
push:
branches:
- main
permissions:
contents: read
models: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
cache: npm
- run: npm ci
- run: npm test
test-action:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./
with:
github_token: \${{ secrets.GITHUB_TOKEN }}
`,
);
if (!pkg || force) {
const args = [
`genaiscript`,
`run`,
scriptId,
provider ? `--provider` : undefined,
provider,
pullRequestComment ? `--pull-request-comment` : undefined,
typeof pullRequestComment === "string" ? pullRequestComment : undefined,
pullRequestDescription ? `--pull-request-description` : undefined,
typeof pullRequestDescription === "string" ? pullRequestDescription : undefined,
pullRequestReviews ? `--pull-request-reviews` : undefined,
].filter(Boolean);
await writeFile(
"package.json",
JSON.stringify(
deleteUndefinedValues({
private: true,
version: "0.0.0",
author: pkg?.author,
license: pkg?.license,
description: script.description,
dependencies: {
...(pkg?.dependencies || {}),
genaiscript: CORE_VERSION,
},
scripts: {
upgrade: "npx -y npm-check-updates -u && npm install && npm run fix",
"docker:build": `docker build -t ${owner}-${repo} .`,
"docker:start": `docker run -e GITHUB_TOKEN ${owner}-${repo}`,
"act:install": "gh extension install https://github.com/nektos/gh-act",
act: "gh act",
lint: `npx --yes prettier --write genaisrc/`,
fix: "genaiscript scripts fix",
typecheck: `genaiscript scripts compile`,
configure: [`genaiscript configure action`, scriptId, `--interactive`]
.filter(Boolean)
.join(" "),
test: "echo 'No tests defined.'",
dev: args.join(" "),
start: [...args, "--github-workspace", "--no-run-trace", "--no-output-trace"].join(" "),
release: "sh release.sh",
},
}),
null,
2,
),
);
}
// upgrade dependencies
await runtimeHost.exec(undefined, "node", ["run", "upgrade"], {
cwd: out,
});
}