@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.17

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 (120) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +332 -5
  4. package/src/deep-scan/docker-driver.mjs +70 -3
  5. package/src/deep-scan/lifecycle.mjs +2 -2
  6. package/src/deep-scan/sbx-driver.mjs +34 -47
  7. package/src/doctor.mjs +53 -1
  8. package/src/exec.mjs +18 -5
  9. package/src/factory/budget/budget.mjs +260 -0
  10. package/src/factory/build/command.mjs +321 -0
  11. package/src/factory/build/factory.mjs +473 -0
  12. package/src/factory/build/findings.mjs +55 -0
  13. package/src/factory/build/host.mjs +230 -0
  14. package/src/factory/build/notes.mjs +191 -0
  15. package/src/factory/build/pull-request.mjs +74 -0
  16. package/src/factory/bundle.mjs +146 -0
  17. package/src/factory/checks/allowed-paths.mjs +50 -0
  18. package/src/factory/checks/plan-header.mjs +296 -0
  19. package/src/factory/checks/qa.mjs +85 -0
  20. package/src/factory/checks/review.mjs +73 -0
  21. package/src/factory/checks/security.mjs +50 -0
  22. package/src/factory/checks/stage-check.mjs +89 -0
  23. package/src/factory/claims/command.mjs +187 -0
  24. package/src/factory/claims/release.mjs +111 -0
  25. package/src/factory/decision/answers.mjs +103 -0
  26. package/src/factory/decision/command.mjs +64 -0
  27. package/src/factory/decision/plan.mjs +99 -0
  28. package/src/factory/decision/request.mjs +116 -0
  29. package/src/factory/doctor/files.mjs +349 -0
  30. package/src/factory/doctor/index.mjs +56 -0
  31. package/src/factory/doctor/local.mjs +513 -0
  32. package/src/factory/doctor/orchestrate.mjs +146 -0
  33. package/src/factory/engine/lease.mjs +146 -0
  34. package/src/factory/engine/local-engine.mjs +177 -0
  35. package/src/factory/engine/lockfile.mjs +64 -0
  36. package/src/factory/engine/workflow-engine.mjs +124 -0
  37. package/src/factory/gate/comment.mjs +88 -0
  38. package/src/factory/gate/config.mjs +57 -0
  39. package/src/factory/gate/gate-core.mjs +250 -0
  40. package/src/factory/gate/guarded.mjs +17 -0
  41. package/src/factory/gate/reads.mjs +105 -0
  42. package/src/factory/gate/task.mjs +193 -0
  43. package/src/factory/gate/trip-reads.mjs +82 -0
  44. package/src/factory/gate/trip.mjs +87 -0
  45. package/src/factory/init/blueprint.mjs +181 -0
  46. package/src/factory/init/index.mjs +338 -0
  47. package/src/factory/labels/evidence.mjs +162 -0
  48. package/src/factory/labels/moves.mjs +32 -0
  49. package/src/factory/labels/reconcile.mjs +267 -0
  50. package/src/factory/labels/revert.mjs +87 -0
  51. package/src/factory/labels/timeline.mjs +72 -0
  52. package/src/factory/labels/voided.mjs +59 -0
  53. package/src/factory/limits/harness.mjs +39 -0
  54. package/src/factory/limits/limits.mjs +131 -0
  55. package/src/factory/merge/command.mjs +172 -0
  56. package/src/factory/outbox/check.mjs +240 -0
  57. package/src/factory/outbox/rulings.mjs +195 -0
  58. package/src/factory/plan/command.mjs +66 -0
  59. package/src/factory/plan/comment.mjs +156 -0
  60. package/src/factory/plan/publish.mjs +149 -0
  61. package/src/factory/plan/risk.mjs +153 -0
  62. package/src/factory/qa/command.mjs +301 -0
  63. package/src/factory/qa/decide.mjs +86 -0
  64. package/src/factory/qa/report.mjs +50 -0
  65. package/src/factory/records/engine-record.mjs +133 -0
  66. package/src/factory/records/main.mjs +96 -0
  67. package/src/factory/records/record.mjs +226 -0
  68. package/src/factory/records/sink.mjs +57 -0
  69. package/src/factory/report/build.mjs +92 -0
  70. package/src/factory/report/command.mjs +80 -0
  71. package/src/factory/report/facts.mjs +226 -0
  72. package/src/factory/report/gate-section.mjs +122 -0
  73. package/src/factory/report/metrics.mjs +111 -0
  74. package/src/factory/report/reads.mjs +246 -0
  75. package/src/factory/report/render.mjs +121 -0
  76. package/src/factory/report/rollout.mjs +154 -0
  77. package/src/factory/review/brief.mjs +195 -0
  78. package/src/factory/review/command.mjs +182 -0
  79. package/src/factory/run/awake.mjs +70 -0
  80. package/src/factory/run/collect.mjs +77 -0
  81. package/src/factory/run/command.mjs +556 -0
  82. package/src/factory/run/gh.mjs +46 -0
  83. package/src/factory/run/launch.mjs +66 -0
  84. package/src/factory/run/pipelines.mjs +694 -0
  85. package/src/factory/run/raw.mjs +96 -0
  86. package/src/factory/run/restart.mjs +83 -0
  87. package/src/factory/run/s3.mjs +193 -0
  88. package/src/factory/run/secrets.mjs +142 -0
  89. package/src/factory/run/teardown.mjs +242 -0
  90. package/src/factory/run/token.mjs +70 -0
  91. package/src/factory/run/worktree.mjs +160 -0
  92. package/src/factory/security/audit.mjs +353 -0
  93. package/src/factory/security/command.mjs +157 -0
  94. package/src/factory/setup/app.mjs +122 -0
  95. package/src/factory/setup/command.mjs +472 -0
  96. package/src/factory/setup/labels.mjs +25 -0
  97. package/src/factory/setup/reads.mjs +159 -0
  98. package/src/factory/setup/writes.mjs +138 -0
  99. package/src/factory/snapshot/write.mjs +176 -0
  100. package/src/factory/stop/command.mjs +136 -0
  101. package/src/factory/sweep/actions-main.mjs +119 -0
  102. package/src/factory/sweep/command.mjs +65 -0
  103. package/src/factory/sweep/knobs.mjs +78 -0
  104. package/src/factory/sweep/marker-version.mjs +15 -0
  105. package/src/factory/sweep/markers.mjs +112 -0
  106. package/src/factory/sweep/overlap.mjs +24 -0
  107. package/src/factory/sweep/run.mjs +198 -0
  108. package/src/factory/sweep/shell.mjs +398 -0
  109. package/src/factory/sweep/split.mjs +104 -0
  110. package/src/factory/sweep/states.mjs +87 -0
  111. package/src/factory/sweep/sweep-core.mjs +2009 -0
  112. package/src/factory/tracker/github.mjs +713 -0
  113. package/src/factory/tracker/operations.mjs +153 -0
  114. package/src/factory/upgrade/index.mjs +83 -0
  115. package/src/init.mjs +62 -24
  116. package/src/kit-owned-paths.mjs +1 -1
  117. package/src/stage/build.mjs +100 -0
  118. package/src/stage/factory-live.mjs +288 -0
  119. package/src/stage.mjs +100 -4
  120. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,96 @@
1
+ // The raw-folder upload (#523, ADR 0021): a collected run folder goes to the S3
2
+ // raw-folder Sink only when `--upload-raw` was given at engine start, only to a bucket
3
+ // that answers a signed request and refuses an unsigned listing, and only after the
4
+ // bucket's own lifecycle has an enabled rule that expires all of `raw/`. The security
5
+ // Stage never uploads. Text files only (a bundle or other binary is named and left on
6
+ // the machine); a link is never followed. Objects are created, never overwritten, at
7
+ // `raw/<host>/<owner>/<repo>/<login>/<run id>/<path>`, every segment lowercased.
8
+
9
+ import { join } from "node:path";
10
+
11
+ import { rawExpiry } from "./s3.mjs";
12
+
13
+ const SEGMENT = /^[a-z0-9][a-z0-9._-]*$/;
14
+
15
+ /** The raw prefix of one run, or null when a segment is not plain. */
16
+ export function rawPrefixOf({ repo, login, runId }) {
17
+ const segments = [...String(repo).split("/"), login, runId].map((s) => String(s).toLowerCase());
18
+ return segments.length === 5 && segments.every((s) => SEGMENT.test(s))
19
+ ? `raw/${segments.join("/")}/`
20
+ : null;
21
+ }
22
+
23
+ /** Every regular file under `dir` as `{path, text}`, plus the links and binaries it skipped. */
24
+ export function readFolder({ fs, dir }) {
25
+ const files = [];
26
+ const links = [];
27
+ const binary = [];
28
+ const walk = (at, rel) => {
29
+ for (const entry of fs.readdirSync(at, { withFileTypes: true })) {
30
+ const path = `${rel}${entry.name}`;
31
+ if (entry.isSymbolicLink()) links.push(path);
32
+ else if (entry.isDirectory()) walk(join(at, entry.name), `${path}/`);
33
+ else if (entry.isFile()) {
34
+ const bytes = fs.readFileSync(join(at, entry.name));
35
+ const text = Buffer.from(bytes).toString("utf8");
36
+ if (Buffer.from(text, "utf8").equals(Buffer.from(bytes))) files.push({ path, text });
37
+ else binary.push(path);
38
+ }
39
+ }
40
+ };
41
+ walk(dir, "");
42
+ files.sort((a, b) => (a.path < b.path ? -1 : 1));
43
+ return { files, links, binary };
44
+ }
45
+
46
+ /**
47
+ * Uploads one collected run folder. Never throws; the result says what happened and holds
48
+ * no key. Nothing is put until the privacy and lifecycle checks have passed.
49
+ *
50
+ * @returns {Promise<{status: "uploaded" | "skipped" | "refused", detail?: string, files?: number}>}
51
+ */
52
+ export async function uploadRawFolder({ s3, fs, dir, repo, login, runId, stage, log = () => {} }) {
53
+ if (stage === "security")
54
+ return { status: "skipped", detail: "a security transcript never goes to the raw-folder Sink" };
55
+ const prefix = rawPrefixOf({ repo, login, runId });
56
+ if (prefix === null) return { status: "refused", detail: "the run's name is not plain" };
57
+ let tree;
58
+ try {
59
+ tree = readFolder({ fs, dir });
60
+ } catch {
61
+ return { status: "refused", detail: "the run folder could not be read" };
62
+ }
63
+ const privacy = await s3.privacy();
64
+ if (privacy.private !== true)
65
+ return {
66
+ status: "refused",
67
+ detail:
68
+ privacy.private === false
69
+ ? "the bucket is not private"
70
+ : "the bucket's privacy could not be read",
71
+ };
72
+ const lifecycle = await s3.lifecycle();
73
+ if (lifecycle.status !== "found")
74
+ return {
75
+ status: "refused",
76
+ detail:
77
+ lifecycle.status === "missing"
78
+ ? "the bucket has no lifecycle rule"
79
+ : `the bucket's lifecycle could not be read (${lifecycle.detail})`,
80
+ };
81
+ if (rawExpiry(lifecycle.xml) === null)
82
+ return { status: "refused", detail: "no enabled lifecycle rule expires raw/" };
83
+ if (tree.binary.length)
84
+ log(`raw upload: ${tree.binary.length} non-text file(s) stay on the machine`);
85
+ if (tree.links.length) log(`raw upload: ${tree.links.length} link(s) were not followed`);
86
+ let sent = 0;
87
+ for (const file of tree.files) {
88
+ const done = await s3.createOnly(`${prefix}${file.path}`, file.text);
89
+ if (done.status === "error")
90
+ return { status: "refused", detail: `a write failed (${done.detail})`, files: sent };
91
+ if (done.status === "different")
92
+ return { status: "refused", detail: "different bytes are already there", files: sent };
93
+ sent += 1;
94
+ }
95
+ return { status: "uploaded", files: sent };
96
+ }
@@ -0,0 +1,83 @@
1
+ // What the engine cleans up when it starts and when it stops (ADR 0039): the Launcher's
2
+ // sandboxes it left behind, and its own open Claims. Everything is recovered from the
3
+ // tracker and the container runtime alone.
4
+ //
5
+ // - Sandboxes: every Docker resource the Launcher labels `agent-kit.deep-scan`
6
+ // (containers, networks, volumes). One engine runs per repository and the Launcher
7
+ // labels no sandbox by engine, so this is every Launcher sandbox on the machine:
8
+ // do not run `deep-scan` beside the engine.
9
+ // - Claims: a live Claim of this engine's name, written as its identity, is released
10
+ // with a reason: `engine-restart` at start (read by the sweep as an `error`, one free
11
+ // retry) and `stopped` at a drain (never an Attempt).
12
+
13
+ import { claimsOf } from "../sweep/sweep-core.mjs";
14
+
15
+ const LABEL = "agent-kit.deep-scan";
16
+
17
+ /** Removes the labelled sandboxes; returns what it removed. Absent Docker is not a failure. */
18
+ export function removeSandboxes({ runner, log }) {
19
+ const removed = [];
20
+ for (const [list, remove, what] of [
21
+ [["ps", "-aq", "--filter", `label=${LABEL}`], ["rm", "-f"], "container"],
22
+ [["network", "ls", "-q", "--filter", `label=${LABEL}`], ["network", "rm"], "network"],
23
+ [["volume", "ls", "-q", "--filter", `label=${LABEL}`], ["volume", "rm", "-f"], "volume"],
24
+ ]) {
25
+ const listed = runner("docker", list);
26
+ if (listed.status !== 0) {
27
+ if (what === "container" && listed.status !== null) {
28
+ log(`restart: no sandboxes read (docker ${list[0]} exited ${listed.status})`);
29
+ }
30
+ return removed;
31
+ }
32
+ const ids = String(listed.stdout)
33
+ .split(/\s+/)
34
+ .filter((id) => /^[A-Za-z0-9_.-]+$/.test(id));
35
+ if (!ids.length) continue;
36
+ const result = runner("docker", [...remove, ...ids]);
37
+ if (result.status === 0) removed.push(...ids.map((id) => `${what} ${id}`));
38
+ else log(`restart: could not remove ${what}s: ${String(result.stderr).trim().slice(0, 160)}`);
39
+ }
40
+ if (removed.length) log(`restart: removed ${removed.length} labelled sandbox resources`);
41
+ return removed;
42
+ }
43
+
44
+ /**
45
+ * Releases this engine's live Claims. `only(claim)` narrows them (a drain spares the
46
+ * Claims of runs that finished). Returns `[{ issue, claim, state }]` of those released.
47
+ */
48
+ export function releaseOwnClaims({ tracker, engine, reason, only = () => true, log }) {
49
+ const released = [];
50
+ const read = tracker.readState();
51
+ for (const issue of read.issues ?? []) {
52
+ for (const claim of claimsOf(issue, engine)) {
53
+ if (claim.released !== undefined || claim.voided || !only(claim)) continue;
54
+ try {
55
+ tracker.release(claim.commentId, reason);
56
+ released.push({
57
+ issue: issue.number,
58
+ claim: claim.claim,
59
+ stage: claim.stage,
60
+ attempt: claim.attempt,
61
+ labels: issue.labels ?? [],
62
+ });
63
+ } catch (error) {
64
+ log(`#${issue.number} could not release Claim ${claim.claim}: ${error.message}`);
65
+ }
66
+ }
67
+ }
68
+ return released;
69
+ }
70
+
71
+ /** The drain's move back: `planning` to `queued` and `building` to `planned`. */
72
+ export function moveBack({ tracker, released, log }) {
73
+ const back = { planning: "queued", building: "planned" };
74
+ for (const { issue, labels } of released) {
75
+ const from = Object.keys(back).find((s) => labels.includes(`factory:${s}`));
76
+ if (!from) continue;
77
+ try {
78
+ tracker.setState(issue, from, back[from]);
79
+ } catch (error) {
80
+ log(`#${issue} could not move back to ${back[from]}: ${error.message}`);
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,193 @@
1
+ // The S3 raw-folder Sink's client (#523): SigV4-signed, path-style requests over an
2
+ // injected `fetch`, mirroring the orchestrate skill's `signRequest` and `s3Sink`
3
+ // (.claude/skills/orchestrate/records.mjs), which the published CLI cannot import.
4
+ // It reads the bucket's privacy and lifecycle and creates objects, never over an
5
+ // existing one, and never writes bucket configuration. The key pair is held in this
6
+ // closure only: it is never in a log line, an error, a result or a record.
7
+
8
+ import { createHash, createHmac } from "node:crypto";
9
+
10
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
11
+ const hmac = (key, data) => createHmac("sha256", key).update(data).digest();
12
+ const uriEncode = (text) =>
13
+ encodeURIComponent(text).replace(
14
+ /[!'()*]/g,
15
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
16
+ );
17
+
18
+ /** One request signed with AWS Signature Version 4; returns the headers to send (never `host`). */
19
+ export function signRequest({
20
+ method,
21
+ url,
22
+ headers = {},
23
+ body = "",
24
+ region,
25
+ service = "s3",
26
+ accessKeyId,
27
+ secretAccessKey,
28
+ now,
29
+ }) {
30
+ const target = new URL(url);
31
+ const stamp = now.toISOString().replace(/[-:]|\.\d+/g, "");
32
+ const day = stamp.slice(0, 8);
33
+ const payload = sha256(body);
34
+ const all = { host: target.host, "x-amz-date": stamp, "x-amz-content-sha256": payload };
35
+ for (const [name, value] of Object.entries(headers))
36
+ all[name.toLowerCase()] = String(value).trim().replace(/\s+/g, " ");
37
+ const names = Object.keys(all).sort();
38
+ const path = target.pathname
39
+ .split("/")
40
+ .map((segment) => uriEncode(decodeURIComponent(segment)))
41
+ .join("/");
42
+ const query = [...target.searchParams]
43
+ .map(([k, v]) => [uriEncode(k), uriEncode(v)])
44
+ .sort(([a, x], [b, y]) => (a === b ? (x < y ? -1 : x > y ? 1 : 0) : a < b ? -1 : 1))
45
+ .map(([k, v]) => `${k}=${v}`)
46
+ .join("&");
47
+ const signedHeaders = names.join(";");
48
+ const canonicalRequest = [
49
+ method,
50
+ path,
51
+ query,
52
+ ...names.map((name) => `${name}:${all[name]}`),
53
+ "",
54
+ signedHeaders,
55
+ payload,
56
+ ].join("\n");
57
+ const scope = `${day}/${region}/${service}/aws4_request`;
58
+ const stringToSign = ["AWS4-HMAC-SHA256", stamp, scope, sha256(canonicalRequest)].join("\n");
59
+ const key = [day, region, service, "aws4_request"].reduce(
60
+ (k, part) => hmac(k, part),
61
+ `AWS4${secretAccessKey}`,
62
+ );
63
+ const signature = createHmac("sha256", key).update(stringToSign).digest("hex");
64
+ const { host: _host, ...send } = all;
65
+ return {
66
+ headers: {
67
+ ...send,
68
+ authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
69
+ },
70
+ };
71
+ }
72
+
73
+ const RAW_ROOT = "raw/";
74
+ const xmlText = (text) =>
75
+ text
76
+ .replace(/&lt;/g, "<")
77
+ .replace(/&gt;/g, ">")
78
+ .replace(/&quot;/g, '"')
79
+ .replace(/&apos;/g, "'")
80
+ .replace(/&amp;/g, "&");
81
+ const s3Code = (text) => /<Code>([A-Za-z0-9]+)<\/Code>/.exec(text)?.[1] ?? null;
82
+
83
+ /**
84
+ * The days after which the bucket's own lifecycle deletes everything under `raw/`; null
85
+ * when no rule does. A rule counts only when it is enabled, expires by age, and covers
86
+ * all of `raw/` (no prefix, or one `raw/` starts with); a tag or size filter reaches only
87
+ * some objects and does not count. Of several covering rules the shortest is quoted.
88
+ */
89
+ export function rawExpiry(xml) {
90
+ let days = null;
91
+ for (const [, rule] of String(xml).matchAll(/<Rule>([\s\S]*?)<\/Rule>/g)) {
92
+ if (!/<Status>\s*Enabled\s*<\/Status>/.test(rule)) continue;
93
+ const after = /<Expiration>[\s\S]*?<Days>\s*(\d+)\s*<\/Days>[\s\S]*?<\/Expiration>/.exec(rule);
94
+ const n = after ? Number(after[1]) : 0;
95
+ if (!(n >= 1)) continue;
96
+ const filter = /<Filter>([\s\S]*?)<\/Filter>/.exec(rule)?.[1] ?? null;
97
+ if (filter !== null && /<Tag>|<ObjectSize/.test(filter)) continue;
98
+ const prefix =
99
+ /<Prefix>([\s\S]*?)<\/Prefix>/.exec(
100
+ filter ?? rule.replace(/<Expiration>[\s\S]*?<\/Expiration>/, ""),
101
+ )?.[1] ?? "";
102
+ if (!RAW_ROOT.startsWith(xmlText(prefix))) continue;
103
+ days = days === null ? n : Math.min(days, n);
104
+ }
105
+ return days === null ? null : { days };
106
+ }
107
+
108
+ /**
109
+ * @param {{ endpoint: string, bucket: string, region: string, accessKeyId: string, secretAccessKey: string,
110
+ * fetch: Function, now?: () => Date }} deps
111
+ */
112
+ export function createS3({
113
+ endpoint,
114
+ bucket,
115
+ region,
116
+ accessKeyId,
117
+ secretAccessKey,
118
+ fetch,
119
+ now = () => new Date(),
120
+ }) {
121
+ const base = String(endpoint).replace(/\/+$/, "");
122
+ const url = (key, query = {}) => {
123
+ const path = `/${[bucket, ...(key ? key.split("/") : [])].map(uriEncode).join("/")}`;
124
+ const text = Object.entries(query)
125
+ .map(([k, v]) => `${uriEncode(k)}=${uriEncode(String(v))}`)
126
+ .join("&");
127
+ return `${base}${path}${text ? `?${text}` : ""}`;
128
+ };
129
+ const request = async (method, key, { query, headers = {}, body = "", signed = true } = {}) => {
130
+ const target = url(key, query);
131
+ const send = signed
132
+ ? signRequest({
133
+ method,
134
+ url: target,
135
+ headers,
136
+ body,
137
+ region,
138
+ accessKeyId,
139
+ secretAccessKey,
140
+ now: now(),
141
+ }).headers
142
+ : { ...headers };
143
+ try {
144
+ const response = await fetch(target, {
145
+ method,
146
+ headers: send,
147
+ ...(body === "" ? {} : { body }),
148
+ });
149
+ return { status: response.status, text: await response.text() };
150
+ } catch (error) {
151
+ return { status: 0, text: "", detail: error?.name ?? "error" };
152
+ }
153
+ };
154
+ const detail = (r) =>
155
+ r.status === 0
156
+ ? `the request failed (${r.detail})`
157
+ : `HTTP ${r.status}${s3Code(r.text) ? ` ${s3Code(r.text)}` : ""}`;
158
+ return {
159
+ /** Private when a signed HEAD answers and an unsigned listing is refused. */
160
+ async privacy() {
161
+ const head = await request("HEAD", "");
162
+ if (head.status !== 200) return { private: null };
163
+ const stranger = await request("GET", "", {
164
+ query: { "list-type": 2, "max-keys": 1 },
165
+ signed: false,
166
+ });
167
+ if (stranger.status === 200) return { private: false };
168
+ return { private: stranger.status === 401 || stranger.status === 403 ? true : null };
169
+ },
170
+ async lifecycle() {
171
+ const r = await request("GET", "", { query: { lifecycle: "" } });
172
+ if (r.status === 200) return { status: "found", xml: r.text };
173
+ return r.status === 404 ? { status: "missing" } : { status: "error", detail: detail(r) };
174
+ },
175
+ /** Creates the object, never over one: identical bytes there are `already`, different stop. */
176
+ async createOnly(key, text) {
177
+ const there = await request("GET", key);
178
+ if (there.status === 200) return { status: there.text === text ? "already" : "different" };
179
+ if (there.status !== 404) return { status: "error", detail: detail(there) };
180
+ const made = await request("PUT", key, {
181
+ headers: { "content-type": "application/octet-stream", "if-none-match": "*" },
182
+ body: text,
183
+ });
184
+ if (made.status >= 200 && made.status < 300) return { status: "created" };
185
+ if (made.status === 412) {
186
+ // Someone created it between the read and the write: the bytes there decide.
187
+ const again = await request("GET", key);
188
+ if (again.status === 200) return { status: again.text === text ? "already" : "different" };
189
+ }
190
+ return { status: "error", detail: detail(made) };
191
+ },
192
+ };
193
+ }
@@ -0,0 +1,142 @@
1
+ // The engine's secrets, read once into memory (ADR 0039): the GitHub PAT from
2
+ // `AGENT_KIT_GITHUB_TOKEN`, a literal or an `op://` reference read with `op read`
3
+ // (never `gh auth token`), and the model keys from the harnesses' own variables, each
4
+ // likewise. Nothing is written to a file or an argument. A missing secret is a refusal
5
+ // that names its cause.
6
+
7
+ import { CREDENTIAL_VARS } from "../../deep-scan/credential.mjs";
8
+ import { firstLine } from "../../exec.mjs";
9
+
10
+ export const TOKEN_VAR = "AGENT_KIT_GITHUB_TOKEN";
11
+
12
+ function resolve(name, value, runner) {
13
+ if (!String(value).startsWith("op://")) return { value };
14
+ const read = runner("op", ["read", "--no-newline", String(value)]);
15
+ if (read.status !== 0) {
16
+ return {
17
+ refused: `${name} is a 1Password reference that op read could not resolve: ${firstLine(read.stderr) || `exit ${read.status}`}`,
18
+ };
19
+ }
20
+ return { value: String(read.stdout).replace(/\r?\n$/, "") };
21
+ }
22
+
23
+ /**
24
+ * @param {{ env: Record<string, string | undefined>, runner: Function }} deps
25
+ * @returns {{ token: string, modelEnv: Record<string, string> } | { refused: string }}
26
+ */
27
+ export function readSecrets({ env, runner }) {
28
+ const raw = env[TOKEN_VAR];
29
+ if (raw === undefined || raw === "") {
30
+ return {
31
+ refused: `${TOKEN_VAR} is not set: the engine needs a fine-grained, one-repository GitHub token (a literal or an op:// reference). It never uses gh auth token.`,
32
+ };
33
+ }
34
+ const token = resolve(TOKEN_VAR, raw, runner);
35
+ if (token.refused) return { refused: token.refused };
36
+ if (!token.value || !/^[\x21-\x7e]+$/.test(token.value)) {
37
+ return { refused: `${TOKEN_VAR} is empty or not a token (its value is not shown).` };
38
+ }
39
+ const modelEnv = {};
40
+ for (const name of CREDENTIAL_VARS) {
41
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
42
+ if (key === undefined || env[key] === "") continue;
43
+ const got = resolve(name, env[key], runner);
44
+ if (got.refused) return { refused: got.refused };
45
+ modelEnv[name] = got.value;
46
+ }
47
+ if (Object.keys(modelEnv).length === 0) {
48
+ return {
49
+ refused: `no model credential: set one of ${CREDENTIAL_VARS.join(", ")} (a key or an op:// reference). It stays in the engine's memory and reaches only the model proxy.`,
50
+ };
51
+ }
52
+ return { token: token.value, modelEnv };
53
+ }
54
+
55
+ export const RECORDS_SINK_VAR = "AGENT_KIT_RECORDS_SINK";
56
+ export const RECORDS_TOKEN_VAR = "AGENT_KIT_RECORDS_TOKEN";
57
+ export const S3_KEY_ID_VAR = "ORCHESTRATE_S3_ACCESS_KEY_ID";
58
+ export const S3_SECRET_VAR = "ORCHESTRATE_S3_SECRET_ACCESS_KEY";
59
+ const RAW_VARS = Object.freeze({
60
+ endpoint: "AGENT_KIT_RAW_SINK_ENDPOINT",
61
+ bucket: "AGENT_KIT_RAW_SINK_BUCKET",
62
+ region: "AGENT_KIT_RAW_SINK_REGION",
63
+ });
64
+
65
+ /**
66
+ * The Sinks' settings and credentials (#523), read once into memory, from the environment
67
+ * only (a literal or an `op://` reference), and never written, logged or passed to a child.
68
+ *
69
+ * records `AGENT_KIT_RECORDS_SINK` (owner/name of a private repository) and
70
+ * `AGENT_KIT_RECORDS_TOKEN`: both, or the engine keeps no Run Record (`notice`).
71
+ * raw `AGENT_KIT_RAW_SINK_ENDPOINT`, `_BUCKET`, `_REGION` and the S3 key pair
72
+ * `ORCHESTRATE_S3_ACCESS_KEY_ID` / `ORCHESTRATE_S3_SECRET_ACCESS_KEY`: read only
73
+ * with `--upload-raw`, which needs all five (`refused` names what is missing).
74
+ *
75
+ * @returns {{ records: {repo: string, token: string} | null, raw: object | null, notice?: string, refused?: string }}
76
+ */
77
+ export function readSinks({ env, runner, uploadRaw }) {
78
+ const out = { records: null, raw: null };
79
+ const get = (name) => {
80
+ const value = env[name];
81
+ if (value === undefined || value === "") return { missing: true };
82
+ const got = resolve(name, value, runner);
83
+ return got.refused ? { refused: got.refused } : { value: got.value };
84
+ };
85
+ const repo = String(env[RECORDS_SINK_VAR] ?? "");
86
+ const token = get(RECORDS_TOKEN_VAR);
87
+ if (token.refused) return { ...out, refused: token.refused };
88
+ if (repo && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) && !token.missing)
89
+ out.records = { repo, token: token.value };
90
+ else
91
+ out.notice = `no Run Record will be kept: ${
92
+ repo === ""
93
+ ? `${RECORDS_SINK_VAR} is not set`
94
+ : token.missing
95
+ ? `${RECORDS_TOKEN_VAR} is not set`
96
+ : `${RECORDS_SINK_VAR} is not owner/name`
97
+ }`;
98
+ if (!uploadRaw) return out;
99
+ const raw = {};
100
+ const missing = [];
101
+ for (const [key, name] of Object.entries(RAW_VARS)) {
102
+ if (env[name] === undefined || env[name] === "") missing.push(name);
103
+ else raw[key] = String(env[name]);
104
+ }
105
+ for (const [key, name] of [
106
+ ["accessKeyId", S3_KEY_ID_VAR],
107
+ ["secretAccessKey", S3_SECRET_VAR],
108
+ ]) {
109
+ const got = get(name);
110
+ if (got.refused) return { ...out, refused: got.refused };
111
+ if (got.missing) missing.push(name);
112
+ else raw[key] = got.value;
113
+ }
114
+ if (missing.length)
115
+ return {
116
+ ...out,
117
+ refused: `--upload-raw needs ${missing.join(", ")} (a value or an op:// reference)`,
118
+ };
119
+ let url;
120
+ try {
121
+ url = new URL(raw.endpoint);
122
+ } catch {
123
+ return { ...out, refused: `${RAW_VARS.endpoint} is not a URL` };
124
+ }
125
+ const plainHost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
126
+ if (
127
+ !(url.protocol === "https:" || (url.protocol === "http:" && plainHost)) ||
128
+ url.username ||
129
+ url.password ||
130
+ (url.pathname !== "/" && url.pathname !== "") ||
131
+ url.search
132
+ )
133
+ return {
134
+ ...out,
135
+ refused: `${RAW_VARS.endpoint} is an https URL with no path, query or password`,
136
+ };
137
+ if (!/^[a-z0-9][a-z0-9.-]{1,62}$/.test(raw.bucket))
138
+ return { ...out, refused: `${RAW_VARS.bucket} is not a bucket name` };
139
+ if (!/^[a-z0-9-]+$/.test(raw.region))
140
+ return { ...out, refused: `${RAW_VARS.region} is not a region` };
141
+ return { ...out, raw };
142
+ }