@tablation/crew 0.130.6 → 0.130.7
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/dist/cli.js +1453 -1392
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -6412,7 +6412,10 @@ function repoFindings(o) {
|
|
|
6412
6412
|
if (o.base.failed) {
|
|
6413
6413
|
problems.push({ severity: "blocker", kind: "base_unsafe", ...at, message: `${o.repo}: ${o.base.message}` });
|
|
6414
6414
|
} else if (o.base.message) passed++;
|
|
6415
|
-
for (const
|
|
6415
|
+
for (const g of o.sandboxGaps ?? []) {
|
|
6416
|
+
problems.push({ severity: "attention", kind: "hook_missing", ...at, hook: g.hook, command: g.command, message: g.message, remedy: g.remedy });
|
|
6417
|
+
}
|
|
6418
|
+
for (const hook2 of o.sandboxGaps ? [] : HOOK_NAMES2) {
|
|
6416
6419
|
const script = o.hooks[hook2];
|
|
6417
6420
|
const command2 = script ? hookCommand(script) : null;
|
|
6418
6421
|
if (!command2) continue;
|
|
@@ -6473,18 +6476,9 @@ function attentionProblems(items, already) {
|
|
|
6473
6476
|
return items.filter((i) => !seen.has(i.key)).map((i) => ({ severity: "attention", kind: i.kind, message: i.message }));
|
|
6474
6477
|
}
|
|
6475
6478
|
|
|
6476
|
-
// src/sandbox-image.ts
|
|
6477
|
-
import { createHash as createHash7 } from "crypto";
|
|
6478
|
-
import { spawn as spawn5 } from "child_process";
|
|
6479
|
-
import { execFileSync as execFileSync9 } from "child_process";
|
|
6480
|
-
import { existsSync as existsSync29, mkdirSync as mkdirSync19, readFileSync as readFileSync28, renameSync as renameSync3, writeFileSync as writeFileSync20, rmSync as rmSync15 } from "fs";
|
|
6481
|
-
import { dirname as dirname15, join as join32 } from "path";
|
|
6482
|
-
import { fileURLToPath } from "url";
|
|
6483
|
-
import { tmpdir as tmpdir3 } from "os";
|
|
6484
|
-
|
|
6485
6479
|
// src/passenger-containers.ts
|
|
6486
|
-
import { execFileSync as
|
|
6487
|
-
import { createHash as
|
|
6480
|
+
import { execFileSync as execFileSync9 } from "child_process";
|
|
6481
|
+
import { createHash as createHash7 } from "crypto";
|
|
6488
6482
|
|
|
6489
6483
|
// src/sandbox-cache.ts
|
|
6490
6484
|
import { execFile as execFile2 } from "child_process";
|
|
@@ -6492,19 +6486,19 @@ import { promisify as promisify2 } from "util";
|
|
|
6492
6486
|
|
|
6493
6487
|
// src/deprovision-host.ts
|
|
6494
6488
|
import { spawnSync as spawnSync7 } from "child_process";
|
|
6495
|
-
import { existsSync as
|
|
6489
|
+
import { existsSync as existsSync29, readdirSync as readdirSync11 } from "fs";
|
|
6496
6490
|
|
|
6497
6491
|
// src/interrupted.ts
|
|
6498
|
-
import { existsSync as
|
|
6499
|
-
import { join as
|
|
6492
|
+
import { existsSync as existsSync27, readdirSync as readdirSync9, readFileSync as readFileSync28 } from "fs";
|
|
6493
|
+
import { join as join31 } from "path";
|
|
6500
6494
|
|
|
6501
6495
|
// src/agent.ts
|
|
6502
6496
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
6503
|
-
import { readFileSync as
|
|
6497
|
+
import { readFileSync as readFileSync27, existsSync as existsSync26, statSync as statSync8, mkdirSync as mkdirSync19, writeFileSync as writeFileSync20, createWriteStream, openSync as openSync4, closeSync as closeSync4, readSync } from "fs";
|
|
6504
6498
|
import { StringDecoder } from "string_decoder";
|
|
6505
6499
|
import { finished } from "stream/promises";
|
|
6506
|
-
import { join as
|
|
6507
|
-
import { createHash as
|
|
6500
|
+
import { join as join30, dirname as dirname15, basename as basename9 } from "path";
|
|
6501
|
+
import { createHash as createHash6, randomUUID } from "crypto";
|
|
6508
6502
|
|
|
6509
6503
|
// src/state.ts
|
|
6510
6504
|
import { readFileSync as readFileSync19, writeFileSync as writeFileSync14, existsSync as existsSync18, mkdirSync as mkdirSync13, rmSync as rmSync10, statSync as statSync7, readdirSync as readdirSync5 } from "fs";
|
|
@@ -10825,894 +10819,1226 @@ var HandoffTranscriptTracker = class {
|
|
|
10825
10819
|
}
|
|
10826
10820
|
};
|
|
10827
10821
|
|
|
10828
|
-
// src/
|
|
10829
|
-
|
|
10822
|
+
// src/sandbox-image.ts
|
|
10823
|
+
import { createHash as createHash4 } from "crypto";
|
|
10824
|
+
import { spawn as spawn3 } from "child_process";
|
|
10825
|
+
import { execFileSync as execFileSync7 } from "child_process";
|
|
10826
|
+
import { existsSync as existsSync23, mkdirSync as mkdirSync17, readFileSync as readFileSync24, renameSync as renameSync3, writeFileSync as writeFileSync18, rmSync as rmSync14 } from "fs";
|
|
10827
|
+
import { dirname as dirname13, join as join26 } from "path";
|
|
10828
|
+
import { fileURLToPath } from "url";
|
|
10829
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
10830
|
+
var SANDBOX_BASE_IMAGE = "nvcr.io/nvidia/base/ubuntu:24.04";
|
|
10831
|
+
var SANDBOX_OPENSHELL_VERSION = "0.1.6";
|
|
10832
|
+
var SANDBOX_CLAUDE_VERSION = "2.1.309";
|
|
10833
|
+
var SANDBOX_CLAUDE_DIST = "https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases";
|
|
10834
|
+
var SANDBOX_CLAUDE_SHA256 = {
|
|
10835
|
+
x86_64: { platform: "linux-x64", sha256: "4d704a8aecbe038affa3000f498ae17c1b4f753add8facb8764120affc99b658" },
|
|
10836
|
+
aarch64: { platform: "linux-arm64", sha256: "9796dd26899337f687739a0b39a7353b639f062a3436a7b941fcf19a1b757a9b" }
|
|
10830
10837
|
};
|
|
10831
|
-
var
|
|
10832
|
-
var
|
|
10833
|
-
var
|
|
10834
|
-
function
|
|
10835
|
-
const
|
|
10836
|
-
for (const
|
|
10837
|
-
|
|
10838
|
-
if (name && !names.includes(name)) names.push(name);
|
|
10838
|
+
var SANDBOX_UID = 1e3;
|
|
10839
|
+
var CREW_PREFIX = "/opt/crew";
|
|
10840
|
+
var SANDBOX_BRIDGE_PATH = `${CREW_PREFIX}/bin/intel-bridge`;
|
|
10841
|
+
function readBridgeBundle() {
|
|
10842
|
+
const here = dirname13(fileURLToPath(import.meta.url));
|
|
10843
|
+
for (const p of [join26(here, "sandbox-intel-bridge.cjs"), join26(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
|
|
10844
|
+
if (existsSync23(p)) return readFileSync24(p, "utf8");
|
|
10839
10845
|
}
|
|
10840
|
-
return
|
|
10841
|
-
}
|
|
10842
|
-
function expandSkillMarkers(text2, lookup2, opts = {}) {
|
|
10843
|
-
const maxDepth = opts.maxDepth ?? MAX_INCLUDE_DEPTH;
|
|
10844
|
-
const maxBytes = opts.maxBytes ?? MAX_INCLUDED_BYTES;
|
|
10845
|
-
const warnings = [];
|
|
10846
|
-
let included = 0;
|
|
10847
|
-
const expand2 = (source, chain) => source.replace(MARKER, (literal, rawName) => {
|
|
10848
|
-
const name = rawName.trim();
|
|
10849
|
-
if (!name) return literal;
|
|
10850
|
-
if (chain.includes(name)) {
|
|
10851
|
-
warnings.push(`skill include "${name}" left literal: it includes itself (${[...chain, name].join(" \u2192 ")})`);
|
|
10852
|
-
return literal;
|
|
10853
|
-
}
|
|
10854
|
-
if (chain.length >= maxDepth) {
|
|
10855
|
-
warnings.push(`skill include "${name}" left literal: nested deeper than ${maxDepth} levels`);
|
|
10856
|
-
return literal;
|
|
10857
|
-
}
|
|
10858
|
-
const body = lookup2(name);
|
|
10859
|
-
if (body === void 0) throw new SkillIncludeError(`no skill named "${name}" for the include ${literal}`);
|
|
10860
|
-
const trimmed = body.replace(/^\n+/, "").replace(/\n+$/, "");
|
|
10861
|
-
const bytes = Buffer.byteLength(trimmed, "utf8");
|
|
10862
|
-
if (included + bytes > maxBytes) {
|
|
10863
|
-
warnings.push(`skill include "${name}" left literal: it would exceed the ${maxBytes}-byte include budget`);
|
|
10864
|
-
return literal;
|
|
10865
|
-
}
|
|
10866
|
-
included += bytes;
|
|
10867
|
-
return expand2(trimmed, [...chain, name]);
|
|
10868
|
-
});
|
|
10869
|
-
return { text: expand2(text2, []), warnings };
|
|
10870
|
-
}
|
|
10871
|
-
|
|
10872
|
-
// src/skills.ts
|
|
10873
|
-
import { readFileSync as readFileSync25, readdirSync as readdirSync8, existsSync as existsSync24 } from "fs";
|
|
10874
|
-
import { join as join27 } from "path";
|
|
10875
|
-
import { parse as parseYaml } from "yaml";
|
|
10876
|
-
import { TablationClient as TablationClient3, StaleWriteError as StaleWriteError3, TablationApiError as TablationApiError2 } from "@tablation/client";
|
|
10877
|
-
|
|
10878
|
-
// src/prompt-additions.ts
|
|
10879
|
-
var PROMPT_ADDITIONS_SEPARATOR = "---\n\nAdditional instructions from this workspace. Where they conflict with anything above, these take precedence.";
|
|
10880
|
-
function appendAdditions(text2, additions) {
|
|
10881
|
-
if (typeof additions !== "string" || additions.trim() === "") return text2;
|
|
10882
|
-
return `${text2}
|
|
10883
|
-
|
|
10884
|
-
${PROMPT_ADDITIONS_SEPARATOR}
|
|
10885
|
-
|
|
10886
|
-
${additions}`;
|
|
10846
|
+
return void 0;
|
|
10887
10847
|
}
|
|
10888
|
-
|
|
10889
|
-
|
|
10890
|
-
|
|
10891
|
-
|
|
10892
|
-
|
|
10893
|
-
var
|
|
10894
|
-
|
|
10895
|
-
|
|
10896
|
-
|
|
10897
|
-
|
|
10898
|
-
|
|
10899
|
-
}
|
|
10900
|
-
|
|
10901
|
-
|
|
10902
|
-
var
|
|
10848
|
+
var SANDBOX_UV_VERSION = "0.13.6";
|
|
10849
|
+
var SANDBOX_SERENA_VERSION = "2.1.0";
|
|
10850
|
+
var SERENA_IMAGE_HOME = `${CREW_PREFIX}/serena`;
|
|
10851
|
+
var SERENA_LANGUAGE_SERVERS_ENV = "CREW_SERENA_LANGUAGE_SERVERS";
|
|
10852
|
+
var SANDBOX_RETRY_AFTER_MS = 60 * 60 * 1e3;
|
|
10853
|
+
var KEEP_TAGS = 2;
|
|
10854
|
+
var CREDENTIAL_HELPER = `#!/bin/sh
|
|
10855
|
+
# git credential helper: answers from the environment the runner passes in, so
|
|
10856
|
+
# no token is ever written into an image layer.
|
|
10857
|
+
[ "$1" = get ] || exit 0
|
|
10858
|
+
[ -n "$CREW_FORGE_TOKEN" ] || exit 0
|
|
10859
|
+
echo "username=\${CREW_FORGE_USER:-x-access-token}"
|
|
10860
|
+
echo "password=$CREW_FORGE_TOKEN"
|
|
10861
|
+
`;
|
|
10862
|
+
var MCP_CONFIG = `${JSON.stringify({ mcpServers: {} }, null, 2)}
|
|
10863
|
+
`;
|
|
10864
|
+
var hash = (parts) => createHash4("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 12);
|
|
10865
|
+
var slug = (s) => s.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "repo";
|
|
10866
|
+
var run2 = (cmd) => `RUN ["/bin/bash", "-c", ${JSON.stringify(`set -euo pipefail; ${cmd}`)}]`;
|
|
10867
|
+
var CREW_ENV = {
|
|
10868
|
+
CREW_SANDBOX: "1",
|
|
10869
|
+
CREW_CACHE_DIR: `${CREW_PREFIX}/cache`,
|
|
10870
|
+
XDG_CACHE_HOME: `${CREW_PREFIX}/cache`,
|
|
10871
|
+
npm_config_cache: `${CREW_PREFIX}/cache/npm`,
|
|
10872
|
+
npm_config_store_dir: `${CREW_PREFIX}/pnpm-store`,
|
|
10873
|
+
// pnpm 11 ignores npm_config_store_dir and reads only this spelling (CREW-2973): without it `pnpm fetch`
|
|
10874
|
+
// at build time fills the builder's home store, and a run's offline install finds /opt/crew/pnpm-store empty.
|
|
10875
|
+
pnpm_config_store_dir: `${CREW_PREFIX}/pnpm-store`,
|
|
10876
|
+
PNPM_HOME: `${CREW_PREFIX}/pnpm`,
|
|
10877
|
+
// A run cannot reach the download host, so an in-run update attempt is only noise.
|
|
10878
|
+
DISABLE_AUTOUPDATER: "1"
|
|
10903
10879
|
};
|
|
10904
|
-
function
|
|
10905
|
-
const
|
|
10906
|
-
|
|
10907
|
-
|
|
10908
|
-
|
|
10909
|
-
|
|
10910
|
-
return
|
|
10880
|
+
function sandboxEnvExports() {
|
|
10881
|
+
const vars = {
|
|
10882
|
+
...CREW_ENV,
|
|
10883
|
+
[SERENA_LANGUAGE_SERVERS_ENV]: `${SERENA_IMAGE_HOME}/language_servers`,
|
|
10884
|
+
UV_PYTHON_INSTALL_DIR: `${CREW_PREFIX}/uv/python`
|
|
10885
|
+
};
|
|
10886
|
+
return Object.entries(vars).map(([k, v]) => `${k}=${v}; export ${k}; `).join("");
|
|
10911
10887
|
}
|
|
10912
|
-
|
|
10913
|
-
const
|
|
10914
|
-
|
|
10915
|
-
|
|
10916
|
-
|
|
10917
|
-
|
|
10918
|
-
|
|
10919
|
-
|
|
10920
|
-
|
|
10921
|
-
|
|
10922
|
-
try {
|
|
10923
|
-
const row = await client2.records.get(route2.resolved.models.crew, seatId);
|
|
10924
|
-
return row.agent_id ?? void 0;
|
|
10925
|
-
} catch {
|
|
10926
|
-
return void 0;
|
|
10927
|
-
}
|
|
10888
|
+
function claudeInstallCommand() {
|
|
10889
|
+
const cases = Object.entries(SANDBOX_CLAUDE_SHA256).map(([arch, { platform: platform2, sha256: sha2562 }]) => `${arch}) p=${platform2}; sum=${sha2562};;`).join(" ");
|
|
10890
|
+
return [
|
|
10891
|
+
`case "$(uname -m)" in ${cases} *) echo "no pinned Claude Code binary for $(uname -m)" >&2; exit 1;; esac`,
|
|
10892
|
+
`mkdir -p ${CREW_PREFIX}/bin`,
|
|
10893
|
+
`curl -fsSL --retry 3 -o ${CREW_PREFIX}/bin/claude "${SANDBOX_CLAUDE_DIST}/${SANDBOX_CLAUDE_VERSION}/$p/claude"`,
|
|
10894
|
+
`echo "$sum ${CREW_PREFIX}/bin/claude" | sha256sum -c -`,
|
|
10895
|
+
`chmod 0755 ${CREW_PREFIX}/bin/claude`,
|
|
10896
|
+
`${CREW_PREFIX}/bin/claude --version | grep -F "${SANDBOX_CLAUDE_VERSION}"`
|
|
10897
|
+
].join("; ");
|
|
10928
10898
|
}
|
|
10929
|
-
|
|
10930
|
-
|
|
10931
|
-
|
|
10932
|
-
|
|
10933
|
-
|
|
10934
|
-
|
|
10935
|
-
|
|
10936
|
-
|
|
10937
|
-
let row;
|
|
10938
|
-
let agentsModelId;
|
|
10939
|
-
try {
|
|
10940
|
-
const agentsModel = await client2.dataModels.get("agents", route2.resolved.workspaceId);
|
|
10941
|
-
agentsModelId = agentsModel.id;
|
|
10942
|
-
row = await client2.records.get(agentsModelId, agentId);
|
|
10943
|
-
} catch {
|
|
10944
|
-
return {};
|
|
10945
|
-
}
|
|
10946
|
-
const additions = typeof row.prompt_additions === "string" && row.prompt_additions.trim() !== "" ? row.prompt_additions : void 0;
|
|
10947
|
-
const divergedPrompt = await divergedRowPrompt(route2, role, row, agentId, agentsModelId, opts);
|
|
10948
|
-
return { divergedPrompt, additions };
|
|
10899
|
+
function serenaInstallCommand() {
|
|
10900
|
+
return [
|
|
10901
|
+
`python3 -m venv ${CREW_PREFIX}/uv-venv`,
|
|
10902
|
+
`${CREW_PREFIX}/uv-venv/bin/pip install --no-cache-dir uv==${SANDBOX_UV_VERSION}`,
|
|
10903
|
+
`ln -sf ${CREW_PREFIX}/uv-venv/bin/uv ${CREW_PREFIX}/bin/uv`,
|
|
10904
|
+
`UV_TOOL_DIR=${CREW_PREFIX}/uv/tools UV_TOOL_BIN_DIR=${CREW_PREFIX}/bin UV_PYTHON_INSTALL_DIR=${CREW_PREFIX}/uv/python UV_CACHE_DIR=${CREW_PREFIX}/cache/uv ${CREW_PREFIX}/bin/uv tool install -p 3.13 serena-agent==${SANDBOX_SERENA_VERSION}`,
|
|
10905
|
+
`${CREW_PREFIX}/bin/serena --help >/dev/null`
|
|
10906
|
+
].join("; ");
|
|
10949
10907
|
}
|
|
10950
|
-
function
|
|
10951
|
-
return
|
|
10908
|
+
function serenaWarmCommand() {
|
|
10909
|
+
return [
|
|
10910
|
+
`mkdir -p ${SERENA_IMAGE_HOME}`,
|
|
10911
|
+
`SERENA_HOME=${SERENA_IMAGE_HOME} serena project index ${WARM_DIR}`
|
|
10912
|
+
].join("; ");
|
|
10952
10913
|
}
|
|
10953
|
-
|
|
10954
|
-
|
|
10955
|
-
|
|
10956
|
-
|
|
10957
|
-
|
|
10958
|
-
|
|
10959
|
-
|
|
10960
|
-
if (lastSynced !== void 0 && lastSynced === row.prompt) return void 0;
|
|
10961
|
-
}
|
|
10962
|
-
return row.prompt;
|
|
10914
|
+
function baseLayer() {
|
|
10915
|
+
const dockerfile = [
|
|
10916
|
+
`FROM ${SANDBOX_BASE_IMAGE}`,
|
|
10917
|
+
`LABEL io.crew.sandbox.layer="base" io.crew.sandbox.openshell="${SANDBOX_OPENSHELL_VERSION}"`,
|
|
10918
|
+
""
|
|
10919
|
+
].join("\n");
|
|
10920
|
+
return { name: "base", tag: `crew-sandbox-base:${hash({ SANDBOX_BASE_IMAGE, SANDBOX_OPENSHELL_VERSION })}`, dockerfile, files: {} };
|
|
10963
10921
|
}
|
|
10964
|
-
|
|
10965
|
-
|
|
10966
|
-
|
|
10967
|
-
|
|
10968
|
-
|
|
10969
|
-
|
|
10922
|
+
var APT_HTTPS_COMMAND = "sed -i -E 's#http://([a-z0-9.-]*\\.)?ubuntu\\.com#https://\\1ubuntu.com#g' /etc/apt/sources.list.d/ubuntu.sources 2>/dev/null || true";
|
|
10923
|
+
var CA_BUNDLE_FILE = "ca-certificates.crt";
|
|
10924
|
+
var HOST_CA_BUNDLES = ["/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem"];
|
|
10925
|
+
function readHostCaBundle(paths = HOST_CA_BUNDLES) {
|
|
10926
|
+
for (const path of paths) {
|
|
10927
|
+
try {
|
|
10928
|
+
return readFileSync24(path, "utf8");
|
|
10929
|
+
} catch {
|
|
10930
|
+
}
|
|
10970
10931
|
}
|
|
10932
|
+
return "";
|
|
10971
10933
|
}
|
|
10972
|
-
function
|
|
10973
|
-
const
|
|
10974
|
-
|
|
10934
|
+
function crewLayer(base, intel, bridge) {
|
|
10935
|
+
const files = { "credential-helper": CREDENTIAL_HELPER, "mcp.json": MCP_CONFIG, ...bridge ? { "intel-bridge": bridge } : {} };
|
|
10936
|
+
const env = Object.entries(CREW_ENV).map(([k, v]) => `${k}=${v}`).join(" ");
|
|
10937
|
+
const dockerfile = [
|
|
10938
|
+
`FROM ${base.tag}`,
|
|
10939
|
+
"USER root",
|
|
10940
|
+
`COPY ${CA_BUNDLE_FILE} /etc/ssl/certs/ca-certificates.crt`,
|
|
10941
|
+
run2(APT_HTTPS_COMMAND),
|
|
10942
|
+
run2(`apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git${intel ? " python3 python3-venv nodejs" : ""} && rm -rf /var/lib/apt/lists/*`),
|
|
10943
|
+
`COPY credential-helper ${CREW_PREFIX}/bin/credential-helper`,
|
|
10944
|
+
`COPY mcp.json ${CREW_PREFIX}/mcp/mcp.json`,
|
|
10945
|
+
...bridge ? [`COPY intel-bridge ${SANDBOX_BRIDGE_PATH}`] : [],
|
|
10946
|
+
run2(claudeInstallCommand()),
|
|
10947
|
+
...intel ? [run2(`mkdir -p ${CREW_PREFIX}/cache && ${serenaInstallCommand()}`)] : [],
|
|
10948
|
+
run2(`chmod 0755 ${CREW_PREFIX}/bin/credential-helper && git config --system credential.helper ${CREW_PREFIX}/bin/credential-helper`),
|
|
10949
|
+
run2(`mkdir -p ${CREW_PREFIX}/cache ${CREW_PREFIX}/pnpm-store ${CREW_PREFIX}/pnpm /sandbox && chown -R ${SANDBOX_UID}:${SANDBOX_UID} ${CREW_PREFIX} /sandbox`),
|
|
10950
|
+
...intel ? [`ENV ${SERENA_LANGUAGE_SERVERS_ENV}=${SERENA_IMAGE_HOME}/language_servers UV_PYTHON_INSTALL_DIR=${CREW_PREFIX}/uv/python`] : [],
|
|
10951
|
+
`ENV ${env} PATH=${CREW_PREFIX}/pnpm:${CREW_PREFIX}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,
|
|
10952
|
+
`LABEL io.crew.sandbox.layer="crew" io.crew.sandbox.claude="${SANDBOX_CLAUDE_VERSION}"`,
|
|
10953
|
+
""
|
|
10954
|
+
].join("\n");
|
|
10955
|
+
return { name: "crew", tag: `crew-sandbox-crew:${hash({ base: base.tag, dockerfile, files })}`, dockerfile, files, caBundleFile: CA_BUNDLE_FILE };
|
|
10975
10956
|
}
|
|
10976
|
-
|
|
10977
|
-
|
|
10978
|
-
|
|
10979
|
-
|
|
10980
|
-
|
|
10981
|
-
|
|
10982
|
-
|
|
10983
|
-
|
|
10984
|
-
|
|
10985
|
-
|
|
10986
|
-
|
|
10987
|
-
const
|
|
10988
|
-
|
|
10989
|
-
|
|
10990
|
-
|
|
10991
|
-
...tier && TIERS.includes(tier) ? { tier } : {},
|
|
10992
|
-
...vendor ? { vendor } : {}
|
|
10993
|
-
};
|
|
10994
|
-
return Object.keys(persona).length > 0 ? persona : void 0;
|
|
10995
|
-
} catch {
|
|
10996
|
-
return void 0;
|
|
10957
|
+
var WARM_DIR = "/tmp/crew-warm";
|
|
10958
|
+
var WARM_MAX_BYTES = 64 * 1024 * 1024;
|
|
10959
|
+
var globToRegExp = (glob) => new RegExp(`^${glob.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")}$`);
|
|
10960
|
+
function readWarmFiles(dir, ref, patterns) {
|
|
10961
|
+
if (patterns.length === 0) return {};
|
|
10962
|
+
const git2 = (args) => execFileSync7("git", ["-C", dir, ...args], { encoding: "utf8", maxBuffer: WARM_MAX_BYTES, stdio: ["ignore", "pipe", "pipe"] });
|
|
10963
|
+
const all = git2(["ls-tree", "-r", "--name-only", ref]).split("\n").filter(Boolean);
|
|
10964
|
+
const res = patterns.map(globToRegExp);
|
|
10965
|
+
const out = {};
|
|
10966
|
+
let total = 0;
|
|
10967
|
+
for (const path of all.filter((f) => res.some((re) => re.test(f))).sort()) {
|
|
10968
|
+
const content = git2(["show", `${ref}:${path}`]);
|
|
10969
|
+
total += content.length;
|
|
10970
|
+
if (total > WARM_MAX_BYTES) throw new Error(`sandbox.warm files exceed ${WARM_MAX_BYTES} bytes`);
|
|
10971
|
+
out[path] = content;
|
|
10997
10972
|
}
|
|
10973
|
+
return out;
|
|
10998
10974
|
}
|
|
10999
|
-
|
|
11000
|
-
const
|
|
11001
|
-
|
|
11002
|
-
|
|
11003
|
-
|
|
11004
|
-
|
|
11005
|
-
|
|
11006
|
-
|
|
11007
|
-
|
|
11008
|
-
|
|
11009
|
-
|
|
11010
|
-
}
|
|
11011
|
-
|
|
11012
|
-
|
|
11013
|
-
|
|
11014
|
-
|
|
11015
|
-
|
|
11016
|
-
|
|
11017
|
-
|
|
11018
|
-
|
|
11019
|
-
|
|
10975
|
+
function repoLayer(repo, decl, crew, warm) {
|
|
10976
|
+
const env = Object.entries(CREW_ENV).map(([k, v]) => `${k}=${v}`).join(" ");
|
|
10977
|
+
const lines2 = [];
|
|
10978
|
+
if (decl.image) {
|
|
10979
|
+
lines2.push(
|
|
10980
|
+
`FROM ${crew.tag} AS crew`,
|
|
10981
|
+
`FROM ${decl.image}`,
|
|
10982
|
+
"USER root",
|
|
10983
|
+
`COPY --from=crew ${CREW_PREFIX} ${CREW_PREFIX}`,
|
|
10984
|
+
`ENV ${env} PATH=${CREW_PREFIX}/pnpm:${CREW_PREFIX}/bin:$PATH`
|
|
10985
|
+
);
|
|
10986
|
+
} else {
|
|
10987
|
+
lines2.push(`FROM ${crew.tag}`, "USER root");
|
|
10988
|
+
}
|
|
10989
|
+
if (decl.packages.length > 0) {
|
|
10990
|
+
lines2.push(run2(APT_HTTPS_COMMAND));
|
|
10991
|
+
lines2.push(run2(`apt-get update && apt-get install -y --no-install-recommends ${decl.packages.join(" ")} && rm -rf /var/lib/apt/lists/*`));
|
|
10992
|
+
}
|
|
10993
|
+
lines2.push(
|
|
10994
|
+
run2(`mkdir -p /sandbox && chown -R ${SANDBOX_UID}:${SANDBOX_UID} /sandbox ${CREW_PREFIX}`),
|
|
10995
|
+
`USER ${SANDBOX_UID}`,
|
|
10996
|
+
"WORKDIR /sandbox"
|
|
10997
|
+
);
|
|
10998
|
+
const files = {};
|
|
10999
|
+
const warming = Object.keys(warm).length > 0;
|
|
11000
|
+
if (warming) {
|
|
11001
|
+
for (const [path, content] of Object.entries(warm)) files[`warm/${path}`] = content;
|
|
11002
|
+
lines2.push(`COPY --chown=${SANDBOX_UID}:${SANDBOX_UID} warm/ ${WARM_DIR}/`, `WORKDIR ${WARM_DIR}`);
|
|
11020
11003
|
}
|
|
11004
|
+
for (const step of decl.setup) lines2.push(run2(step));
|
|
11005
|
+
if (warming && decl.intel) lines2.push(run2(serenaWarmCommand()));
|
|
11006
|
+
if (warming) lines2.push("WORKDIR /sandbox", run2(`rm -rf ${WARM_DIR}`));
|
|
11007
|
+
lines2.push(`LABEL io.crew.sandbox.layer="repo" io.crew.sandbox.repo=${JSON.stringify(repo)}`, "");
|
|
11008
|
+
const dockerfile = lines2.join("\n");
|
|
11009
|
+
return { name: "repo", tag: `crew-sandbox/${slug(repo)}:${hash({ crew: crew.tag, dockerfile, files })}`, dockerfile, files };
|
|
11021
11010
|
}
|
|
11022
|
-
function
|
|
11023
|
-
|
|
11011
|
+
function planSandbox(repo, decl, warm = {}, bridge) {
|
|
11012
|
+
const base = baseLayer();
|
|
11013
|
+
const crew = crewLayer(base, decl.intel, bridge);
|
|
11014
|
+
const layer = repoLayer(repo, decl, crew, warm);
|
|
11015
|
+
return { repo, tag: layer.tag, claude: SANDBOX_CLAUDE_VERSION, layers: [base, crew, layer] };
|
|
11024
11016
|
}
|
|
11025
|
-
|
|
11026
|
-
|
|
11017
|
+
var SHIP_SANDBOX_KEY = "@ship";
|
|
11018
|
+
var shipSandboxRef = () => ({ name: SHIP_SANDBOX_KEY, decl: { packages: [], setup: [] } });
|
|
11019
|
+
var sandboxStatePath = (stateDir) => join26(stateDir, "sandbox-images.json");
|
|
11020
|
+
function readSandboxState(stateDir) {
|
|
11027
11021
|
try {
|
|
11028
|
-
const
|
|
11029
|
-
|
|
11030
|
-
});
|
|
11031
|
-
if (!res.ok) return void 0;
|
|
11032
|
-
const me = await res.json();
|
|
11033
|
-
return typeof me.role === "string" ? me.role : void 0;
|
|
11022
|
+
const v = JSON.parse(readFileSync24(sandboxStatePath(stateDir), "utf8"));
|
|
11023
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
11034
11024
|
} catch {
|
|
11035
|
-
return
|
|
11025
|
+
return {};
|
|
11036
11026
|
}
|
|
11037
11027
|
}
|
|
11038
|
-
function
|
|
11039
|
-
|
|
11040
|
-
|
|
11041
|
-
|
|
11042
|
-
|
|
11028
|
+
function writeSandboxState(stateDir, state) {
|
|
11029
|
+
mkdirSync17(stateDir, { recursive: true });
|
|
11030
|
+
const file = sandboxStatePath(stateDir);
|
|
11031
|
+
writeFileSync18(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
|
|
11032
|
+
`);
|
|
11033
|
+
renameSync3(`${file}.tmp`, file);
|
|
11043
11034
|
}
|
|
11044
|
-
function
|
|
11045
|
-
return
|
|
11035
|
+
function sandboxImageFor(state, repo) {
|
|
11036
|
+
return state[repo]?.tags[0]?.tag ?? null;
|
|
11046
11037
|
}
|
|
11047
|
-
function
|
|
11048
|
-
return
|
|
11038
|
+
function sandboxImageForRun(state, repo, declares) {
|
|
11039
|
+
return (declares && repo ? sandboxImageFor(state, repo) : null) ?? sandboxImageFor(state, SHIP_SANDBOX_KEY);
|
|
11049
11040
|
}
|
|
11050
|
-
function
|
|
11051
|
-
|
|
11041
|
+
function sandboxImageStatus(state, plan) {
|
|
11042
|
+
const s = state[plan.repo];
|
|
11043
|
+
const current = s?.tags[0];
|
|
11044
|
+
if (s?.failure && s.failure.tag === plan.tag) {
|
|
11045
|
+
return { status: "failed", detail: `last build of ${plan.tag} failed at ${s.failure.at}; log ${s.failure.logPath}${current ? `; running ${current.tag}` : ""}` };
|
|
11046
|
+
}
|
|
11047
|
+
if (!current) return { status: "missing", detail: `no image built yet (wants ${plan.tag}); run \`crew sandbox build\`` };
|
|
11048
|
+
if (current.tag !== plan.tag) return { status: "stale", detail: `running ${current.tag} (claude ${current.claude ?? "unknown"}), declaration now builds ${plan.tag} (claude ${plan.claude})` };
|
|
11049
|
+
return { status: "ok", detail: `${current.tag} built ${current.builtAt}, claude ${current.claude ?? "unknown"}` };
|
|
11052
11050
|
}
|
|
11053
|
-
var
|
|
11054
|
-
|
|
11055
|
-
|
|
11056
|
-
|
|
11057
|
-
|
|
11051
|
+
var spawnBuildRunner = (engine = "docker") => (args, logPath) => new Promise((resolve8) => {
|
|
11052
|
+
const child = spawn3(engine, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
11053
|
+
const chunks = [];
|
|
11054
|
+
child.stdout.on("data", (d) => chunks.push(d));
|
|
11055
|
+
child.stderr.on("data", (d) => chunks.push(d));
|
|
11056
|
+
const done = (code, extra = "") => {
|
|
11057
|
+
writeFileSync18(logPath, `$ ${engine} ${args.join(" ")}
|
|
11058
|
+
${Buffer.concat(chunks).toString("utf8")}${extra}`, { flag: "a" });
|
|
11059
|
+
resolve8(code);
|
|
11060
|
+
};
|
|
11061
|
+
child.on("error", (e) => done(127, `${e.message}
|
|
11062
|
+
`));
|
|
11063
|
+
child.on("close", (code) => done(code ?? 1));
|
|
11064
|
+
});
|
|
11065
|
+
var engineHasImage = (engine = "docker", exec = realExec) => (tag) => {
|
|
11066
|
+
try {
|
|
11067
|
+
exec(engine, ["image", "inspect", tag], { timeoutMs: 2e4 });
|
|
11068
|
+
return true;
|
|
11069
|
+
} catch {
|
|
11070
|
+
return false;
|
|
11058
11071
|
}
|
|
11059
|
-
|
|
11060
|
-
|
|
11061
|
-
baseUrl: `${route2.baseUrl}/api`,
|
|
11062
|
-
apiKey: resolveApiKey(route2),
|
|
11063
|
-
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11064
|
-
});
|
|
11065
|
-
let agentsModel;
|
|
11072
|
+
};
|
|
11073
|
+
var engineRemoveImage = (engine = "docker", exec = realExec) => (tag) => {
|
|
11066
11074
|
try {
|
|
11067
|
-
|
|
11068
|
-
} catch
|
|
11069
|
-
if (e instanceof TablationApiError && e.status === 404) {
|
|
11070
|
-
throw new AgentsSyncError(
|
|
11071
|
-
`workspace ${workspaceId} has no Agents table yet \u2014 every workspace auto-provisions one (ISSUE-465); an older workspace may still need its one-time backfill`
|
|
11072
|
-
);
|
|
11073
|
-
}
|
|
11074
|
-
throw e;
|
|
11075
|
+
exec(engine, ["image", "rm", tag], { timeoutMs: 6e4 });
|
|
11076
|
+
} catch {
|
|
11075
11077
|
}
|
|
11076
|
-
|
|
11077
|
-
|
|
11078
|
-
|
|
11079
|
-
const
|
|
11080
|
-
|
|
11081
|
-
|
|
11082
|
-
|
|
11083
|
-
|
|
11084
|
-
|
|
11085
|
-
|
|
11086
|
-
|
|
11087
|
-
|
|
11078
|
+
};
|
|
11079
|
+
var sandboxLogDir = (stateDir) => join26(stateDir, "sandbox-logs");
|
|
11080
|
+
async function buildSandboxImage(plan, deps) {
|
|
11081
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
11082
|
+
const state = readSandboxState(deps.stateDir);
|
|
11083
|
+
const entry = state[plan.repo] ?? { tags: [] };
|
|
11084
|
+
if (entry.tags[0]?.tag === plan.tag && deps.hasImage(plan.tag)) {
|
|
11085
|
+
return { kind: "reused", tag: plan.tag };
|
|
11086
|
+
}
|
|
11087
|
+
const logDir = sandboxLogDir(deps.stateDir);
|
|
11088
|
+
mkdirSync17(logDir, { recursive: true });
|
|
11089
|
+
const logPath = join26(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
|
|
11090
|
+
const builtLayers = [];
|
|
11091
|
+
for (const layer of plan.layers) {
|
|
11092
|
+
if (deps.hasImage(layer.tag)) continue;
|
|
11093
|
+
const ctx = join26(tmpdir2(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
|
|
11094
|
+
mkdirSync17(ctx, { recursive: true });
|
|
11095
|
+
try {
|
|
11096
|
+
writeFileSync18(join26(ctx, "Dockerfile"), layer.dockerfile);
|
|
11097
|
+
for (const [name, content] of Object.entries(layer.files)) {
|
|
11098
|
+
mkdirSync17(dirname13(join26(ctx, name)), { recursive: true });
|
|
11099
|
+
writeFileSync18(join26(ctx, name), content);
|
|
11088
11100
|
}
|
|
11089
|
-
|
|
11090
|
-
|
|
11091
|
-
|
|
11092
|
-
|
|
11093
|
-
|
|
11094
|
-
|
|
11095
|
-
if (opts.dryRun) {
|
|
11096
|
-
outcomes.push({ role, action: "created", agentId: "(dry run)" });
|
|
11097
|
-
continue;
|
|
11101
|
+
if (layer.caBundleFile) writeFileSync18(join26(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
|
|
11102
|
+
const code = await deps.run(["build", "--tag", layer.tag, "--file", join26(ctx, "Dockerfile"), ctx], logPath);
|
|
11103
|
+
if (code !== 0) {
|
|
11104
|
+
state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
|
|
11105
|
+
writeSandboxState(deps.stateDir, state);
|
|
11106
|
+
return { kind: "failed", tag: plan.tag, logPath, layer: layer.name };
|
|
11098
11107
|
}
|
|
11099
|
-
|
|
11100
|
-
|
|
11101
|
-
|
|
11102
|
-
|
|
11108
|
+
builtLayers.push(layer.name);
|
|
11109
|
+
} finally {
|
|
11110
|
+
rmSync14(ctx, { recursive: true, force: true });
|
|
11111
|
+
}
|
|
11112
|
+
}
|
|
11113
|
+
const tags = [{ tag: plan.tag, builtAt: now().toISOString(), claude: plan.claude }, ...entry.tags.filter((t) => t.tag !== plan.tag)];
|
|
11114
|
+
const dropped = tags.slice(KEEP_TAGS);
|
|
11115
|
+
state[plan.repo] = { tags: tags.slice(0, KEEP_TAGS) };
|
|
11116
|
+
writeSandboxState(deps.stateDir, state);
|
|
11117
|
+
for (const t of dropped) deps.removeImage(t.tag);
|
|
11118
|
+
return { kind: "built", tag: plan.tag, builtLayers };
|
|
11119
|
+
}
|
|
11120
|
+
var sandboxFailedKey = (repo) => `sandbox_build_failed:${repo}`;
|
|
11121
|
+
function sandboxFailedItem(repo, tag, layer, logPath, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
11122
|
+
return {
|
|
11123
|
+
kind: "sandbox_build_failed",
|
|
11124
|
+
key: sandboxFailedKey(repo),
|
|
11125
|
+
since: nowIso,
|
|
11126
|
+
message: `${repo}: sandbox image ${tag} failed to build at the ${layer} layer (log: ${logPath}); sandboxes keep running the previous image. Retries automatically after the declaration changes or in an hour; \`crew sandbox build\` forces it`
|
|
11127
|
+
};
|
|
11128
|
+
}
|
|
11129
|
+
async function sandboxBuildTick(repos, deps, force = false) {
|
|
11130
|
+
const nowMs = (deps.now ?? (() => /* @__PURE__ */ new Date()))().getTime();
|
|
11131
|
+
for (const r of repos) {
|
|
11132
|
+
const plan = planSandbox(r.name, r.decl, r.warm, r.bridge);
|
|
11133
|
+
const state = readSandboxState(deps.stateDir)[r.name];
|
|
11134
|
+
const upToDate = state?.tags[0]?.tag === plan.tag && deps.hasImage(plan.tag);
|
|
11135
|
+
if (upToDate) {
|
|
11136
|
+
deps.clear(sandboxFailedKey(r.name));
|
|
11103
11137
|
continue;
|
|
11104
11138
|
}
|
|
11105
|
-
if (
|
|
11106
|
-
|
|
11107
|
-
|
|
11108
|
-
|
|
11109
|
-
|
|
11110
|
-
|
|
11111
|
-
if (!(e instanceof StaleWriteError2) && !isPromptGateRejection(e)) throw e;
|
|
11112
|
-
}
|
|
11113
|
-
}
|
|
11114
|
-
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11115
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: anchoredAt, ...historyId ? { historyId } : {} };
|
|
11116
|
-
outcomes.push({ role, action: "unchanged", agentId: row.id });
|
|
11117
|
-
continue;
|
|
11118
|
-
}
|
|
11119
|
-
if (row.prompt_customized === true) {
|
|
11120
|
-
const prior = cache[role]?.agentId === row.id ? cache[role] : void 0;
|
|
11121
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...prior?.historyId ? { historyId: prior.historyId } : {} };
|
|
11122
|
-
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11123
|
-
continue;
|
|
11124
|
-
}
|
|
11125
|
-
if (opts.force) {
|
|
11126
|
-
if (opts.dryRun) {
|
|
11127
|
-
outcomes.push({ role, action: "forced", agentId: row.id, previousPrompt: row.prompt });
|
|
11128
|
-
continue;
|
|
11129
|
-
}
|
|
11130
|
-
let updated;
|
|
11131
|
-
try {
|
|
11132
|
-
updated = await client2.records.update(agentsModel.id, row.id, { prompt: defaultPrompt, ...promptSourceFields(agentsModel, defaultPrompt) });
|
|
11133
|
-
} catch (e) {
|
|
11134
|
-
if (!isPromptGateRejection(e)) throw e;
|
|
11135
|
-
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11136
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...cache[role]?.agentId === row.id && cache[role]?.historyId ? { historyId: cache[role].historyId } : {} };
|
|
11137
|
-
continue;
|
|
11138
|
-
}
|
|
11139
|
-
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11140
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: updated.updated_at, ...historyId ? { historyId } : {} };
|
|
11141
|
-
outcomes.push({ role, action: "forced", agentId: row.id, previousPrompt: row.prompt });
|
|
11142
|
-
continue;
|
|
11143
|
-
}
|
|
11144
|
-
const cached = cache[role]?.agentId === row.id ? cache[role] : void 0;
|
|
11145
|
-
const baselineKnown = hasPromptBaselineColumn(agentsModel) && typeof row.prompt_baseline === "string";
|
|
11146
|
-
if (baselineKnown) {
|
|
11147
|
-
if (row.prompt !== row.prompt_baseline) {
|
|
11148
|
-
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11149
|
-
continue;
|
|
11150
|
-
}
|
|
11139
|
+
if (!force && state?.failure?.tag === plan.tag && nowMs - Date.parse(state.failure.at) < SANDBOX_RETRY_AFTER_MS) continue;
|
|
11140
|
+
deps.log(`sandbox image for ${r.name}: building ${plan.tag}`);
|
|
11141
|
+
const out = await buildSandboxImage(plan, deps);
|
|
11142
|
+
if (out.kind === "failed") {
|
|
11143
|
+
deps.raise(sandboxFailedItem(r.name, out.tag, out.layer, out.logPath));
|
|
11144
|
+
deps.log(`sandbox image for ${r.name}: build failed at the ${out.layer} layer, log ${out.logPath}`);
|
|
11151
11145
|
} else {
|
|
11152
|
-
|
|
11153
|
-
|
|
11154
|
-
continue;
|
|
11155
|
-
}
|
|
11156
|
-
let lastSyncedPrompt;
|
|
11157
|
-
try {
|
|
11158
|
-
const entries = await fetchHistoryEntries(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11159
|
-
lastSyncedPrompt = entries.find((e) => e.history_id === cached.historyId)?.prompt;
|
|
11160
|
-
} catch {
|
|
11161
|
-
lastSyncedPrompt = void 0;
|
|
11162
|
-
}
|
|
11163
|
-
if (lastSyncedPrompt === void 0 || lastSyncedPrompt !== row.prompt) {
|
|
11164
|
-
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11165
|
-
continue;
|
|
11166
|
-
}
|
|
11167
|
-
}
|
|
11168
|
-
if (opts.dryRun) {
|
|
11169
|
-
outcomes.push({ role, action: "updated", agentId: row.id });
|
|
11170
|
-
continue;
|
|
11171
|
-
}
|
|
11172
|
-
try {
|
|
11173
|
-
const updated = await client2.records.update(
|
|
11174
|
-
agentsModel.id,
|
|
11175
|
-
row.id,
|
|
11176
|
-
{ prompt: defaultPrompt, ...promptSourceFields(agentsModel, defaultPrompt) },
|
|
11177
|
-
row.updated_at
|
|
11178
|
-
);
|
|
11179
|
-
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11180
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: updated.updated_at, ...historyId ? { historyId } : {} };
|
|
11181
|
-
outcomes.push({ role, action: "updated", agentId: row.id });
|
|
11182
|
-
} catch (e) {
|
|
11183
|
-
if (e instanceof StaleWriteError2) {
|
|
11184
|
-
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11185
|
-
continue;
|
|
11186
|
-
}
|
|
11187
|
-
if (isPromptGateRejection(e)) {
|
|
11188
|
-
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...cached?.historyId ? { historyId: cached.historyId } : {} };
|
|
11189
|
-
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11190
|
-
continue;
|
|
11191
|
-
}
|
|
11192
|
-
throw e;
|
|
11193
|
-
}
|
|
11194
|
-
}
|
|
11195
|
-
const crewLinks = opts.dryRun ? [] : await linkCrewSeats(route2, client2, agentsModel.id, agentPersonas, opts.userAgent, opts.readOnly === true);
|
|
11196
|
-
const release = opts.dryRun ? { agentId: route2.resolved.releaseAgentId } : await linkReleaseSeat(route2, client2, agentsModel, opts.userAgent, opts.readOnly === true);
|
|
11197
|
-
return {
|
|
11198
|
-
outcomes,
|
|
11199
|
-
agentPersonas,
|
|
11200
|
-
crewLinks,
|
|
11201
|
-
...release.agentId ? { releaseAgentId: release.agentId } : {},
|
|
11202
|
-
...release.note ? { releaseNote: release.note } : {},
|
|
11203
|
-
...opts.readOnly ? { readOnly: true } : {}
|
|
11204
|
-
};
|
|
11205
|
-
}
|
|
11206
|
-
async function linkReleaseSeat(route2, client2, agentsModel, userAgent, readOnly) {
|
|
11207
|
-
const seatId = route2.resolved.releaseSeat;
|
|
11208
|
-
if (!seatId) return {};
|
|
11209
|
-
const rows = await client2.records.list(agentsModel.id, { limit: 200 });
|
|
11210
|
-
let agentId = rows.find((r) => r.name === RELEASE_AGENT_NAME)?.id;
|
|
11211
|
-
if (!agentId) {
|
|
11212
|
-
if (readOnly) return { note: `Release: no "${RELEASE_AGENT_NAME}" Agents row in this workspace \u2014 writes as the ship until a workspace admin runs \`crew agents sync\`` };
|
|
11213
|
-
try {
|
|
11214
|
-
agentId = (await client2.records.create(agentsModel.id, {
|
|
11215
|
-
name: RELEASE_AGENT_NAME,
|
|
11216
|
-
prompt: RELEASE_AGENT_PROMPT,
|
|
11217
|
-
...promptSourceFields(agentsModel, RELEASE_AGENT_PROMPT)
|
|
11218
|
-
})).id;
|
|
11219
|
-
} catch (e) {
|
|
11220
|
-
if (isForbidden(e)) return { note: `Release: could not create the "${RELEASE_AGENT_NAME}" Agents row (${NO_WRITE_NOTE}) \u2014 writes as the ship` };
|
|
11221
|
-
throw e;
|
|
11146
|
+
deps.clear(sandboxFailedKey(r.name));
|
|
11147
|
+
deps.log(`sandbox image for ${r.name}: ${out.kind === "built" ? `built ${out.tag}` : `${out.tag} already built`}`);
|
|
11222
11148
|
}
|
|
11149
|
+
return r.name;
|
|
11223
11150
|
}
|
|
11224
|
-
|
|
11225
|
-
const crewModel = await client2.dataModels.get(crewModelId);
|
|
11226
|
-
let columnName;
|
|
11227
|
-
try {
|
|
11228
|
-
columnName = await ensureCrewAgentField(route2, client2, crewModel, agentsModel.id, userAgent);
|
|
11229
|
-
} catch (e) {
|
|
11230
|
-
if (e instanceof CrewAgentFieldMissing) return { note: `Release: ${CREW_FIELD_MISSING_NOTE}` };
|
|
11231
|
-
throw e;
|
|
11232
|
-
}
|
|
11233
|
-
const seatRow = await client2.records.get(crewModelId, seatId);
|
|
11234
|
-
if (seatRow[CREW_AGENT_COLUMN] !== agentId) await client2.records.update(crewModelId, seatId, { [columnName]: agentId });
|
|
11235
|
-
return { agentId };
|
|
11151
|
+
return null;
|
|
11236
11152
|
}
|
|
11237
|
-
|
|
11238
|
-
|
|
11239
|
-
var
|
|
11153
|
+
|
|
11154
|
+
// src/skill-include.ts
|
|
11155
|
+
var SkillIncludeError = class extends Error {
|
|
11240
11156
|
};
|
|
11241
|
-
|
|
11242
|
-
|
|
11243
|
-
|
|
11244
|
-
|
|
11245
|
-
|
|
11246
|
-
|
|
11247
|
-
|
|
11248
|
-
|
|
11249
|
-
const crewModel = await client2.dataModels.get(crewModelId);
|
|
11250
|
-
let columnName;
|
|
11251
|
-
try {
|
|
11252
|
-
columnName = await ensureCrewAgentField(route2, client2, crewModel, agentsModelId, userAgent);
|
|
11253
|
-
} catch (e) {
|
|
11254
|
-
if (e instanceof CrewAgentFieldMissing) {
|
|
11255
|
-
return ROLE_NAMES.map((role) => ({ role, action: seats2[role] ? "no_agent_field" : "no_seat" }));
|
|
11256
|
-
}
|
|
11257
|
-
throw e;
|
|
11157
|
+
var MAX_INCLUDE_DEPTH = 3;
|
|
11158
|
+
var MAX_INCLUDED_BYTES = 2e5;
|
|
11159
|
+
var MARKER = /\{\{[ \t]*skill:[ \t]*([^{}\r\n]*?)[ \t]*\}\}/g;
|
|
11160
|
+
function skillMarkerNames(text2) {
|
|
11161
|
+
const names = [];
|
|
11162
|
+
for (const m of text2.matchAll(MARKER)) {
|
|
11163
|
+
const name = m[1].trim();
|
|
11164
|
+
if (name && !names.includes(name)) names.push(name);
|
|
11258
11165
|
}
|
|
11259
|
-
|
|
11260
|
-
|
|
11261
|
-
|
|
11262
|
-
|
|
11263
|
-
|
|
11264
|
-
|
|
11265
|
-
|
|
11166
|
+
return names;
|
|
11167
|
+
}
|
|
11168
|
+
function expandSkillMarkers(text2, lookup2, opts = {}) {
|
|
11169
|
+
const maxDepth = opts.maxDepth ?? MAX_INCLUDE_DEPTH;
|
|
11170
|
+
const maxBytes = opts.maxBytes ?? MAX_INCLUDED_BYTES;
|
|
11171
|
+
const warnings = [];
|
|
11172
|
+
let included = 0;
|
|
11173
|
+
const expand2 = (source, chain) => source.replace(MARKER, (literal, rawName) => {
|
|
11174
|
+
const name = rawName.trim();
|
|
11175
|
+
if (!name) return literal;
|
|
11176
|
+
if (chain.includes(name)) {
|
|
11177
|
+
warnings.push(`skill include "${name}" left literal: it includes itself (${[...chain, name].join(" \u2192 ")})`);
|
|
11178
|
+
return literal;
|
|
11266
11179
|
}
|
|
11267
|
-
if (
|
|
11268
|
-
|
|
11269
|
-
|
|
11180
|
+
if (chain.length >= maxDepth) {
|
|
11181
|
+
warnings.push(`skill include "${name}" left literal: nested deeper than ${maxDepth} levels`);
|
|
11182
|
+
return literal;
|
|
11270
11183
|
}
|
|
11271
|
-
const
|
|
11272
|
-
if (
|
|
11273
|
-
|
|
11274
|
-
|
|
11184
|
+
const body = lookup2(name);
|
|
11185
|
+
if (body === void 0) throw new SkillIncludeError(`no skill named "${name}" for the include ${literal}`);
|
|
11186
|
+
const trimmed = body.replace(/^\n+/, "").replace(/\n+$/, "");
|
|
11187
|
+
const bytes = Buffer.byteLength(trimmed, "utf8");
|
|
11188
|
+
if (included + bytes > maxBytes) {
|
|
11189
|
+
warnings.push(`skill include "${name}" left literal: it would exceed the ${maxBytes}-byte include budget`);
|
|
11190
|
+
return literal;
|
|
11275
11191
|
}
|
|
11276
|
-
|
|
11277
|
-
|
|
11278
|
-
}
|
|
11279
|
-
return outcomes;
|
|
11280
|
-
}
|
|
11281
|
-
async function ensureCrewAgentField(route2, client2, crewModel, agentsModelId, userAgent) {
|
|
11282
|
-
const existing = crewModel.fields.find(
|
|
11283
|
-
(f) => f.fieldType?.kind === "REFERENCE" && f.fieldType.targetModelId === agentsModelId && f.fieldType.isMultiple === false
|
|
11284
|
-
);
|
|
11285
|
-
if (existing) return existing.columnName;
|
|
11286
|
-
const workspaceId = route2.resolved.workspaceId;
|
|
11287
|
-
const baseUrl = route2.baseUrl.replace(/\/+$/, "");
|
|
11288
|
-
const apiKey = resolveApiKey(route2);
|
|
11289
|
-
const headers = { Authorization: `Bearer ${apiKey}`, "User-Agent": userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" };
|
|
11290
|
-
const typesRes = await fetch(`${baseUrl}/api/workspaces/${workspaceId}/field-types`, { headers });
|
|
11291
|
-
if (!typesRes.ok) throw new AgentsSyncError(`field-types lookup failed: ${typesRes.status} ${typesRes.statusText}`);
|
|
11292
|
-
const types = await typesRes.json();
|
|
11293
|
-
const fieldType = types.find((t) => t.kind === "REFERENCE" && t.targetModelId === agentsModelId && t.isMultiple === false);
|
|
11294
|
-
if (!fieldType) {
|
|
11295
|
-
throw new AgentsSyncError(
|
|
11296
|
-
`workspace ${workspaceId} has no single-valued Agents-reference field type \u2014 every table auto-provisions one (see the pseudo-builtin reference types convention); an older Agents table may need its one-time backfill`
|
|
11297
|
-
);
|
|
11298
|
-
}
|
|
11299
|
-
const createRes = await fetch(`${baseUrl}/api/data-models/${crewModel.id}/fields`, {
|
|
11300
|
-
method: "POST",
|
|
11301
|
-
headers: { ...headers, "Content-Type": "application/json" },
|
|
11302
|
-
body: JSON.stringify({
|
|
11303
|
-
name: CREW_AGENT_FIELD_NAME,
|
|
11304
|
-
columnName: CREW_AGENT_COLUMN,
|
|
11305
|
-
fieldTypeId: fieldType.id,
|
|
11306
|
-
description: "The Agents-table row backing this seat's persona \u2014 set by `crew agents sync` (ISSUE-416), never edited by hand."
|
|
11307
|
-
})
|
|
11192
|
+
included += bytes;
|
|
11193
|
+
return expand2(trimmed, [...chain, name]);
|
|
11308
11194
|
});
|
|
11309
|
-
|
|
11310
|
-
if (!createRes.ok) throw new AgentsSyncError(`creating the Crew table's Agent field failed: ${createRes.status} ${createRes.statusText}`);
|
|
11311
|
-
const created = await createRes.json();
|
|
11312
|
-
return created.columnName;
|
|
11313
|
-
}
|
|
11314
|
-
function describeSyncOutcome(o) {
|
|
11315
|
-
const label = PERSONA_NAME[o.role];
|
|
11316
|
-
switch (o.action) {
|
|
11317
|
-
case "created":
|
|
11318
|
-
return `${label}: created (${o.agentId})`;
|
|
11319
|
-
case "updated":
|
|
11320
|
-
return `${label}: prompt updated from crew's local default`;
|
|
11321
|
-
case "unchanged":
|
|
11322
|
-
return `${label}: already in sync`;
|
|
11323
|
-
case "diverged":
|
|
11324
|
-
return `${label}: HAS LOCAL EDITS \u2014 crew's default is newer but was NOT applied; review ${o.agentId} in the app before syncing again`;
|
|
11325
|
-
case "overridden":
|
|
11326
|
-
return `${label}: override in place \u2014 prompt not synced (clear "Customize prompt" on the Agents row to resume)`;
|
|
11327
|
-
case "adopted":
|
|
11328
|
-
return `${label}: using the workspace's existing Agents row (${o.agentId})`;
|
|
11329
|
-
case "missing":
|
|
11330
|
-
return `${label}: no Agents row in this workspace \u2014 writes as the ship until a workspace admin runs \`crew agents sync\``;
|
|
11331
|
-
case "forced":
|
|
11332
|
-
return `${label}: --force overwrote local edits (previous prompt was: ${JSON.stringify(o.previousPrompt ?? "")})`;
|
|
11333
|
-
}
|
|
11334
|
-
}
|
|
11335
|
-
function describeCrewLink(o) {
|
|
11336
|
-
const label = PERSONA_NAME[o.role];
|
|
11337
|
-
switch (o.action) {
|
|
11338
|
-
case "linked":
|
|
11339
|
-
return `${label}: Crew row now references its Agents row`;
|
|
11340
|
-
case "already_linked":
|
|
11341
|
-
return `${label}: Crew row already references its Agents row`;
|
|
11342
|
-
case "no_seat":
|
|
11343
|
-
return `${label}: no seat configured for this role \u2014 skipped linking`;
|
|
11344
|
-
case "no_agent_field":
|
|
11345
|
-
return `${label}: ${CREW_FIELD_MISSING_NOTE}`;
|
|
11346
|
-
case "no_agents_row":
|
|
11347
|
-
return `${label}: no Agents row to link yet \u2014 a workspace admin's \`crew agents sync\` creates it; run it here afterwards to link this seat`;
|
|
11348
|
-
case "persona_diverged":
|
|
11349
|
-
return `${label}: persona has local edits and was not synced this pass \u2014 skipped linking until it's resolved`;
|
|
11350
|
-
}
|
|
11195
|
+
return { text: expand2(text2, []), warnings };
|
|
11351
11196
|
}
|
|
11352
11197
|
|
|
11353
11198
|
// src/skills.ts
|
|
11354
|
-
|
|
11199
|
+
import { readFileSync as readFileSync26, readdirSync as readdirSync8, existsSync as existsSync25 } from "fs";
|
|
11200
|
+
import { join as join28 } from "path";
|
|
11201
|
+
import { parse as parseYaml } from "yaml";
|
|
11202
|
+
import { TablationClient as TablationClient3, StaleWriteError as StaleWriteError3, TablationApiError as TablationApiError2 } from "@tablation/client";
|
|
11203
|
+
|
|
11204
|
+
// src/prompt-additions.ts
|
|
11205
|
+
var PROMPT_ADDITIONS_SEPARATOR = "---\n\nAdditional instructions from this workspace. Where they conflict with anything above, these take precedence.";
|
|
11206
|
+
function appendAdditions(text2, additions) {
|
|
11207
|
+
if (typeof additions !== "string" || additions.trim() === "") return text2;
|
|
11208
|
+
return `${text2}
|
|
11209
|
+
|
|
11210
|
+
${PROMPT_ADDITIONS_SEPARATOR}
|
|
11211
|
+
|
|
11212
|
+
${additions}`;
|
|
11213
|
+
}
|
|
11214
|
+
|
|
11215
|
+
// src/agents.ts
|
|
11216
|
+
import { readFileSync as readFileSync25, existsSync as existsSync24 } from "fs";
|
|
11217
|
+
import { join as join27 } from "path";
|
|
11218
|
+
import { TablationClient as TablationClient2, StaleWriteError as StaleWriteError2, TablationApiError } from "@tablation/client";
|
|
11219
|
+
var PERSONA_NAME = {
|
|
11220
|
+
dev: "Developer",
|
|
11221
|
+
design: "Design",
|
|
11222
|
+
qa: "QA",
|
|
11223
|
+
triage: "Triage",
|
|
11224
|
+
pair: "Pair"
|
|
11355
11225
|
};
|
|
11356
|
-
|
|
11357
|
-
|
|
11358
|
-
|
|
11359
|
-
|
|
11360
|
-
|
|
11361
|
-
const
|
|
11362
|
-
|
|
11363
|
-
if (
|
|
11364
|
-
|
|
11365
|
-
|
|
11226
|
+
var CREW_AGENT_FIELD_NAME = "Agent";
|
|
11227
|
+
var CREW_AGENT_COLUMN = "agent_id";
|
|
11228
|
+
var AgentsSyncError = class extends Error {
|
|
11229
|
+
};
|
|
11230
|
+
function personaDefaultPrompt(promptsDir, role) {
|
|
11231
|
+
const briefPath = join27(promptsDir, "personas", `lane-${role}.md`);
|
|
11232
|
+
if (!existsSync24(briefPath)) throw new AgentsSyncError(`no brief at ${briefPath}`);
|
|
11233
|
+
if (SELF_CONTAINED_ROLES.has(role)) return readFileSync25(briefPath, "utf8");
|
|
11234
|
+
const commonPath = join27(promptsDir, "personas", "common.md");
|
|
11235
|
+
if (!existsSync24(commonPath)) return readFileSync25(briefPath, "utf8");
|
|
11236
|
+
return `${readFileSync25(commonPath, "utf8")}${readFileSync25(briefPath, "utf8")}`;
|
|
11237
|
+
}
|
|
11238
|
+
async function resolveAgentId(route2, role, opts) {
|
|
11239
|
+
const cached = route2.resolved?.agentPersonas?.[role]?.agentId;
|
|
11240
|
+
if (cached) return cached;
|
|
11241
|
+
const seatId = route2.resolved?.seats?.[role];
|
|
11242
|
+
if (!seatId || !route2.resolved) return void 0;
|
|
11243
|
+
const client2 = new TablationClient2({
|
|
11244
|
+
baseUrl: `${route2.baseUrl}/api`,
|
|
11245
|
+
apiKey: resolveApiKey(route2),
|
|
11246
|
+
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11247
|
+
});
|
|
11248
|
+
try {
|
|
11249
|
+
const row = await client2.records.get(route2.resolved.models.crew, seatId);
|
|
11250
|
+
return row.agent_id ?? void 0;
|
|
11251
|
+
} catch {
|
|
11252
|
+
return void 0;
|
|
11366
11253
|
}
|
|
11367
|
-
return { name: meta.name, description: meta.description, prompt: body, file: path };
|
|
11368
11254
|
}
|
|
11369
|
-
function
|
|
11370
|
-
const
|
|
11371
|
-
if (!
|
|
11372
|
-
|
|
11255
|
+
async function fetchPersonaPrompt(route2, role, opts) {
|
|
11256
|
+
const agentId = await resolveAgentId(route2, role, opts);
|
|
11257
|
+
if (!agentId || !route2.resolved) return {};
|
|
11258
|
+
const client2 = new TablationClient2({
|
|
11259
|
+
baseUrl: `${route2.baseUrl}/api`,
|
|
11260
|
+
apiKey: resolveApiKey(route2),
|
|
11261
|
+
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11262
|
+
});
|
|
11263
|
+
let row;
|
|
11264
|
+
let agentsModelId;
|
|
11265
|
+
try {
|
|
11266
|
+
const agentsModel = await client2.dataModels.get("agents", route2.resolved.workspaceId);
|
|
11267
|
+
agentsModelId = agentsModel.id;
|
|
11268
|
+
row = await client2.records.get(agentsModelId, agentId);
|
|
11269
|
+
} catch {
|
|
11270
|
+
return {};
|
|
11271
|
+
}
|
|
11272
|
+
const additions = typeof row.prompt_additions === "string" && row.prompt_additions.trim() !== "" ? row.prompt_additions : void 0;
|
|
11273
|
+
const divergedPrompt = await divergedRowPrompt(route2, role, row, agentId, agentsModelId, opts);
|
|
11274
|
+
return { divergedPrompt, additions };
|
|
11373
11275
|
}
|
|
11374
|
-
|
|
11276
|
+
function personaPromptOptions(p) {
|
|
11277
|
+
return { divergedPrompt: p.divergedPrompt, personaAdditions: p.additions };
|
|
11278
|
+
}
|
|
11279
|
+
async function divergedRowPrompt(route2, role, row, agentId, agentsModelId, opts) {
|
|
11280
|
+
if (!route2.resolved) return void 0;
|
|
11281
|
+
const defaultPrompt = personaDefaultPrompt(route2.promptsDir, role);
|
|
11282
|
+
if (row.prompt === defaultPrompt) return void 0;
|
|
11283
|
+
const cached = route2.resolved.agentPersonas?.[role];
|
|
11284
|
+
if (cached?.agentId === agentId && cached.historyId) {
|
|
11285
|
+
const lastSynced = await fetchLastSyncedPrompt(route2, agentsModelId, agentId, cached.historyId, opts.userAgent);
|
|
11286
|
+
if (lastSynced !== void 0 && lastSynced === row.prompt) return void 0;
|
|
11287
|
+
}
|
|
11288
|
+
return row.prompt;
|
|
11289
|
+
}
|
|
11290
|
+
async function fetchLastSyncedPrompt(route2, agentsModelId, recordId, historyId, userAgent) {
|
|
11291
|
+
try {
|
|
11292
|
+
const entries = await fetchHistoryEntries(route2, agentsModelId, recordId, userAgent);
|
|
11293
|
+
return entries.find((e) => e.history_id === historyId)?.prompt;
|
|
11294
|
+
} catch {
|
|
11295
|
+
return void 0;
|
|
11296
|
+
}
|
|
11297
|
+
}
|
|
11298
|
+
function choiceValue(v) {
|
|
11299
|
+
const raw = typeof v === "string" ? v : v && typeof v === "object" ? v.value ?? v.key : void 0;
|
|
11300
|
+
return typeof raw === "string" && raw.trim() ? raw.trim().toLowerCase() : void 0;
|
|
11301
|
+
}
|
|
11302
|
+
async function fetchSeatPersona(route2, role, opts) {
|
|
11303
|
+
const agentId = await resolveAgentId(route2, role, opts);
|
|
11304
|
+
if (!agentId || !route2.resolved) return void 0;
|
|
11305
|
+
const client2 = new TablationClient2({
|
|
11306
|
+
baseUrl: `${route2.baseUrl}/api`,
|
|
11307
|
+
apiKey: resolveApiKey(route2),
|
|
11308
|
+
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11309
|
+
});
|
|
11310
|
+
try {
|
|
11311
|
+
const agentsModel = await client2.dataModels.get("agents", route2.resolved.workspaceId);
|
|
11312
|
+
const row = await client2.records.get(agentsModel.id, agentId);
|
|
11313
|
+
const tier = choiceValue(row.tier);
|
|
11314
|
+
const vendor = choiceValue(row.vendor);
|
|
11315
|
+
const persona = {
|
|
11316
|
+
...row.model ? { model: row.model } : {},
|
|
11317
|
+
...tier && TIERS.includes(tier) ? { tier } : {},
|
|
11318
|
+
...vendor ? { vendor } : {}
|
|
11319
|
+
};
|
|
11320
|
+
return Object.keys(persona).length > 0 ? persona : void 0;
|
|
11321
|
+
} catch {
|
|
11322
|
+
return void 0;
|
|
11323
|
+
}
|
|
11324
|
+
}
|
|
11325
|
+
async function currentPersonaPrompt(route2, role, opts) {
|
|
11326
|
+
const { divergedPrompt, additions } = await fetchPersonaPrompt(route2, role, opts);
|
|
11327
|
+
return appendAdditions(divergedPrompt ?? personaDefaultPrompt(route2.promptsDir, role), additions);
|
|
11328
|
+
}
|
|
11329
|
+
async function fetchHistoryEntries(route2, agentsModelId, recordId, userAgent, limit = 50) {
|
|
11330
|
+
const url = `${route2.baseUrl.replace(/\/+$/, "")}/api/data-models/${agentsModelId}/records/${recordId}/history?limit=${limit}`;
|
|
11331
|
+
const res = await fetch(url, {
|
|
11332
|
+
headers: {
|
|
11333
|
+
Authorization: `Bearer ${resolveApiKey(route2)}`,
|
|
11334
|
+
"User-Agent": userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0"
|
|
11335
|
+
}
|
|
11336
|
+
});
|
|
11337
|
+
if (!res.ok) throw new AgentsSyncError(`history lookup for ${recordId}: ${res.status} ${res.statusText}`);
|
|
11338
|
+
return await res.json();
|
|
11339
|
+
}
|
|
11340
|
+
async function fetchLatestHistoryId(route2, agentsModelId, recordId, userAgent) {
|
|
11341
|
+
try {
|
|
11342
|
+
const entries = await fetchHistoryEntries(route2, agentsModelId, recordId, userAgent, 1);
|
|
11343
|
+
return entries[0]?.history_id;
|
|
11344
|
+
} catch {
|
|
11345
|
+
return void 0;
|
|
11346
|
+
}
|
|
11347
|
+
}
|
|
11348
|
+
function isAdminRole(role) {
|
|
11349
|
+
return role === void 0 || role === "WORKSPACE_ADMIN" || role === "PLATFORM_ADMIN";
|
|
11350
|
+
}
|
|
11351
|
+
async function fetchKeyRole(route2, userAgent) {
|
|
11352
|
+
if (!route2.resolved) return void 0;
|
|
11353
|
+
try {
|
|
11354
|
+
const res = await fetch(`${route2.baseUrl.replace(/\/+$/, "")}/api/auth/me?workspaceId=${route2.resolved.workspaceId}`, {
|
|
11355
|
+
headers: { Authorization: `Bearer ${resolveApiKey(route2)}`, "User-Agent": userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11356
|
+
});
|
|
11357
|
+
if (!res.ok) return void 0;
|
|
11358
|
+
const me = await res.json();
|
|
11359
|
+
return typeof me.role === "string" ? me.role : void 0;
|
|
11360
|
+
} catch {
|
|
11361
|
+
return void 0;
|
|
11362
|
+
}
|
|
11363
|
+
}
|
|
11364
|
+
function isForbidden(e) {
|
|
11365
|
+
return e instanceof TablationApiError && e.status === 403;
|
|
11366
|
+
}
|
|
11367
|
+
function promptSourceFields(model, prompt) {
|
|
11368
|
+
return model.fields?.some((f) => f.columnName === "prompt_baseline") ? { prompt_source: "crew", prompt_baseline: prompt } : {};
|
|
11369
|
+
}
|
|
11370
|
+
function hasPromptBaselineColumn(model) {
|
|
11371
|
+
return model.fields?.some((f) => f.columnName === "prompt_baseline") === true;
|
|
11372
|
+
}
|
|
11373
|
+
function needsBaselineBackfill(model, row) {
|
|
11374
|
+
return hasPromptBaselineColumn(model) && row.prompt_customized !== true && (typeof row.prompt_baseline !== "string" || !row.prompt_source);
|
|
11375
|
+
}
|
|
11376
|
+
function isPromptGateRejection(e) {
|
|
11377
|
+
return e instanceof TablationApiError && e.status === 422;
|
|
11378
|
+
}
|
|
11379
|
+
var RELEASE_AGENT_NAME = "Release agent";
|
|
11380
|
+
var RELEASE_AGENT_PROMPT = "Principal for the crew release phase (merge, deploy, release comments). It runs no model; this row only gives those tracker writes an agent identity.";
|
|
11381
|
+
async function syncPersonas(route2, opts) {
|
|
11375
11382
|
if (!route2.resolved) {
|
|
11376
|
-
throw new
|
|
11383
|
+
throw new AgentsSyncError(`route "${route2.route}" has no resolved ids \u2014 run \`crew connect\` first`);
|
|
11377
11384
|
}
|
|
11378
11385
|
const workspaceId = route2.resolved.workspaceId;
|
|
11379
|
-
const client2 = new
|
|
11386
|
+
const client2 = new TablationClient2({
|
|
11380
11387
|
baseUrl: `${route2.baseUrl}/api`,
|
|
11381
11388
|
apiKey: resolveApiKey(route2),
|
|
11382
11389
|
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11383
11390
|
});
|
|
11384
|
-
let
|
|
11391
|
+
let agentsModel;
|
|
11385
11392
|
try {
|
|
11386
|
-
|
|
11393
|
+
agentsModel = await client2.dataModels.get("agents", workspaceId);
|
|
11387
11394
|
} catch (e) {
|
|
11388
|
-
if (e instanceof
|
|
11389
|
-
throw new
|
|
11390
|
-
`workspace ${workspaceId} has no
|
|
11395
|
+
if (e instanceof TablationApiError && e.status === 404) {
|
|
11396
|
+
throw new AgentsSyncError(
|
|
11397
|
+
`workspace ${workspaceId} has no Agents table yet \u2014 every workspace auto-provisions one (ISSUE-465); an older workspace may still need its one-time backfill`
|
|
11391
11398
|
);
|
|
11392
11399
|
}
|
|
11393
11400
|
throw e;
|
|
11394
11401
|
}
|
|
11395
|
-
const
|
|
11396
|
-
const
|
|
11397
|
-
const cache = route2.resolved.agentSkills ?? {};
|
|
11402
|
+
const rows = await client2.records.list(agentsModel.id, { limit: 200 });
|
|
11403
|
+
const cache = route2.resolved.agentPersonas ?? {};
|
|
11398
11404
|
const outcomes = [];
|
|
11399
|
-
const
|
|
11400
|
-
for (const
|
|
11401
|
-
const
|
|
11405
|
+
const agentPersonas = { ...cache };
|
|
11406
|
+
for (const role of ROLE_NAMES) {
|
|
11407
|
+
const name = PERSONA_NAME[role];
|
|
11408
|
+
const defaultPrompt = personaDefaultPrompt(route2.promptsDir, role);
|
|
11409
|
+
const row = rows.find((r) => r.name === name);
|
|
11410
|
+
if (opts.readOnly) {
|
|
11411
|
+
if (!row) {
|
|
11412
|
+
outcomes.push({ role, action: "missing", agentId: "" });
|
|
11413
|
+
continue;
|
|
11414
|
+
}
|
|
11415
|
+
const prior = cache[role]?.agentId === row.id ? cache[role] : void 0;
|
|
11416
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: prior?.lastSyncedUpdatedAt ?? row.updated_at, ...prior?.historyId ? { historyId: prior.historyId } : {} };
|
|
11417
|
+
outcomes.push({ role, action: "adopted", agentId: row.id });
|
|
11418
|
+
continue;
|
|
11419
|
+
}
|
|
11402
11420
|
if (!row) {
|
|
11403
11421
|
if (opts.dryRun) {
|
|
11404
|
-
outcomes.push({
|
|
11422
|
+
outcomes.push({ role, action: "created", agentId: "(dry run)" });
|
|
11405
11423
|
continue;
|
|
11406
11424
|
}
|
|
11407
|
-
const created = await client2.records.create(
|
|
11408
|
-
|
|
11409
|
-
|
|
11410
|
-
|
|
11411
|
-
...promptSourceFields(skillsModel, skill.prompt)
|
|
11412
|
-
});
|
|
11413
|
-
agentSkills[skill.name] = { skillId: created.id, lastSyncedUpdatedAt: created.updated_at };
|
|
11414
|
-
outcomes.push({ name: skill.name, action: "created", skillId: created.id });
|
|
11425
|
+
const created = await client2.records.create(agentsModel.id, { name, prompt: defaultPrompt, ...promptSourceFields(agentsModel, defaultPrompt) });
|
|
11426
|
+
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, created.id, opts.userAgent);
|
|
11427
|
+
agentPersonas[role] = { agentId: created.id, lastSyncedUpdatedAt: created.updated_at, ...historyId ? { historyId } : {} };
|
|
11428
|
+
outcomes.push({ role, action: "created", agentId: created.id });
|
|
11415
11429
|
continue;
|
|
11416
11430
|
}
|
|
11417
|
-
if (row.
|
|
11431
|
+
if (row.prompt === defaultPrompt) {
|
|
11418
11432
|
let anchoredAt = row.updated_at;
|
|
11419
|
-
if (!opts.dryRun && needsBaselineBackfill(
|
|
11433
|
+
if (!opts.dryRun && needsBaselineBackfill(agentsModel, row)) {
|
|
11420
11434
|
try {
|
|
11421
|
-
anchoredAt = (await client2.records.update(
|
|
11422
|
-
skillsModel.id,
|
|
11423
|
-
row.id,
|
|
11424
|
-
promptSourceFields(skillsModel, skill.prompt),
|
|
11425
|
-
row.updated_at
|
|
11426
|
-
)).updated_at;
|
|
11435
|
+
anchoredAt = (await client2.records.update(agentsModel.id, row.id, promptSourceFields(agentsModel, defaultPrompt), row.updated_at)).updated_at;
|
|
11427
11436
|
} catch (e) {
|
|
11428
|
-
if (!(e instanceof
|
|
11437
|
+
if (!(e instanceof StaleWriteError2) && !isPromptGateRejection(e)) throw e;
|
|
11429
11438
|
}
|
|
11430
11439
|
}
|
|
11431
|
-
|
|
11432
|
-
|
|
11440
|
+
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11441
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: anchoredAt, ...historyId ? { historyId } : {} };
|
|
11442
|
+
outcomes.push({ role, action: "unchanged", agentId: row.id });
|
|
11433
11443
|
continue;
|
|
11434
11444
|
}
|
|
11435
11445
|
if (row.prompt_customized === true) {
|
|
11436
|
-
|
|
11437
|
-
|
|
11446
|
+
const prior = cache[role]?.agentId === row.id ? cache[role] : void 0;
|
|
11447
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...prior?.historyId ? { historyId: prior.historyId } : {} };
|
|
11448
|
+
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11438
11449
|
continue;
|
|
11439
11450
|
}
|
|
11440
|
-
const body = { description: skill.description, prompt: skill.prompt, ...promptSourceFields(skillsModel, skill.prompt) };
|
|
11441
11451
|
if (opts.force) {
|
|
11442
11452
|
if (opts.dryRun) {
|
|
11443
|
-
outcomes.push({
|
|
11453
|
+
outcomes.push({ role, action: "forced", agentId: row.id, previousPrompt: row.prompt });
|
|
11444
11454
|
continue;
|
|
11445
11455
|
}
|
|
11456
|
+
let updated;
|
|
11446
11457
|
try {
|
|
11447
|
-
|
|
11448
|
-
agentSkills[skill.name] = { skillId: row.id, lastSyncedUpdatedAt: updated.updated_at };
|
|
11449
|
-
outcomes.push({ name: skill.name, action: "forced", skillId: row.id });
|
|
11458
|
+
updated = await client2.records.update(agentsModel.id, row.id, { prompt: defaultPrompt, ...promptSourceFields(agentsModel, defaultPrompt) });
|
|
11450
11459
|
} catch (e) {
|
|
11451
11460
|
if (!isPromptGateRejection(e)) throw e;
|
|
11452
|
-
outcomes.push({
|
|
11461
|
+
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11462
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...cache[role]?.agentId === row.id && cache[role]?.historyId ? { historyId: cache[role].historyId } : {} };
|
|
11463
|
+
continue;
|
|
11453
11464
|
}
|
|
11465
|
+
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11466
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: updated.updated_at, ...historyId ? { historyId } : {} };
|
|
11467
|
+
outcomes.push({ role, action: "forced", agentId: row.id, previousPrompt: row.prompt });
|
|
11454
11468
|
continue;
|
|
11455
11469
|
}
|
|
11456
|
-
|
|
11457
|
-
|
|
11470
|
+
const cached = cache[role]?.agentId === row.id ? cache[role] : void 0;
|
|
11471
|
+
const baselineKnown = hasPromptBaselineColumn(agentsModel) && typeof row.prompt_baseline === "string";
|
|
11472
|
+
if (baselineKnown) {
|
|
11458
11473
|
if (row.prompt !== row.prompt_baseline) {
|
|
11459
|
-
outcomes.push({
|
|
11474
|
+
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11460
11475
|
continue;
|
|
11461
11476
|
}
|
|
11462
|
-
knownBaseline = row.updated_at;
|
|
11463
11477
|
} else {
|
|
11464
|
-
|
|
11465
|
-
|
|
11466
|
-
|
|
11467
|
-
|
|
11468
|
-
|
|
11478
|
+
if (!cached?.historyId) {
|
|
11479
|
+
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11480
|
+
continue;
|
|
11481
|
+
}
|
|
11482
|
+
let lastSyncedPrompt;
|
|
11483
|
+
try {
|
|
11484
|
+
const entries = await fetchHistoryEntries(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11485
|
+
lastSyncedPrompt = entries.find((e) => e.history_id === cached.historyId)?.prompt;
|
|
11486
|
+
} catch {
|
|
11487
|
+
lastSyncedPrompt = void 0;
|
|
11488
|
+
}
|
|
11489
|
+
if (lastSyncedPrompt === void 0 || lastSyncedPrompt !== row.prompt) {
|
|
11490
|
+
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11491
|
+
continue;
|
|
11492
|
+
}
|
|
11469
11493
|
}
|
|
11470
11494
|
if (opts.dryRun) {
|
|
11471
|
-
outcomes.push({
|
|
11495
|
+
outcomes.push({ role, action: "updated", agentId: row.id });
|
|
11472
11496
|
continue;
|
|
11473
11497
|
}
|
|
11474
11498
|
try {
|
|
11475
11499
|
const updated = await client2.records.update(
|
|
11476
|
-
|
|
11500
|
+
agentsModel.id,
|
|
11477
11501
|
row.id,
|
|
11478
|
-
|
|
11479
|
-
|
|
11502
|
+
{ prompt: defaultPrompt, ...promptSourceFields(agentsModel, defaultPrompt) },
|
|
11503
|
+
row.updated_at
|
|
11480
11504
|
);
|
|
11481
|
-
|
|
11482
|
-
|
|
11505
|
+
const historyId = await fetchLatestHistoryId(route2, agentsModel.id, row.id, opts.userAgent);
|
|
11506
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: updated.updated_at, ...historyId ? { historyId } : {} };
|
|
11507
|
+
outcomes.push({ role, action: "updated", agentId: row.id });
|
|
11483
11508
|
} catch (e) {
|
|
11484
|
-
if (e instanceof
|
|
11485
|
-
outcomes.push({
|
|
11509
|
+
if (e instanceof StaleWriteError2) {
|
|
11510
|
+
outcomes.push({ role, action: "diverged", agentId: row.id });
|
|
11486
11511
|
continue;
|
|
11487
11512
|
}
|
|
11488
11513
|
if (isPromptGateRejection(e)) {
|
|
11489
|
-
|
|
11514
|
+
agentPersonas[role] = { agentId: row.id, lastSyncedUpdatedAt: row.updated_at, ...cached?.historyId ? { historyId: cached.historyId } : {} };
|
|
11515
|
+
outcomes.push({ role, action: "overridden", agentId: row.id });
|
|
11490
11516
|
continue;
|
|
11491
11517
|
}
|
|
11492
11518
|
throw e;
|
|
11493
11519
|
}
|
|
11494
11520
|
}
|
|
11495
|
-
|
|
11521
|
+
const crewLinks = opts.dryRun ? [] : await linkCrewSeats(route2, client2, agentsModel.id, agentPersonas, opts.userAgent, opts.readOnly === true);
|
|
11522
|
+
const release = opts.dryRun ? { agentId: route2.resolved.releaseAgentId } : await linkReleaseSeat(route2, client2, agentsModel, opts.userAgent, opts.readOnly === true);
|
|
11523
|
+
return {
|
|
11524
|
+
outcomes,
|
|
11525
|
+
agentPersonas,
|
|
11526
|
+
crewLinks,
|
|
11527
|
+
...release.agentId ? { releaseAgentId: release.agentId } : {},
|
|
11528
|
+
...release.note ? { releaseNote: release.note } : {},
|
|
11529
|
+
...opts.readOnly ? { readOnly: true } : {}
|
|
11530
|
+
};
|
|
11496
11531
|
}
|
|
11497
|
-
function
|
|
11498
|
-
|
|
11499
|
-
|
|
11500
|
-
|
|
11501
|
-
|
|
11502
|
-
|
|
11503
|
-
|
|
11504
|
-
|
|
11505
|
-
|
|
11506
|
-
|
|
11507
|
-
|
|
11508
|
-
|
|
11509
|
-
|
|
11510
|
-
|
|
11532
|
+
async function linkReleaseSeat(route2, client2, agentsModel, userAgent, readOnly) {
|
|
11533
|
+
const seatId = route2.resolved.releaseSeat;
|
|
11534
|
+
if (!seatId) return {};
|
|
11535
|
+
const rows = await client2.records.list(agentsModel.id, { limit: 200 });
|
|
11536
|
+
let agentId = rows.find((r) => r.name === RELEASE_AGENT_NAME)?.id;
|
|
11537
|
+
if (!agentId) {
|
|
11538
|
+
if (readOnly) return { note: `Release: no "${RELEASE_AGENT_NAME}" Agents row in this workspace \u2014 writes as the ship until a workspace admin runs \`crew agents sync\`` };
|
|
11539
|
+
try {
|
|
11540
|
+
agentId = (await client2.records.create(agentsModel.id, {
|
|
11541
|
+
name: RELEASE_AGENT_NAME,
|
|
11542
|
+
prompt: RELEASE_AGENT_PROMPT,
|
|
11543
|
+
...promptSourceFields(agentsModel, RELEASE_AGENT_PROMPT)
|
|
11544
|
+
})).id;
|
|
11545
|
+
} catch (e) {
|
|
11546
|
+
if (isForbidden(e)) return { note: `Release: could not create the "${RELEASE_AGENT_NAME}" Agents row (${NO_WRITE_NOTE}) \u2014 writes as the ship` };
|
|
11547
|
+
throw e;
|
|
11548
|
+
}
|
|
11511
11549
|
}
|
|
11512
|
-
|
|
11513
|
-
|
|
11514
|
-
|
|
11515
|
-
const client2 = new TablationClient3({
|
|
11516
|
-
baseUrl: `${route2.baseUrl}/api`,
|
|
11517
|
-
apiKey: resolveApiKey(route2),
|
|
11518
|
-
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11519
|
-
});
|
|
11520
|
-
let rows;
|
|
11550
|
+
const crewModelId = route2.resolved.models.crew;
|
|
11551
|
+
const crewModel = await client2.dataModels.get(crewModelId);
|
|
11552
|
+
let columnName;
|
|
11521
11553
|
try {
|
|
11522
|
-
|
|
11523
|
-
|
|
11524
|
-
|
|
11525
|
-
|
|
11526
|
-
}
|
|
11527
|
-
const local = new Map(listLocalSkills(route2.promptsDir).map((s) => [s.name, s]));
|
|
11528
|
-
const cache = route2.resolved.agentSkills ?? {};
|
|
11529
|
-
const out = {};
|
|
11530
|
-
for (const row of rows) {
|
|
11531
|
-
const name = row.name;
|
|
11532
|
-
const edited = isEditedSkillRow(row, local.get(name)?.prompt, cache[name]);
|
|
11533
|
-
const base = edited ? row.prompt : local.get(name)?.prompt ?? row.prompt;
|
|
11534
|
-
const composed = appendAdditions(base, row.prompt_additions);
|
|
11535
|
-
if (edited || composed !== base) out[name] = composed;
|
|
11554
|
+
columnName = await ensureCrewAgentField(route2, client2, crewModel, agentsModel.id, userAgent);
|
|
11555
|
+
} catch (e) {
|
|
11556
|
+
if (e instanceof CrewAgentFieldMissing) return { note: `Release: ${CREW_FIELD_MISSING_NOTE}` };
|
|
11557
|
+
throw e;
|
|
11536
11558
|
}
|
|
11537
|
-
|
|
11538
|
-
}
|
|
11539
|
-
|
|
11540
|
-
if (row.prompt === localPrompt) return false;
|
|
11541
|
-
if (row.prompt_customized !== true && row.prompt === row.prompt_baseline) return false;
|
|
11542
|
-
return !(cached?.skillId === row.id && cached.lastSyncedUpdatedAt === row.updated_at);
|
|
11559
|
+
const seatRow = await client2.records.get(crewModelId, seatId);
|
|
11560
|
+
if (seatRow[CREW_AGENT_COLUMN] !== agentId) await client2.records.update(crewModelId, seatId, { [columnName]: agentId });
|
|
11561
|
+
return { agentId };
|
|
11543
11562
|
}
|
|
11544
|
-
|
|
11545
|
-
|
|
11546
|
-
|
|
11547
|
-
|
|
11548
|
-
|
|
11549
|
-
|
|
11563
|
+
var NO_WRITE_NOTE = "this key has no write access to the Agents table";
|
|
11564
|
+
var CREW_FIELD_MISSING_NOTE = "Crew table has no Agent field yet \u2014 a workspace admin's `crew agents sync` adds it";
|
|
11565
|
+
var CrewAgentFieldMissing = class extends Error {
|
|
11566
|
+
};
|
|
11567
|
+
async function linkCrewSeats(route2, client2, agentsModelId, agentPersonas, userAgent, readOnly) {
|
|
11568
|
+
const seats2 = route2.resolved.seats;
|
|
11569
|
+
const rolesWithSeats = ROLE_NAMES.filter((role) => seats2[role] && agentPersonas[role]);
|
|
11570
|
+
if (rolesWithSeats.length === 0) {
|
|
11571
|
+
if (readOnly) return ROLE_NAMES.map((role) => ({ role, action: seats2[role] ? "no_agents_row" : "no_seat" }));
|
|
11572
|
+
return ROLE_NAMES.map((role) => ({ role, action: seats2[role] ? "persona_diverged" : "no_seat" }));
|
|
11573
|
+
}
|
|
11574
|
+
const crewModelId = route2.resolved.models.crew;
|
|
11575
|
+
const crewModel = await client2.dataModels.get(crewModelId);
|
|
11576
|
+
let columnName;
|
|
11577
|
+
try {
|
|
11578
|
+
columnName = await ensureCrewAgentField(route2, client2, crewModel, agentsModelId, userAgent);
|
|
11579
|
+
} catch (e) {
|
|
11580
|
+
if (e instanceof CrewAgentFieldMissing) {
|
|
11581
|
+
return ROLE_NAMES.map((role) => ({ role, action: seats2[role] ? "no_agent_field" : "no_seat" }));
|
|
11550
11582
|
}
|
|
11583
|
+
throw e;
|
|
11551
11584
|
}
|
|
11552
|
-
|
|
11553
|
-
|
|
11554
|
-
|
|
11555
|
-
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
|
|
11559
|
-
import { tmpdir as tmpdir2 } from "os";
|
|
11560
|
-
import { basename as basename8, dirname as dirname13, join as join28 } from "path";
|
|
11561
|
-
import { promisify } from "util";
|
|
11562
|
-
|
|
11563
|
-
// src/run-limit.ts
|
|
11564
|
-
var DEFAULT_MAX_RUN_MINUTES = 240;
|
|
11565
|
-
var KILL_GRACE_MS = 5e3;
|
|
11566
|
-
var WALL_CLOCK_REASON = "wall-clock";
|
|
11567
|
-
function resolveMaxRunMinutes(route2, toolchain) {
|
|
11568
|
-
return route2 ?? toolchain ?? DEFAULT_MAX_RUN_MINUTES;
|
|
11569
|
-
}
|
|
11570
|
-
function deadlineFor(spawnedAt, maxRunMinutes) {
|
|
11571
|
-
if (!maxRunMinutes || maxRunMinutes <= 0) return void 0;
|
|
11572
|
-
const t = Date.parse(spawnedAt);
|
|
11573
|
-
return Number.isNaN(t) ? void 0 : new Date(t + maxRunMinutes * 6e4).toISOString();
|
|
11574
|
-
}
|
|
11575
|
-
function msUntilDeadline(deadline, now = Date.now()) {
|
|
11576
|
-
if (!deadline) return void 0;
|
|
11577
|
-
const t = Date.parse(deadline);
|
|
11578
|
-
return Number.isNaN(t) ? void 0 : t - now;
|
|
11579
|
-
}
|
|
11580
|
-
async function killRunGroup(pid, o = {}) {
|
|
11581
|
-
const alive = o.isAlive ?? ((p) => {
|
|
11582
|
-
try {
|
|
11583
|
-
process.kill(p, 0);
|
|
11584
|
-
return true;
|
|
11585
|
-
} catch (e) {
|
|
11586
|
-
return e.code === "EPERM";
|
|
11585
|
+
const outcomes = [];
|
|
11586
|
+
for (const role of ROLE_NAMES) {
|
|
11587
|
+
const seatId = seats2[role];
|
|
11588
|
+
const agentId = agentPersonas[role]?.agentId;
|
|
11589
|
+
if (!seatId) {
|
|
11590
|
+
outcomes.push({ role, action: "no_seat" });
|
|
11591
|
+
continue;
|
|
11587
11592
|
}
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
process.kill(-pid, sig);
|
|
11592
|
-
} catch {
|
|
11593
|
-
try {
|
|
11594
|
-
process.kill(pid, sig);
|
|
11595
|
-
} catch {
|
|
11596
|
-
}
|
|
11593
|
+
if (!agentId) {
|
|
11594
|
+
outcomes.push({ role, action: readOnly ? "no_agents_row" : "persona_diverged" });
|
|
11595
|
+
continue;
|
|
11597
11596
|
}
|
|
11598
|
-
|
|
11599
|
-
|
|
11600
|
-
|
|
11601
|
-
|
|
11602
|
-
|
|
11597
|
+
const seatRow = await client2.records.get(crewModelId, seatId);
|
|
11598
|
+
if (seatRow[CREW_AGENT_COLUMN] === agentId) {
|
|
11599
|
+
outcomes.push({ role, action: "already_linked" });
|
|
11600
|
+
continue;
|
|
11601
|
+
}
|
|
11602
|
+
await client2.records.update(crewModelId, seatId, { [columnName]: agentId });
|
|
11603
|
+
outcomes.push({ role, action: "linked" });
|
|
11604
|
+
}
|
|
11605
|
+
return outcomes;
|
|
11603
11606
|
}
|
|
11604
|
-
|
|
11605
|
-
|
|
11606
|
-
|
|
11607
|
-
|
|
11608
|
-
|
|
11609
|
-
|
|
11610
|
-
|
|
11611
|
-
|
|
11612
|
-
|
|
11613
|
-
|
|
11614
|
-
|
|
11615
|
-
|
|
11616
|
-
|
|
11617
|
-
|
|
11618
|
-
|
|
11619
|
-
|
|
11620
|
-
|
|
11621
|
-
var HostRunner = class {
|
|
11622
|
-
kind = "host";
|
|
11623
|
-
start(plan, o) {
|
|
11624
|
-
const child = spawn3(plan.bin, plan.args, {
|
|
11625
|
-
cwd: plan.cwd,
|
|
11626
|
-
env: o.env,
|
|
11627
|
-
stdio: ["pipe", o.streamFd, "inherit"],
|
|
11628
|
-
detached: true
|
|
11629
|
-
});
|
|
11630
|
-
return { child, handle: { runner: "host", pid: child.pid } };
|
|
11631
|
-
}
|
|
11632
|
-
async kill(handle) {
|
|
11633
|
-
if (handle.pid !== void 0) await killRunGroup(handle.pid);
|
|
11634
|
-
}
|
|
11635
|
-
isAlive(handle) {
|
|
11636
|
-
if (handle.pid === void 0) return false;
|
|
11637
|
-
try {
|
|
11638
|
-
process.kill(handle.pid, 0);
|
|
11639
|
-
return true;
|
|
11640
|
-
} catch (e) {
|
|
11641
|
-
return e.code === "EPERM";
|
|
11642
|
-
}
|
|
11607
|
+
async function ensureCrewAgentField(route2, client2, crewModel, agentsModelId, userAgent) {
|
|
11608
|
+
const existing = crewModel.fields.find(
|
|
11609
|
+
(f) => f.fieldType?.kind === "REFERENCE" && f.fieldType.targetModelId === agentsModelId && f.fieldType.isMultiple === false
|
|
11610
|
+
);
|
|
11611
|
+
if (existing) return existing.columnName;
|
|
11612
|
+
const workspaceId = route2.resolved.workspaceId;
|
|
11613
|
+
const baseUrl = route2.baseUrl.replace(/\/+$/, "");
|
|
11614
|
+
const apiKey = resolveApiKey(route2);
|
|
11615
|
+
const headers = { Authorization: `Bearer ${apiKey}`, "User-Agent": userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" };
|
|
11616
|
+
const typesRes = await fetch(`${baseUrl}/api/workspaces/${workspaceId}/field-types`, { headers });
|
|
11617
|
+
if (!typesRes.ok) throw new AgentsSyncError(`field-types lookup failed: ${typesRes.status} ${typesRes.statusText}`);
|
|
11618
|
+
const types = await typesRes.json();
|
|
11619
|
+
const fieldType = types.find((t) => t.kind === "REFERENCE" && t.targetModelId === agentsModelId && t.isMultiple === false);
|
|
11620
|
+
if (!fieldType) {
|
|
11621
|
+
throw new AgentsSyncError(
|
|
11622
|
+
`workspace ${workspaceId} has no single-valued Agents-reference field type \u2014 every table auto-provisions one (see the pseudo-builtin reference types convention); an older Agents table may need its one-time backfill`
|
|
11623
|
+
);
|
|
11643
11624
|
}
|
|
11644
|
-
|
|
11645
|
-
|
|
11625
|
+
const createRes = await fetch(`${baseUrl}/api/data-models/${crewModel.id}/fields`, {
|
|
11626
|
+
method: "POST",
|
|
11627
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
11628
|
+
body: JSON.stringify({
|
|
11629
|
+
name: CREW_AGENT_FIELD_NAME,
|
|
11630
|
+
columnName: CREW_AGENT_COLUMN,
|
|
11631
|
+
fieldTypeId: fieldType.id,
|
|
11632
|
+
description: "The Agents-table row backing this seat's persona \u2014 set by `crew agents sync` (ISSUE-416), never edited by hand."
|
|
11633
|
+
})
|
|
11634
|
+
});
|
|
11635
|
+
if (createRes.status === 403) throw new CrewAgentFieldMissing();
|
|
11636
|
+
if (!createRes.ok) throw new AgentsSyncError(`creating the Crew table's Agent field failed: ${createRes.status} ${createRes.statusText}`);
|
|
11637
|
+
const created = await createRes.json();
|
|
11638
|
+
return created.columnName;
|
|
11639
|
+
}
|
|
11640
|
+
function describeSyncOutcome(o) {
|
|
11641
|
+
const label = PERSONA_NAME[o.role];
|
|
11642
|
+
switch (o.action) {
|
|
11643
|
+
case "created":
|
|
11644
|
+
return `${label}: created (${o.agentId})`;
|
|
11645
|
+
case "updated":
|
|
11646
|
+
return `${label}: prompt updated from crew's local default`;
|
|
11647
|
+
case "unchanged":
|
|
11648
|
+
return `${label}: already in sync`;
|
|
11649
|
+
case "diverged":
|
|
11650
|
+
return `${label}: HAS LOCAL EDITS \u2014 crew's default is newer but was NOT applied; review ${o.agentId} in the app before syncing again`;
|
|
11651
|
+
case "overridden":
|
|
11652
|
+
return `${label}: override in place \u2014 prompt not synced (clear "Customize prompt" on the Agents row to resume)`;
|
|
11653
|
+
case "adopted":
|
|
11654
|
+
return `${label}: using the workspace's existing Agents row (${o.agentId})`;
|
|
11655
|
+
case "missing":
|
|
11656
|
+
return `${label}: no Agents row in this workspace \u2014 writes as the ship until a workspace admin runs \`crew agents sync\``;
|
|
11657
|
+
case "forced":
|
|
11658
|
+
return `${label}: --force overwrote local edits (previous prompt was: ${JSON.stringify(o.previousPrompt ?? "")})`;
|
|
11646
11659
|
}
|
|
11647
|
-
|
|
11660
|
+
}
|
|
11661
|
+
function describeCrewLink(o) {
|
|
11662
|
+
const label = PERSONA_NAME[o.role];
|
|
11663
|
+
switch (o.action) {
|
|
11664
|
+
case "linked":
|
|
11665
|
+
return `${label}: Crew row now references its Agents row`;
|
|
11666
|
+
case "already_linked":
|
|
11667
|
+
return `${label}: Crew row already references its Agents row`;
|
|
11668
|
+
case "no_seat":
|
|
11669
|
+
return `${label}: no seat configured for this role \u2014 skipped linking`;
|
|
11670
|
+
case "no_agent_field":
|
|
11671
|
+
return `${label}: ${CREW_FIELD_MISSING_NOTE}`;
|
|
11672
|
+
case "no_agents_row":
|
|
11673
|
+
return `${label}: no Agents row to link yet \u2014 a workspace admin's \`crew agents sync\` creates it; run it here afterwards to link this seat`;
|
|
11674
|
+
case "persona_diverged":
|
|
11675
|
+
return `${label}: persona has local edits and was not synced this pass \u2014 skipped linking until it's resolved`;
|
|
11648
11676
|
}
|
|
11677
|
+
}
|
|
11678
|
+
|
|
11679
|
+
// src/skills.ts
|
|
11680
|
+
var SkillSyncError = class extends Error {
|
|
11649
11681
|
};
|
|
11650
|
-
function
|
|
11651
|
-
|
|
11682
|
+
function parseSkillFile(path) {
|
|
11683
|
+
const text2 = readFileSync26(path, "utf8");
|
|
11684
|
+
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text2);
|
|
11685
|
+
if (!match) throw new SkillSyncError(`${path}: missing YAML frontmatter (expected a leading --- block)`);
|
|
11686
|
+
const frontmatter = match[1];
|
|
11687
|
+
const body = match[2];
|
|
11688
|
+
const meta = parseYaml(frontmatter);
|
|
11689
|
+
if (typeof meta.name !== "string" || !meta.name) throw new SkillSyncError(`${path}: frontmatter is missing "name"`);
|
|
11690
|
+
if (typeof meta.description !== "string" || !meta.description) {
|
|
11691
|
+
throw new SkillSyncError(`${path}: frontmatter is missing "description"`);
|
|
11692
|
+
}
|
|
11693
|
+
return { name: meta.name, description: meta.description, prompt: body, file: path };
|
|
11652
11694
|
}
|
|
11653
|
-
function
|
|
11654
|
-
const
|
|
11655
|
-
|
|
11656
|
-
return
|
|
11695
|
+
function listLocalSkills(promptsDir) {
|
|
11696
|
+
const dir = join28(promptsDir, "skills");
|
|
11697
|
+
if (!existsSync25(dir)) return [];
|
|
11698
|
+
return readdirSync8(dir).filter((f) => f.endsWith(".md")).map((f) => parseSkillFile(join28(dir, f)));
|
|
11657
11699
|
}
|
|
11658
|
-
|
|
11659
|
-
|
|
11660
|
-
|
|
11661
|
-
/** Injected for tests; the real one reads the plan's checkout. */
|
|
11662
|
-
originOf;
|
|
11663
|
-
constructor(cfg = {}, originOf = gitOrigin) {
|
|
11664
|
-
this.cfg = { ...DEFAULT_SANDBOX_CONFIG, ...cfg };
|
|
11665
|
-
this.originOf = originOf;
|
|
11700
|
+
async function syncSkills(route2, opts) {
|
|
11701
|
+
if (!route2.resolved) {
|
|
11702
|
+
throw new SkillSyncError(`route "${route2.route}" has no resolved ids \u2014 run \`crew connect\` first`);
|
|
11666
11703
|
}
|
|
11667
|
-
|
|
11668
|
-
|
|
11704
|
+
const workspaceId = route2.resolved.workspaceId;
|
|
11705
|
+
const client2 = new TablationClient3({
|
|
11706
|
+
baseUrl: `${route2.baseUrl}/api`,
|
|
11707
|
+
apiKey: resolveApiKey(route2),
|
|
11708
|
+
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11709
|
+
});
|
|
11710
|
+
let skillsModel;
|
|
11711
|
+
try {
|
|
11712
|
+
skillsModel = await client2.dataModels.get("agent_skills", workspaceId);
|
|
11713
|
+
} catch (e) {
|
|
11714
|
+
if (e instanceof TablationApiError2 && e.status === 404) {
|
|
11715
|
+
throw new SkillSyncError(
|
|
11716
|
+
`workspace ${workspaceId} has no Agent Skills table yet \u2014 every workspace auto-provisions one; an older workspace may still need its one-time backfill`
|
|
11717
|
+
);
|
|
11718
|
+
}
|
|
11719
|
+
throw e;
|
|
11669
11720
|
}
|
|
11670
|
-
|
|
11671
|
-
|
|
11672
|
-
|
|
11673
|
-
|
|
11721
|
+
const local = listLocalSkills(route2.promptsDir);
|
|
11722
|
+
const rows = await client2.records.list(skillsModel.id, { limit: 200 });
|
|
11723
|
+
const cache = route2.resolved.agentSkills ?? {};
|
|
11724
|
+
const outcomes = [];
|
|
11725
|
+
const agentSkills = { ...cache };
|
|
11726
|
+
for (const skill of local) {
|
|
11727
|
+
const row = rows.find((r) => r.name === skill.name);
|
|
11728
|
+
if (!row) {
|
|
11729
|
+
if (opts.dryRun) {
|
|
11730
|
+
outcomes.push({ name: skill.name, action: "created", skillId: "(dry run)" });
|
|
11731
|
+
continue;
|
|
11732
|
+
}
|
|
11733
|
+
const created = await client2.records.create(skillsModel.id, {
|
|
11734
|
+
name: skill.name,
|
|
11735
|
+
description: skill.description,
|
|
11736
|
+
prompt: skill.prompt,
|
|
11737
|
+
...promptSourceFields(skillsModel, skill.prompt)
|
|
11738
|
+
});
|
|
11739
|
+
agentSkills[skill.name] = { skillId: created.id, lastSyncedUpdatedAt: created.updated_at };
|
|
11740
|
+
outcomes.push({ name: skill.name, action: "created", skillId: created.id });
|
|
11741
|
+
continue;
|
|
11674
11742
|
}
|
|
11675
|
-
|
|
11676
|
-
|
|
11677
|
-
|
|
11678
|
-
|
|
11679
|
-
|
|
11680
|
-
|
|
11681
|
-
|
|
11682
|
-
|
|
11743
|
+
if (row.description === skill.description && row.prompt === skill.prompt) {
|
|
11744
|
+
let anchoredAt = row.updated_at;
|
|
11745
|
+
if (!opts.dryRun && needsBaselineBackfill(skillsModel, row)) {
|
|
11746
|
+
try {
|
|
11747
|
+
anchoredAt = (await client2.records.update(
|
|
11748
|
+
skillsModel.id,
|
|
11749
|
+
row.id,
|
|
11750
|
+
promptSourceFields(skillsModel, skill.prompt),
|
|
11751
|
+
row.updated_at
|
|
11752
|
+
)).updated_at;
|
|
11753
|
+
} catch (e) {
|
|
11754
|
+
if (!(e instanceof StaleWriteError3) && !isPromptGateRejection(e)) throw e;
|
|
11755
|
+
}
|
|
11756
|
+
}
|
|
11757
|
+
agentSkills[skill.name] = { skillId: row.id, lastSyncedUpdatedAt: anchoredAt };
|
|
11758
|
+
outcomes.push({ name: skill.name, action: "unchanged", skillId: row.id });
|
|
11759
|
+
continue;
|
|
11683
11760
|
}
|
|
11684
|
-
|
|
11685
|
-
|
|
11686
|
-
|
|
11687
|
-
|
|
11688
|
-
|
|
11761
|
+
if (row.prompt_customized === true) {
|
|
11762
|
+
agentSkills[skill.name] = { skillId: row.id, lastSyncedUpdatedAt: row.updated_at };
|
|
11763
|
+
outcomes.push({ name: skill.name, action: "overridden", skillId: row.id });
|
|
11764
|
+
continue;
|
|
11765
|
+
}
|
|
11766
|
+
const body = { description: skill.description, prompt: skill.prompt, ...promptSourceFields(skillsModel, skill.prompt) };
|
|
11767
|
+
if (opts.force) {
|
|
11768
|
+
if (opts.dryRun) {
|
|
11769
|
+
outcomes.push({ name: skill.name, action: "forced", skillId: row.id });
|
|
11770
|
+
continue;
|
|
11771
|
+
}
|
|
11689
11772
|
try {
|
|
11690
|
-
|
|
11773
|
+
const updated = await client2.records.update(skillsModel.id, row.id, body);
|
|
11774
|
+
agentSkills[skill.name] = { skillId: row.id, lastSyncedUpdatedAt: updated.updated_at };
|
|
11775
|
+
outcomes.push({ name: skill.name, action: "forced", skillId: row.id });
|
|
11691
11776
|
} catch (e) {
|
|
11692
|
-
|
|
11777
|
+
if (!isPromptGateRejection(e)) throw e;
|
|
11778
|
+
outcomes.push({ name: skill.name, action: "overridden", skillId: row.id });
|
|
11693
11779
|
}
|
|
11694
|
-
|
|
11695
|
-
mkdirSync17(dirname13(policyFile), { recursive: true });
|
|
11696
|
-
writeFileSync18(policyFile, generated.yaml, { mode: 384 });
|
|
11780
|
+
continue;
|
|
11697
11781
|
}
|
|
11698
|
-
|
|
11699
|
-
if (
|
|
11700
|
-
|
|
11701
|
-
|
|
11702
|
-
|
|
11703
|
-
|
|
11704
|
-
|
|
11705
|
-
|
|
11782
|
+
let knownBaseline;
|
|
11783
|
+
if (hasPromptBaselineColumn(skillsModel) && typeof row.prompt_baseline === "string") {
|
|
11784
|
+
if (row.prompt !== row.prompt_baseline) {
|
|
11785
|
+
outcomes.push({ name: skill.name, action: "diverged", skillId: row.id });
|
|
11786
|
+
continue;
|
|
11787
|
+
}
|
|
11788
|
+
knownBaseline = row.updated_at;
|
|
11789
|
+
} else {
|
|
11790
|
+
knownBaseline = cache[skill.name]?.skillId === row.id ? cache[skill.name]?.lastSyncedUpdatedAt : void 0;
|
|
11706
11791
|
}
|
|
11707
|
-
|
|
11708
|
-
|
|
11709
|
-
|
|
11710
|
-
|
|
11711
|
-
|
|
11712
|
-
|
|
11713
|
-
|
|
11714
|
-
|
|
11715
|
-
|
|
11792
|
+
if (!knownBaseline) {
|
|
11793
|
+
outcomes.push({ name: skill.name, action: "diverged", skillId: row.id });
|
|
11794
|
+
continue;
|
|
11795
|
+
}
|
|
11796
|
+
if (opts.dryRun) {
|
|
11797
|
+
outcomes.push({ name: skill.name, action: "updated", skillId: row.id });
|
|
11798
|
+
continue;
|
|
11799
|
+
}
|
|
11800
|
+
try {
|
|
11801
|
+
const updated = await client2.records.update(
|
|
11802
|
+
skillsModel.id,
|
|
11803
|
+
row.id,
|
|
11804
|
+
body,
|
|
11805
|
+
knownBaseline
|
|
11806
|
+
);
|
|
11807
|
+
agentSkills[skill.name] = { skillId: row.id, lastSyncedUpdatedAt: updated.updated_at };
|
|
11808
|
+
outcomes.push({ name: skill.name, action: "updated", skillId: row.id });
|
|
11809
|
+
} catch (e) {
|
|
11810
|
+
if (e instanceof StaleWriteError3) {
|
|
11811
|
+
outcomes.push({ name: skill.name, action: "diverged", skillId: row.id });
|
|
11812
|
+
continue;
|
|
11813
|
+
}
|
|
11814
|
+
if (isPromptGateRejection(e)) {
|
|
11815
|
+
outcomes.push({ name: skill.name, action: "overridden", skillId: row.id });
|
|
11816
|
+
continue;
|
|
11817
|
+
}
|
|
11818
|
+
throw e;
|
|
11819
|
+
}
|
|
11820
|
+
}
|
|
11821
|
+
return { outcomes, agentSkills };
|
|
11822
|
+
}
|
|
11823
|
+
function describeSkillSyncOutcome(o) {
|
|
11824
|
+
switch (o.action) {
|
|
11825
|
+
case "created":
|
|
11826
|
+
return `${o.name}: created (${o.skillId})`;
|
|
11827
|
+
case "updated":
|
|
11828
|
+
return `${o.name}: prompt updated from crew's local file`;
|
|
11829
|
+
case "unchanged":
|
|
11830
|
+
return `${o.name}: already in sync`;
|
|
11831
|
+
case "overridden":
|
|
11832
|
+
return `${o.name}: override in place \u2014 prompt not synced (clear "Customize prompt" on the Agent Skills row to resume)`;
|
|
11833
|
+
case "forced":
|
|
11834
|
+
return `${o.name}: overwritten from crew's local file (--force)`;
|
|
11835
|
+
case "diverged":
|
|
11836
|
+
return `${o.name}: HAS LOCAL EDITS \u2014 crew's default is newer but was NOT applied; review ${o.skillId} in the app before syncing again`;
|
|
11837
|
+
}
|
|
11838
|
+
}
|
|
11839
|
+
async function fetchSkillOverrides(route2, opts) {
|
|
11840
|
+
if (!route2.resolved) return {};
|
|
11841
|
+
const client2 = new TablationClient3({
|
|
11842
|
+
baseUrl: `${route2.baseUrl}/api`,
|
|
11843
|
+
apiKey: resolveApiKey(route2),
|
|
11844
|
+
headers: { "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" }
|
|
11845
|
+
});
|
|
11846
|
+
let rows;
|
|
11847
|
+
try {
|
|
11848
|
+
const model = await client2.dataModels.get("agent_skills", route2.resolved.workspaceId);
|
|
11849
|
+
rows = await client2.records.list(model.id, { limit: 200 });
|
|
11850
|
+
} catch {
|
|
11851
|
+
return {};
|
|
11852
|
+
}
|
|
11853
|
+
const local = new Map(listLocalSkills(route2.promptsDir).map((s) => [s.name, s]));
|
|
11854
|
+
const cache = route2.resolved.agentSkills ?? {};
|
|
11855
|
+
const out = {};
|
|
11856
|
+
for (const row of rows) {
|
|
11857
|
+
const name = row.name;
|
|
11858
|
+
const edited = isEditedSkillRow(row, local.get(name)?.prompt, cache[name]);
|
|
11859
|
+
const base = edited ? row.prompt : local.get(name)?.prompt ?? row.prompt;
|
|
11860
|
+
const composed = appendAdditions(base, row.prompt_additions);
|
|
11861
|
+
if (edited || composed !== base) out[name] = composed;
|
|
11862
|
+
}
|
|
11863
|
+
return out;
|
|
11864
|
+
}
|
|
11865
|
+
function isEditedSkillRow(row, localPrompt, cached) {
|
|
11866
|
+
if (row.prompt === localPrompt) return false;
|
|
11867
|
+
if (row.prompt_customized !== true && row.prompt === row.prompt_baseline) return false;
|
|
11868
|
+
return !(cached?.skillId === row.id && cached.lastSyncedUpdatedAt === row.updated_at);
|
|
11869
|
+
}
|
|
11870
|
+
function skillMarkerWarnings(promptsDir, personaPrompts) {
|
|
11871
|
+
const shipped = new Set(listLocalSkills(promptsDir).map((s) => s.name));
|
|
11872
|
+
const out = [];
|
|
11873
|
+
for (const [role, text2] of Object.entries(personaPrompts)) {
|
|
11874
|
+
for (const name of skillMarkerNames(text2 ?? "")) {
|
|
11875
|
+
if (!shipped.has(name)) out.push(`${role}: brief includes {{skill: ${name}}} but this prompt set ships no skill with that name`);
|
|
11876
|
+
}
|
|
11877
|
+
}
|
|
11878
|
+
return out;
|
|
11879
|
+
}
|
|
11880
|
+
|
|
11881
|
+
// src/runner.ts
|
|
11882
|
+
import { spawn as spawn4, execFile, execFileSync as execFileSync8 } from "child_process";
|
|
11883
|
+
import { mkdtempSync, mkdirSync as mkdirSync18, writeFileSync as writeFileSync19, rmSync as rmSync15 } from "fs";
|
|
11884
|
+
import { createHash as createHash5 } from "crypto";
|
|
11885
|
+
import { tmpdir as tmpdir3 } from "os";
|
|
11886
|
+
import { basename as basename8, dirname as dirname14, join as join29 } from "path";
|
|
11887
|
+
import { promisify } from "util";
|
|
11888
|
+
|
|
11889
|
+
// src/run-limit.ts
|
|
11890
|
+
var DEFAULT_MAX_RUN_MINUTES = 240;
|
|
11891
|
+
var KILL_GRACE_MS = 5e3;
|
|
11892
|
+
var WALL_CLOCK_REASON = "wall-clock";
|
|
11893
|
+
function resolveMaxRunMinutes(route2, toolchain) {
|
|
11894
|
+
return route2 ?? toolchain ?? DEFAULT_MAX_RUN_MINUTES;
|
|
11895
|
+
}
|
|
11896
|
+
function deadlineFor(spawnedAt, maxRunMinutes) {
|
|
11897
|
+
if (!maxRunMinutes || maxRunMinutes <= 0) return void 0;
|
|
11898
|
+
const t = Date.parse(spawnedAt);
|
|
11899
|
+
return Number.isNaN(t) ? void 0 : new Date(t + maxRunMinutes * 6e4).toISOString();
|
|
11900
|
+
}
|
|
11901
|
+
function msUntilDeadline(deadline, now = Date.now()) {
|
|
11902
|
+
if (!deadline) return void 0;
|
|
11903
|
+
const t = Date.parse(deadline);
|
|
11904
|
+
return Number.isNaN(t) ? void 0 : t - now;
|
|
11905
|
+
}
|
|
11906
|
+
async function killRunGroup(pid, o = {}) {
|
|
11907
|
+
const alive = o.isAlive ?? ((p) => {
|
|
11908
|
+
try {
|
|
11909
|
+
process.kill(p, 0);
|
|
11910
|
+
return true;
|
|
11911
|
+
} catch (e) {
|
|
11912
|
+
return e.code === "EPERM";
|
|
11913
|
+
}
|
|
11914
|
+
});
|
|
11915
|
+
const signal = (sig) => {
|
|
11916
|
+
try {
|
|
11917
|
+
process.kill(-pid, sig);
|
|
11918
|
+
} catch {
|
|
11919
|
+
try {
|
|
11920
|
+
process.kill(pid, sig);
|
|
11921
|
+
} catch {
|
|
11922
|
+
}
|
|
11923
|
+
}
|
|
11924
|
+
};
|
|
11925
|
+
signal("SIGTERM");
|
|
11926
|
+
const end = Date.now() + (o.graceMs ?? KILL_GRACE_MS);
|
|
11927
|
+
while (alive(pid) && Date.now() < end) await new Promise((r) => setTimeout(r, 50));
|
|
11928
|
+
if (alive(pid)) signal("SIGKILL");
|
|
11929
|
+
}
|
|
11930
|
+
var RUN_KILLED_MARKER = "<!-- crew:run-killed -->";
|
|
11931
|
+
function runKilledComment(b) {
|
|
11932
|
+
const tree = b.dirty === null ? "The worktree could not be checked." : b.dirty ? "The worktree has uncommitted changes \u2014 they are this seat's own, from that run." : "The worktree is clean.";
|
|
11933
|
+
return `${RUN_KILLED_MARKER}
|
|
11934
|
+
|
|
11935
|
+
The agent run on this ticket was stopped at its wall-clock limit of ${b.limitMinutes} minutes before it handed on${b.branch ? `; its branch is \`${b.branch}\`` : ""}. ${tree} The worktree is left as it was. The next run on this seat resumes from it rather than starting over.`;
|
|
11936
|
+
}
|
|
11937
|
+
|
|
11938
|
+
// src/runner.ts
|
|
11939
|
+
var execFileP = promisify(execFile);
|
|
11940
|
+
var DEFAULT_SANDBOX_CONFIG = {
|
|
11941
|
+
bin: "openshell",
|
|
11942
|
+
mirrorDir: "/cache",
|
|
11943
|
+
workDir: DEFAULT_SANDBOX_WORKDIR
|
|
11944
|
+
};
|
|
11945
|
+
var SANDBOX_STDIN_LIMIT = 4 * 1024 * 1024 - 64 * 1024;
|
|
11946
|
+
var SANDBOX_PROMPT_PATH = "/sandbox/prompt.txt";
|
|
11947
|
+
var HostRunner = class {
|
|
11948
|
+
kind = "host";
|
|
11949
|
+
start(plan, o) {
|
|
11950
|
+
const child = spawn4(plan.bin, plan.args, {
|
|
11951
|
+
cwd: plan.cwd,
|
|
11952
|
+
env: o.env,
|
|
11953
|
+
stdio: ["pipe", o.streamFd, "inherit"],
|
|
11954
|
+
detached: true
|
|
11955
|
+
});
|
|
11956
|
+
return { child, handle: { runner: "host", pid: child.pid } };
|
|
11957
|
+
}
|
|
11958
|
+
async kill(handle) {
|
|
11959
|
+
if (handle.pid !== void 0) await killRunGroup(handle.pid);
|
|
11960
|
+
}
|
|
11961
|
+
isAlive(handle) {
|
|
11962
|
+
if (handle.pid === void 0) return false;
|
|
11963
|
+
try {
|
|
11964
|
+
process.kill(handle.pid, 0);
|
|
11965
|
+
return true;
|
|
11966
|
+
} catch (e) {
|
|
11967
|
+
return e.code === "EPERM";
|
|
11968
|
+
}
|
|
11969
|
+
}
|
|
11970
|
+
reattach(meta) {
|
|
11971
|
+
return { runner: "host", pid: meta.pid };
|
|
11972
|
+
}
|
|
11973
|
+
async release() {
|
|
11974
|
+
}
|
|
11975
|
+
};
|
|
11976
|
+
function shQuote2(s) {
|
|
11977
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
11978
|
+
}
|
|
11979
|
+
function sandboxName(plan, now = Date.now()) {
|
|
11980
|
+
const h = createHash5("sha256").update([plan.route, plan.role, plan.ticket ?? ""].join("\0")).digest();
|
|
11981
|
+
const tag = (h.readUInt32BE(0) % 36 ** 6).toString(36).padStart(6, "0");
|
|
11982
|
+
return `crew-${tag}${now.toString(36).slice(-8).padStart(8, "0")}`;
|
|
11983
|
+
}
|
|
11984
|
+
var SandboxRunner = class {
|
|
11985
|
+
kind = "sandbox";
|
|
11986
|
+
cfg;
|
|
11987
|
+
/** Injected for tests; the real one reads the plan's checkout. */
|
|
11988
|
+
originOf;
|
|
11989
|
+
constructor(cfg = {}, originOf = gitOrigin) {
|
|
11990
|
+
this.cfg = { ...DEFAULT_SANDBOX_CONFIG, ...cfg };
|
|
11991
|
+
this.originOf = originOf;
|
|
11992
|
+
}
|
|
11993
|
+
os(args, o = {}) {
|
|
11994
|
+
return execFileP(this.cfg.bin, args, { env: o.env ?? process.env, maxBuffer: 16 * 1024 * 1024 });
|
|
11995
|
+
}
|
|
11996
|
+
async start(plan, o) {
|
|
11997
|
+
const origin = plan.sandboxOrigin ?? (plan.repo ? null : this.originOf(plan.cwd));
|
|
11998
|
+
if (!origin) {
|
|
11999
|
+
throw new Error(plan.repo ? `cannot place the repository ${plan.repo} of ${plan.ticket ?? "this run"} on route ${plan.route}, so there is nothing to clone into the sandbox` : `cannot find the origin remote of ${plan.cwd}, so there is nothing to clone into the sandbox`);
|
|
12000
|
+
}
|
|
12001
|
+
const repo = parseRemote(origin);
|
|
12002
|
+
if (!repo) throw new Error(`cannot read a forge host and path from the origin remote ${origin}`);
|
|
12003
|
+
const name = sandboxName(plan);
|
|
12004
|
+
const { cfg } = this;
|
|
12005
|
+
const secretKeys = Object.keys(plan.setEnv);
|
|
12006
|
+
if (cfg.forgeTokenVar && o.env[cfg.forgeTokenVar] !== void 0 && !secretKeys.includes(cfg.forgeTokenVar)) secretKeys.push(cfg.forgeTokenVar);
|
|
12007
|
+
for (const [k, v] of Object.entries(plan.setEnv)) {
|
|
12008
|
+
if (/[\r\n]/.test(v)) throw new Error(`the sandbox environment variable ${k} contains a newline, which the sandbox gateway refuses`);
|
|
12009
|
+
}
|
|
12010
|
+
const createEnv = { ...process.env, ...plan.setEnv };
|
|
12011
|
+
if (cfg.forgeTokenVar && o.env[cfg.forgeTokenVar] !== void 0) createEnv[cfg.forgeTokenVar] = o.env[cfg.forgeTokenVar];
|
|
12012
|
+
let policyFile = cfg.policy;
|
|
12013
|
+
let generated;
|
|
12014
|
+
if (!policyFile && plan.sandboxPolicy) {
|
|
12015
|
+
try {
|
|
12016
|
+
generated = generateSandboxPolicy({ mirrorDir: cfg.mirrorDir, workDir: cfg.workDir, ...plan.sandboxPolicy });
|
|
12017
|
+
} catch (e) {
|
|
12018
|
+
throw new Error(`cannot generate the sandbox policy: ${e.message}`);
|
|
12019
|
+
}
|
|
12020
|
+
policyFile = policyPathFor(plan.streamPath);
|
|
12021
|
+
mkdirSync18(dirname14(policyFile), { recursive: true });
|
|
12022
|
+
writeFileSync19(policyFile, generated.yaml, { mode: 384 });
|
|
12023
|
+
}
|
|
12024
|
+
const create2 = ["sandbox", "create", "--name", name, "--detach"];
|
|
12025
|
+
if (policyFile) create2.push("--policy", policyFile);
|
|
12026
|
+
const image = cfg.image ?? plan.sandboxImage;
|
|
12027
|
+
if (image) create2.push("--from", image);
|
|
12028
|
+
if (cfg.cacheVolume) {
|
|
12029
|
+
create2.push("--driver-config-json", JSON.stringify({
|
|
12030
|
+
docker: { mounts: [{ type: "volume", source: cfg.cacheVolume, target: cfg.mirrorDir, read_only: true }] }
|
|
12031
|
+
}));
|
|
12032
|
+
}
|
|
12033
|
+
for (const k of secretKeys) create2.push("--env-from", k);
|
|
12034
|
+
const maxSeconds = Math.max(60, Math.ceil((plan.maxRunMinutes ?? 0) * 60) + 600);
|
|
12035
|
+
create2.push("--", "sleep", String(plan.maxRunMinutes ? maxSeconds : 86400));
|
|
12036
|
+
const t0 = Date.now();
|
|
12037
|
+
try {
|
|
12038
|
+
await this.os(create2, { env: createEnv });
|
|
12039
|
+
} catch (e) {
|
|
12040
|
+
await this.deleteQuietly(name);
|
|
12041
|
+
throw new Error(`openshell could not create the sandbox: ${describeExecError(e)}`);
|
|
11716
12042
|
}
|
|
11717
12043
|
o.emit.emit(`sandbox_created: ${name}`, { role: plan.role, data: { event: "sandbox_created", sandbox: name, ms: Date.now() - t0 } });
|
|
11718
12044
|
const handle = { runner: "sandbox", sandbox: name, sandboxBin: cfg.bin };
|
|
@@ -11740,18 +12066,18 @@ var SandboxRunner = class {
|
|
|
11740
12066
|
const harness = cfg.agentBin ?? basename8(plan.bin);
|
|
11741
12067
|
const viaUpload = Buffer.byteLength(plan.prompt) > SANDBOX_STDIN_LIMIT;
|
|
11742
12068
|
if (viaUpload) {
|
|
11743
|
-
const tmp = mkdtempSync(
|
|
12069
|
+
const tmp = mkdtempSync(join29(tmpdir3(), "crew-prompt-"));
|
|
11744
12070
|
try {
|
|
11745
|
-
const file =
|
|
11746
|
-
|
|
12071
|
+
const file = join29(tmp, "prompt.txt");
|
|
12072
|
+
writeFileSync19(file, plan.prompt, { mode: 384 });
|
|
11747
12073
|
await this.os(["sandbox", "upload", name, file, SANDBOX_PROMPT_PATH]);
|
|
11748
12074
|
} finally {
|
|
11749
|
-
|
|
12075
|
+
rmSync15(tmp, { recursive: true, force: true });
|
|
11750
12076
|
}
|
|
11751
12077
|
}
|
|
11752
12078
|
const withStubs = `${sandboxEnvExports()}PATH=${shQuote2(SANDBOX_STUB_DIR)}:"$PATH"; export PATH; `;
|
|
11753
12079
|
const command2 = viaUpload ? ["sh", "-c", `${withStubs}exec ${[harness, ...plan.args].map(shQuote2).join(" ")} < ${SANDBOX_PROMPT_PATH}`] : ["sh", "-c", `${withStubs}exec "$@"`, "sh", harness, ...plan.args];
|
|
11754
|
-
const child =
|
|
12080
|
+
const child = spawn4(cfg.bin, ["sandbox", "exec", "-n", name, "--no-login-shell", "--workdir", cfg.workDir, "--", ...command2], {
|
|
11755
12081
|
env: process.env,
|
|
11756
12082
|
stdio: ["pipe", o.streamFd, "inherit"],
|
|
11757
12083
|
detached: true
|
|
@@ -11806,7 +12132,7 @@ var SandboxRunner = class {
|
|
|
11806
12132
|
var describeExecError = describe;
|
|
11807
12133
|
function gitOrigin(cwd) {
|
|
11808
12134
|
try {
|
|
11809
|
-
return
|
|
12135
|
+
return execFileSync8("git", ["-C", cwd, "remote", "get-url", "origin"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
11810
12136
|
} catch {
|
|
11811
12137
|
return null;
|
|
11812
12138
|
}
|
|
@@ -11818,7 +12144,7 @@ function runnerOfSidecar(sc) {
|
|
|
11818
12144
|
return sc.runner === "sandbox" ? new SandboxRunner(sc.sandboxBin ? { bin: sc.sandboxBin } : {}) : new HostRunner();
|
|
11819
12145
|
}
|
|
11820
12146
|
var PROBE_CREATE_TIMEOUT_MS = 12e4;
|
|
11821
|
-
function checkSandboxRunner(cfg = {}, run3 = (b, a, t) =>
|
|
12147
|
+
function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: t ?? 15e3 })) {
|
|
11822
12148
|
const bin = cfg.bin ?? DEFAULT_SANDBOX_CONFIG.bin;
|
|
11823
12149
|
let version;
|
|
11824
12150
|
try {
|
|
@@ -11934,7 +12260,7 @@ var ALLOWANCE_REFUSAL_MARKER = "AI_ALLOWANCE_EXCEEDED";
|
|
|
11934
12260
|
function streamShowsAllowanceRefusal(streamPath) {
|
|
11935
12261
|
let raw;
|
|
11936
12262
|
try {
|
|
11937
|
-
raw =
|
|
12263
|
+
raw = readFileSync27(streamPath, "utf8");
|
|
11938
12264
|
} catch {
|
|
11939
12265
|
return false;
|
|
11940
12266
|
}
|
|
@@ -11957,7 +12283,7 @@ function streamShowsAllowanceRefusal(streamPath) {
|
|
|
11957
12283
|
}
|
|
11958
12284
|
return false;
|
|
11959
12285
|
}
|
|
11960
|
-
var digestPathFor = (stateDir, routeLabel, role, runId) =>
|
|
12286
|
+
var digestPathFor = (stateDir, routeLabel, role, runId) => join30(stateDir, `digest-${routeLabel}-${role}${runId ? `-${runId}` : ""}.md`);
|
|
11961
12287
|
function codeBridgeFor(o, harness) {
|
|
11962
12288
|
if (!o.ticket) return void 0;
|
|
11963
12289
|
const number = /(\d+)$/.exec(o.ticket)?.[1];
|
|
@@ -11984,7 +12310,7 @@ function codeBridgeFor(o, harness) {
|
|
|
11984
12310
|
"--clone",
|
|
11985
12311
|
o.ship.sandbox?.workDir ?? DEFAULT_SANDBOX_WORKDIR,
|
|
11986
12312
|
"--state-dir",
|
|
11987
|
-
|
|
12313
|
+
dirname15(SANDBOX_INTEL_DIR),
|
|
11988
12314
|
"--ticket",
|
|
11989
12315
|
number,
|
|
11990
12316
|
...seed ? ["--seed-cache", seed] : []
|
|
@@ -11997,33 +12323,33 @@ function codeBridgeFor(o, harness) {
|
|
|
11997
12323
|
bridge.settingsFile = `${SANDBOX_INTEL_DIR}/gemini-settings.json`;
|
|
11998
12324
|
bridge.files = [{ path: bridge.settingsFile, content: text2 }];
|
|
11999
12325
|
} else {
|
|
12000
|
-
const file =
|
|
12001
|
-
|
|
12002
|
-
|
|
12326
|
+
const file = join30(intelDir(o.stateDir, o.route.route, number), "gemini-settings.json");
|
|
12327
|
+
mkdirSync19(dirname15(file), { recursive: true });
|
|
12328
|
+
writeFileSync20(file, text2);
|
|
12003
12329
|
bridge.settingsFile = file;
|
|
12004
12330
|
}
|
|
12005
12331
|
}
|
|
12006
12332
|
return bridge;
|
|
12007
12333
|
}
|
|
12008
12334
|
function planAgentRun(o) {
|
|
12009
|
-
const briefPath =
|
|
12010
|
-
if (!
|
|
12335
|
+
const briefPath = join30(o.route.promptsDir, "personas", `lane-${o.role}.md`);
|
|
12336
|
+
if (!existsSync26(briefPath)) {
|
|
12011
12337
|
throw new AgentError(`no brief at ${briefPath} \u2014 refusing to run an unscoped session`);
|
|
12012
12338
|
}
|
|
12013
|
-
const commonPath =
|
|
12014
|
-
const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) &&
|
|
12339
|
+
const commonPath = join30(o.route.promptsDir, "personas", "common.md");
|
|
12340
|
+
const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) && existsSync26(commonPath);
|
|
12015
12341
|
const now = o.now ?? (() => Date.now());
|
|
12016
12342
|
const routeLabel = routeSlug(o.route.route);
|
|
12017
12343
|
const ownDigest = o.runId ? digestPathFor(o.stateDir, routeLabel, o.role, o.runId) : void 0;
|
|
12018
|
-
const digestPath2 = ownDigest &&
|
|
12344
|
+
const digestPath2 = ownDigest && existsSync26(ownDigest) ? ownDigest : digestPathFor(o.stateDir, routeLabel, o.role);
|
|
12019
12345
|
let digest;
|
|
12020
12346
|
let ageSeconds;
|
|
12021
|
-
if (
|
|
12347
|
+
if (existsSync26(digestPath2)) {
|
|
12022
12348
|
ageSeconds = Math.floor((now() - statSync8(digestPath2).mtimeMs) / 1e3);
|
|
12023
|
-
if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest =
|
|
12349
|
+
if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync27(digestPath2, "utf8");
|
|
12024
12350
|
}
|
|
12025
|
-
const common = usesCommon ?
|
|
12026
|
-
const brief =
|
|
12351
|
+
const common = usesCommon ? readFileSync27(commonPath, "utf8") : "";
|
|
12352
|
+
const brief = readFileSync27(briefPath, "utf8");
|
|
12027
12353
|
const effectiveCommon = o.divergedPrompt ? "" : common;
|
|
12028
12354
|
const effectiveBrief = appendAdditions(o.divergedPrompt ?? brief, o.personaAdditions);
|
|
12029
12355
|
const localSkills = new Map(listLocalSkills(o.route.promptsDir).map((s) => [s.name, s.prompt]));
|
|
@@ -12045,8 +12371,8 @@ function planAgentRun(o) {
|
|
|
12045
12371
|
brief: expanded.text,
|
|
12046
12372
|
digest
|
|
12047
12373
|
});
|
|
12048
|
-
const promptSha =
|
|
12049
|
-
const streamsDir =
|
|
12374
|
+
const promptSha = createHash6("sha256").update(expanded.text).digest("hex");
|
|
12375
|
+
const streamsDir = join30(o.stateDir, "streams");
|
|
12050
12376
|
const base = `${routeLabel}-${o.role}-${o.cycle}${o.runId ? `-${o.runId}` : ""}`;
|
|
12051
12377
|
const seat = resolveSeat(o.ship, o.route, o.role, o.agentPersona ?? (o.agentModel ? { model: o.agentModel } : {}), o.repo);
|
|
12052
12378
|
const { model } = seat;
|
|
@@ -12149,8 +12475,8 @@ function planAgentRun(o) {
|
|
|
12149
12475
|
digestAttached: digest !== void 0,
|
|
12150
12476
|
digestAgeSeconds: ageSeconds,
|
|
12151
12477
|
model,
|
|
12152
|
-
streamPath:
|
|
12153
|
-
eventsPath:
|
|
12478
|
+
streamPath: join30(streamsDir, `${base}.jsonl`),
|
|
12479
|
+
eventsPath: join30(streamsDir, `${base}.events.jsonl`),
|
|
12154
12480
|
ticket: o.ticket,
|
|
12155
12481
|
ticketRecordId: o.ticketRecordId ?? null,
|
|
12156
12482
|
repo: o.repo ?? null,
|
|
@@ -12182,7 +12508,7 @@ function describePlan(p) {
|
|
|
12182
12508
|
var pidPathFor = (streamPath) => `${streamPath}.pid`;
|
|
12183
12509
|
function readRunSidecar(streamPath) {
|
|
12184
12510
|
try {
|
|
12185
|
-
const sc = JSON.parse(
|
|
12511
|
+
const sc = JSON.parse(readFileSync27(pidPathFor(streamPath), "utf8"));
|
|
12186
12512
|
return typeof sc.pid === "number" && typeof sc.spawnedAt === "string" && typeof sc.role === "string" ? sc : null;
|
|
12187
12513
|
} catch {
|
|
12188
12514
|
return null;
|
|
@@ -12230,7 +12556,7 @@ async function killForDeadline(kill, pid, emit, role, ticket, spawnedAt, limitMi
|
|
|
12230
12556
|
var withoutKey = ({ apiKey: _apiKey, ...rest }) => rest;
|
|
12231
12557
|
function openSink(path) {
|
|
12232
12558
|
try {
|
|
12233
|
-
|
|
12559
|
+
mkdirSync19(dirname15(path), { recursive: true });
|
|
12234
12560
|
return createWriteStream(path, { flags: "a" });
|
|
12235
12561
|
} catch {
|
|
12236
12562
|
return void 0;
|
|
@@ -12416,7 +12742,7 @@ var RunObserver = class {
|
|
|
12416
12742
|
};
|
|
12417
12743
|
function writeRunMeta(id, startedAt, liveTicket, extra) {
|
|
12418
12744
|
try {
|
|
12419
|
-
|
|
12745
|
+
writeFileSync20(`${id.streamPath}.meta.json`, JSON.stringify({
|
|
12420
12746
|
route: id.route,
|
|
12421
12747
|
role: id.role,
|
|
12422
12748
|
hint: id.ticket,
|
|
@@ -12607,7 +12933,7 @@ function spawnAgent(plan, emit, hintMoved) {
|
|
|
12607
12933
|
const id = identityOf(plan, adapter.harness);
|
|
12608
12934
|
let streamFd;
|
|
12609
12935
|
try {
|
|
12610
|
-
|
|
12936
|
+
mkdirSync19(dirname15(plan.streamPath), { recursive: true });
|
|
12611
12937
|
streamFd = openSync4(plan.streamPath, "a");
|
|
12612
12938
|
} catch (e) {
|
|
12613
12939
|
void endSink(eventsSink);
|
|
@@ -12666,7 +12992,7 @@ function spawnAgent(plan, emit, hintMoved) {
|
|
|
12666
12992
|
...plan.workspaceRunId ? { workspaceRunId: plan.workspaceRunId } : {}
|
|
12667
12993
|
};
|
|
12668
12994
|
try {
|
|
12669
|
-
|
|
12995
|
+
writeFileSync20(pidPathFor(plan.streamPath), JSON.stringify(sidecar));
|
|
12670
12996
|
} catch {
|
|
12671
12997
|
}
|
|
12672
12998
|
}
|
|
@@ -12780,21 +13106,21 @@ var pidAlive = (pid) => {
|
|
|
12780
13106
|
};
|
|
12781
13107
|
function runFinished(streamPath) {
|
|
12782
13108
|
const path = `${streamPath}.meta.json`;
|
|
12783
|
-
if (!
|
|
13109
|
+
if (!existsSync27(path)) return false;
|
|
12784
13110
|
try {
|
|
12785
|
-
return JSON.parse(
|
|
13111
|
+
return JSON.parse(readFileSync28(path, "utf8")).running !== true;
|
|
12786
13112
|
} catch {
|
|
12787
13113
|
return true;
|
|
12788
13114
|
}
|
|
12789
13115
|
}
|
|
12790
13116
|
function orphanedStreams(o) {
|
|
12791
|
-
const dir =
|
|
12792
|
-
if (!
|
|
13117
|
+
const dir = join31(o.stateDir, "streams");
|
|
13118
|
+
if (!existsSync27(dir)) return [];
|
|
12793
13119
|
const ownerAlive = o.isOwnerAlive ?? pidAlive;
|
|
12794
13120
|
const out = [];
|
|
12795
13121
|
for (const name of readdirSync9(dir)) {
|
|
12796
13122
|
if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
|
|
12797
|
-
const streamPath =
|
|
13123
|
+
const streamPath = join31(dir, name);
|
|
12798
13124
|
if (runFinished(streamPath)) continue;
|
|
12799
13125
|
const sidecar = readRunSidecar(streamPath);
|
|
12800
13126
|
if (!sidecar || sidecar.route !== o.routeLabel) continue;
|
|
@@ -12847,15 +13173,15 @@ async function reconcileRuns(o) {
|
|
|
12847
13173
|
}
|
|
12848
13174
|
|
|
12849
13175
|
// src/live-runs.ts
|
|
12850
|
-
import { existsSync as
|
|
12851
|
-
import { join as
|
|
13176
|
+
import { existsSync as existsSync28, readdirSync as readdirSync10, statSync as statSync9 } from "fs";
|
|
13177
|
+
import { join as join32 } from "path";
|
|
12852
13178
|
function liveRuns(stateDir, isAlive = runIsAlive) {
|
|
12853
|
-
const dir =
|
|
12854
|
-
if (!
|
|
13179
|
+
const dir = join32(stateDir, "streams");
|
|
13180
|
+
if (!existsSync28(dir)) return [];
|
|
12855
13181
|
const out = [];
|
|
12856
13182
|
for (const name of readdirSync10(dir)) {
|
|
12857
13183
|
if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
|
|
12858
|
-
const streamPath =
|
|
13184
|
+
const streamPath = join32(dir, name);
|
|
12859
13185
|
if (runFinished(streamPath)) continue;
|
|
12860
13186
|
const sidecar = readRunSidecar(streamPath);
|
|
12861
13187
|
if (!sidecar || !isAlive(sidecar)) continue;
|
|
@@ -12865,12 +13191,12 @@ function liveRuns(stateDir, isAlive = runIsAlive) {
|
|
|
12865
13191
|
}
|
|
12866
13192
|
function runActivity(stateDir, isAlive = runIsAlive) {
|
|
12867
13193
|
const activeRuns = liveRuns(stateDir, isAlive).length;
|
|
12868
|
-
const dir =
|
|
13194
|
+
const dir = join32(stateDir, "streams");
|
|
12869
13195
|
let newest = 0;
|
|
12870
|
-
if (
|
|
13196
|
+
if (existsSync28(dir)) {
|
|
12871
13197
|
for (const name of readdirSync10(dir)) {
|
|
12872
13198
|
if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
|
|
12873
|
-
const streamPath =
|
|
13199
|
+
const streamPath = join32(dir, name);
|
|
12874
13200
|
if (!runFinished(streamPath)) continue;
|
|
12875
13201
|
try {
|
|
12876
13202
|
newest = Math.max(newest, statSync9(`${streamPath}.meta.json`).mtimeMs);
|
|
@@ -12965,7 +13291,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
|
|
|
12965
13291
|
if (host === "windows") return [];
|
|
12966
13292
|
const ctx = installContext();
|
|
12967
13293
|
const systemd = detectSystemd();
|
|
12968
|
-
return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) =>
|
|
13294
|
+
return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) => existsSync29(p));
|
|
12969
13295
|
};
|
|
12970
13296
|
return {
|
|
12971
13297
|
liveRuns: () => liveRuns(stateDir).map((r) => ({ role: r.role, route: r.route, pid: r.pid, ticketRecordId: r.ticketRecordId ?? void 0, streamPath: r.streamPath })),
|
|
@@ -13026,7 +13352,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
|
|
|
13026
13352
|
},
|
|
13027
13353
|
remaining() {
|
|
13028
13354
|
const left = [];
|
|
13029
|
-
if (
|
|
13355
|
+
if (existsSync29(cfg.configFile)) left.push(`config ${cfg.configFile}`);
|
|
13030
13356
|
for (const h of forgeHosts()) if (hasForgeToken(cfg.ship.forges, h, stateDir)) left.push(`forge token for ${h}`);
|
|
13031
13357
|
try {
|
|
13032
13358
|
for (const k of readdirSync11(keysDir(stateDir))) left.push(`seat key ${k}`);
|
|
@@ -13049,7 +13375,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
|
|
|
13049
13375
|
|
|
13050
13376
|
// src/sandbox-cache.ts
|
|
13051
13377
|
var execFileP2 = promisify2(execFile2);
|
|
13052
|
-
var
|
|
13378
|
+
var realExec2 = (bin, args, o) => execFileP2(bin, args, { env: o?.env ?? process.env, maxBuffer: 16 * 1024 * 1024 });
|
|
13053
13379
|
var OPENSHELL_ATTACHABLE_LABEL = "openshell.ai/sandbox-attachable=true";
|
|
13054
13380
|
var OPENSHELL_WORKSPACE_LABEL = "openshell.ai/sandbox-attachable-workspace";
|
|
13055
13381
|
var VOLUME_ROOT = "/cache";
|
|
@@ -13185,7 +13511,7 @@ git -C "$m" show "refs/heads/$base:$path"
|
|
|
13185
13511
|
var SandboxCache = class {
|
|
13186
13512
|
s;
|
|
13187
13513
|
exec;
|
|
13188
|
-
constructor(s, exec =
|
|
13514
|
+
constructor(s, exec = realExec2) {
|
|
13189
13515
|
this.s = s;
|
|
13190
13516
|
this.exec = exec;
|
|
13191
13517
|
}
|
|
@@ -13310,610 +13636,317 @@ var SandboxCache = class {
|
|
|
13310
13636
|
return rows;
|
|
13311
13637
|
}
|
|
13312
13638
|
/** Drops mirrors (and their dependency trees) for repositories not in `keep`. Returns what was dropped. */
|
|
13313
|
-
async prune(keep) {
|
|
13314
|
-
const have = new Set(keep.map((r) => `${r.host}/${r.path}`));
|
|
13315
|
-
const drop = (await this.list()).map((m) => m.repo).filter((r) => !have.has(`${r.host}/${r.path}`));
|
|
13316
|
-
for (const r of drop) {
|
|
13317
|
-
await this.helper(this.s.helperImage, `rm -rf ${VOLUME_ROOT}/${q(mirrorRelPath(r))} ${VOLUME_ROOT}/${q(depsRelDir(r))} ${VOLUME_ROOT}/${q(intelRelDir(r))}`, []);
|
|
13318
|
-
}
|
|
13319
|
-
return drop;
|
|
13320
|
-
}
|
|
13321
|
-
/** Recreates the volume empty; the next pass refreshes every mirror. */
|
|
13322
|
-
async reset() {
|
|
13323
|
-
try {
|
|
13324
|
-
await this.engine(["volume", "rm", "--force", this.s.volume]);
|
|
13325
|
-
} catch (e) {
|
|
13326
|
-
throw new Error(`could not remove volume ${this.s.volume}: ${describe(e)}`);
|
|
13327
|
-
}
|
|
13328
|
-
await this.ensureVolume();
|
|
13329
|
-
}
|
|
13330
|
-
};
|
|
13331
|
-
function describe(e) {
|
|
13332
|
-
const err3 = e;
|
|
13333
|
-
const lines2 = (err3.stderr?.trim() || err3.message || String(e)).split("\n");
|
|
13334
|
-
const tail3 = lines2.slice(-3);
|
|
13335
|
-
const first = lines2.find((l) => /^(fatal|error):/.test(l.trim()));
|
|
13336
|
-
return (first && !tail3.includes(first) ? [first, ...tail3] : tail3).join(" / ");
|
|
13337
|
-
}
|
|
13338
|
-
function cacheSettingsOf(cfg) {
|
|
13339
|
-
if (!cfg?.cacheVolume) return null;
|
|
13340
|
-
return {
|
|
13341
|
-
engine: cfg.engine ?? DEFAULT_CACHE_SETTINGS.engine,
|
|
13342
|
-
volume: cfg.cacheVolume,
|
|
13343
|
-
workspace: cfg.cacheWorkspace ?? DEFAULT_CACHE_SETTINGS.workspace,
|
|
13344
|
-
helperImage: cfg.cacheImage ?? DEFAULT_CACHE_SETTINGS.helperImage,
|
|
13345
|
-
depsImage: cfg.depsImage ?? cfg.image,
|
|
13346
|
-
depsCommand: cfg.depsCommand,
|
|
13347
|
-
depsLockfile: cfg.depsLockfile ?? DEFAULT_CACHE_SETTINGS.depsLockfile
|
|
13348
|
-
};
|
|
13349
|
-
}
|
|
13350
|
-
var sandboxCacheKey = (volume, r) => `sandbox_cache:${volume}:${r.host}/${r.path}`;
|
|
13351
|
-
function unmirroredRepos(served, mirrors) {
|
|
13352
|
-
const have = new Set(mirrors.map((m) => `${m.repo.host}/${m.repo.path}`));
|
|
13353
|
-
return served.map((r) => `${r.host}/${r.path}`).filter((k, i, a) => !have.has(k) && a.indexOf(k) === i);
|
|
13354
|
-
}
|
|
13355
|
-
var CACHE_REFRESH_INTERVAL_MS = 6e4;
|
|
13356
|
-
function makeCachePass(o) {
|
|
13357
|
-
const now = o.now ?? Date.now;
|
|
13358
|
-
let last = -Infinity;
|
|
13359
|
-
return async () => {
|
|
13360
|
-
if (now() - last < CACHE_REFRESH_INTERVAL_MS) return [];
|
|
13361
|
-
last = now();
|
|
13362
|
-
const all = [];
|
|
13363
|
-
for (const r of o.repos()) {
|
|
13364
|
-
let release;
|
|
13365
|
-
try {
|
|
13366
|
-
release = o.lock(r.dir);
|
|
13367
|
-
all.push(...await o.cache.refresh([r]));
|
|
13368
|
-
} catch (e) {
|
|
13369
|
-
all.push({ repo: r, ok: false, detail: describe(e) });
|
|
13370
|
-
} finally {
|
|
13371
|
-
release?.();
|
|
13372
|
-
}
|
|
13373
|
-
}
|
|
13374
|
-
for (const out of all) {
|
|
13375
|
-
const key = sandboxCacheKey(o.volume, out.repo);
|
|
13376
|
-
if (out.ok) o.ok(key);
|
|
13377
|
-
else await o.fail(key, `sandbox cache: ${out.repo.host}/${out.repo.path} did not refresh (${out.detail}); runs use the previous mirror. Resumes automatically when a later pass refreshes it`, new Date(now()).toISOString());
|
|
13378
|
-
}
|
|
13379
|
-
return all;
|
|
13380
|
-
};
|
|
13381
|
-
}
|
|
13382
|
-
|
|
13383
|
-
// src/passenger-containers.ts
|
|
13384
|
-
var realExec2 = (cmd, args, opts) => {
|
|
13385
|
-
try {
|
|
13386
|
-
return execFileSync8(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: opts?.timeoutMs });
|
|
13387
|
-
} catch (e) {
|
|
13388
|
-
const err3 = e;
|
|
13389
|
-
const why = [err3.stderr, err3.stdout].map((x) => (x ?? "").trim()).filter(Boolean).join(" / ");
|
|
13390
|
-
throw new Error(`${cmd} ${args.join(" ")}: ${why || err3.message.trim()}`);
|
|
13391
|
-
}
|
|
13392
|
-
};
|
|
13393
|
-
var DOCKER_INFO_TIMEOUT_MS = 1e4;
|
|
13394
|
-
function dockerAvailable(exec = realExec2) {
|
|
13395
|
-
try {
|
|
13396
|
-
exec("docker", ["info"], { timeoutMs: DOCKER_INFO_TIMEOUT_MS });
|
|
13397
|
-
return true;
|
|
13398
|
-
} catch {
|
|
13399
|
-
return false;
|
|
13400
|
-
}
|
|
13401
|
-
}
|
|
13402
|
-
var PASSENGER_IMAGE_REPO = "tablation/crew-passenger-mcp";
|
|
13403
|
-
function passengerImageRef(cfg) {
|
|
13404
|
-
return process.env.CREW_PASSENGER_IMAGE || cfg.ship.passengerImage || `${PASSENGER_IMAGE_REPO}:${crewVersion(cfg.crewHome)}`;
|
|
13405
|
-
}
|
|
13406
|
-
function imagePresent(image, exec = realExec2) {
|
|
13407
|
-
try {
|
|
13408
|
-
exec("docker", ["image", "inspect", image]);
|
|
13409
|
-
return true;
|
|
13410
|
-
} catch {
|
|
13411
|
-
return false;
|
|
13412
|
-
}
|
|
13413
|
-
}
|
|
13414
|
-
function ensureImage(image, exec = realExec2) {
|
|
13415
|
-
if (!imagePresent(image, exec)) exec("docker", ["pull", image]);
|
|
13416
|
-
}
|
|
13417
|
-
function containerNameFor(workspaceId) {
|
|
13418
|
-
return `crew-passenger-${workspaceId}`;
|
|
13419
|
-
}
|
|
13420
|
-
function portFor(workspaceId, base = 28765, span = 1e3) {
|
|
13421
|
-
const digest = createHash6("sha256").update(workspaceId).digest();
|
|
13422
|
-
return base + digest.readUInt32BE(0) % span;
|
|
13423
|
-
}
|
|
13424
|
-
function mountsDigest(mounts, image) {
|
|
13425
|
-
const sorted2 = [...mounts].sort((a, b) => a.containerPath.localeCompare(b.containerPath));
|
|
13426
|
-
return createHash6("sha256").update(JSON.stringify({ mounts: sorted2, image })).digest("hex").slice(0, 16);
|
|
13427
|
-
}
|
|
13428
|
-
function planContainers(cfg) {
|
|
13429
|
-
const byWorkspace = /* @__PURE__ */ new Map();
|
|
13430
|
-
const image = passengerImageRef(cfg);
|
|
13431
|
-
for (const route2 of cfg.routes) {
|
|
13432
|
-
if (!route2.enabled || !route2.hostPassengers || !route2.resolved?.workspaceId) continue;
|
|
13433
|
-
const workspaceId = route2.resolved.workspaceId;
|
|
13434
|
-
const mounts = byWorkspace.get(workspaceId) ?? /* @__PURE__ */ new Map();
|
|
13435
|
-
for (const target of passengerCheckoutTargets(route2, passengerMirrorArea(cfg.ship))) {
|
|
13436
|
-
mounts.set(target.name, { hostPath: target.dir, containerPath: `/workspace/${target.name}` });
|
|
13437
|
-
}
|
|
13438
|
-
byWorkspace.set(workspaceId, mounts);
|
|
13439
|
-
}
|
|
13440
|
-
return [...byWorkspace.entries()].filter(([, mounts]) => mounts.size > 0).map(([workspaceId, mounts]) => {
|
|
13441
|
-
const mountList = [...mounts.values()];
|
|
13442
|
-
return {
|
|
13443
|
-
workspaceId,
|
|
13444
|
-
containerName: containerNameFor(workspaceId),
|
|
13445
|
-
port: portFor(workspaceId),
|
|
13446
|
-
image,
|
|
13447
|
-
mounts: mountList,
|
|
13448
|
-
mountsHash: mountsDigest(mountList, image)
|
|
13449
|
-
};
|
|
13450
|
-
});
|
|
13451
|
-
}
|
|
13452
|
-
function listPassengerContainers(exec = realExec2) {
|
|
13453
|
-
const out = exec("docker", ["ps", "-a", "--filter", "name=crew-passenger-", "--format", "{{.Names}} {{.State}}"]);
|
|
13454
|
-
return out.split("\n").map((l) => l.trim()).filter(Boolean).map((line) => {
|
|
13455
|
-
const [name, state] = line.split(" ");
|
|
13456
|
-
return { name, running: state === "running" };
|
|
13457
|
-
});
|
|
13458
|
-
}
|
|
13459
|
-
function currentMountsHash(name, exec) {
|
|
13460
|
-
try {
|
|
13461
|
-
const out = exec("docker", ["inspect", "--format", '{{ index .Config.Labels "crew.mounts.hash" }}', name]);
|
|
13462
|
-
const hash2 = out.trim();
|
|
13463
|
-
return hash2 || void 0;
|
|
13464
|
-
} catch {
|
|
13465
|
-
return void 0;
|
|
13466
|
-
}
|
|
13467
|
-
}
|
|
13468
|
-
function stopContainer(name, exec = realExec2) {
|
|
13469
|
-
try {
|
|
13470
|
-
exec("docker", ["rm", "-f", name]);
|
|
13471
|
-
} catch {
|
|
13472
|
-
}
|
|
13473
|
-
}
|
|
13474
|
-
function startContainer(plan, tablationApiBaseUrl, sync, exec = realExec2) {
|
|
13475
|
-
const args = [
|
|
13476
|
-
"run",
|
|
13477
|
-
"-d",
|
|
13478
|
-
"--name",
|
|
13479
|
-
plan.containerName,
|
|
13480
|
-
"--restart",
|
|
13481
|
-
"unless-stopped",
|
|
13482
|
-
"-p",
|
|
13483
|
-
`${plan.port}:8765`,
|
|
13484
|
-
"-e",
|
|
13485
|
-
`PASSENGER_MCP_WORKSPACE_ID=${plan.workspaceId}`,
|
|
13486
|
-
"-e",
|
|
13487
|
-
`TABLATION_API_BASE_URL=${tablationApiBaseUrl}`,
|
|
13488
|
-
"--label",
|
|
13489
|
-
`crew.mounts.hash=${plan.mountsHash}`
|
|
13490
|
-
];
|
|
13491
|
-
if (sync) {
|
|
13492
|
-
args.push(
|
|
13493
|
-
"--add-host",
|
|
13494
|
-
"host.docker.internal:host-gateway",
|
|
13495
|
-
"-e",
|
|
13496
|
-
`PASSENGER_SYNC_URL=http://${sync.host}:${sync.port}/sync`,
|
|
13497
|
-
"-e",
|
|
13498
|
-
`PASSENGER_SYNC_SECRET=${sync.secret}`,
|
|
13499
|
-
"-e",
|
|
13500
|
-
`PASSENGER_MCP_SECRET=${sync.secret}`
|
|
13501
|
-
);
|
|
13502
|
-
}
|
|
13503
|
-
for (const m of plan.mounts) args.push("-v", `${m.hostPath}:${m.containerPath}:ro`);
|
|
13504
|
-
args.push(plan.image);
|
|
13505
|
-
exec("docker", args);
|
|
13506
|
-
}
|
|
13507
|
-
function syncPassengerContainers(cfg, tablationApiBaseUrl, exec = realExec2, syncEndpoints = /* @__PURE__ */ new Map()) {
|
|
13508
|
-
const plans = planContainers(cfg);
|
|
13509
|
-
const plannedByName = new Map(plans.map((p) => [p.containerName, p]));
|
|
13510
|
-
const existing = listPassengerContainers(exec);
|
|
13511
|
-
const existingByName = new Map(existing.map((c) => [c.name, c]));
|
|
13512
|
-
const started = [];
|
|
13513
|
-
const recreated = [];
|
|
13514
|
-
const stopped = [];
|
|
13515
|
-
const ensured = /* @__PURE__ */ new Set();
|
|
13516
|
-
const start = (plan, sync) => {
|
|
13517
|
-
if (!ensured.has(plan.image)) {
|
|
13518
|
-
ensureImage(plan.image, exec);
|
|
13519
|
-
ensured.add(plan.image);
|
|
13520
|
-
}
|
|
13521
|
-
startContainer(plan, tablationApiBaseUrl, sync, exec);
|
|
13522
|
-
};
|
|
13523
|
-
for (const plan of plans) {
|
|
13524
|
-
const sync = syncEndpoints.get(plan.workspaceId);
|
|
13525
|
-
const current = existingByName.get(plan.containerName);
|
|
13526
|
-
if (!current) {
|
|
13527
|
-
start(plan, sync);
|
|
13528
|
-
started.push(plan.containerName);
|
|
13529
|
-
} else if (!current.running) {
|
|
13530
|
-
stopContainer(plan.containerName, exec);
|
|
13531
|
-
start(plan, sync);
|
|
13532
|
-
started.push(plan.containerName);
|
|
13533
|
-
} else if (currentMountsHash(plan.containerName, exec) !== plan.mountsHash) {
|
|
13534
|
-
stopContainer(plan.containerName, exec);
|
|
13535
|
-
start(plan, sync);
|
|
13536
|
-
recreated.push(plan.containerName);
|
|
13537
|
-
}
|
|
13538
|
-
}
|
|
13539
|
-
for (const { name } of existing) {
|
|
13540
|
-
if (!plannedByName.has(name)) {
|
|
13541
|
-
stopContainer(name, exec);
|
|
13542
|
-
stopped.push(name);
|
|
13543
|
-
}
|
|
13544
|
-
}
|
|
13545
|
-
return { started, recreated, stopped };
|
|
13546
|
-
}
|
|
13547
|
-
function passengerCheckoutSyncSpecs(cfg, workspaceId, onRefused) {
|
|
13548
|
-
const specs = [];
|
|
13549
|
-
for (const route2 of cfg.routes) {
|
|
13550
|
-
if (!route2.enabled || !route2.hostPassengers || !route2.resolved?.workspaceId) continue;
|
|
13551
|
-
if (workspaceId && route2.resolved.workspaceId !== workspaceId) continue;
|
|
13552
|
-
const routeWorkspaceId = route2.resolved.workspaceId;
|
|
13553
|
-
const mirrorArea = passengerMirrorArea(cfg.ship);
|
|
13554
|
-
const cache = mirrorArea ? cacheSettingsOf(cfg.ship.sandbox) : null;
|
|
13555
|
-
const ordinaryByName = new Map(reposOf(route2).map((t) => [t.name, t]));
|
|
13556
|
-
for (const target of passengerCheckoutTargets(route2, mirrorArea)) {
|
|
13557
|
-
const ordinary = ordinaryByName.get(target.name);
|
|
13558
|
-
const override = route2.repoOverrides[target.name];
|
|
13559
|
-
let refused = false;
|
|
13560
|
-
const declared = ordinary ? loadRepoConfigTolerant(ordinary.dir, (e) => {
|
|
13561
|
-
refused = true;
|
|
13562
|
-
onRefused?.(target.name, e);
|
|
13563
|
-
}) : null;
|
|
13564
|
-
if (refused) continue;
|
|
13565
|
-
const effective = resolveRepoConfig(
|
|
13566
|
-
declared,
|
|
13567
|
-
{ branch: { ...route2.branch, ...override?.branch } },
|
|
13568
|
-
ordinary?.dir ?? target.dir
|
|
13569
|
-
);
|
|
13570
|
-
specs.push({
|
|
13571
|
-
name: target.name,
|
|
13572
|
-
workspaceId: routeWorkspaceId,
|
|
13573
|
-
dir: target.dir,
|
|
13574
|
-
remote: target.remote,
|
|
13575
|
-
gitRemoteName: effective.branch.remote,
|
|
13576
|
-
base: effective.branch.base,
|
|
13577
|
-
originUrl: ordinary ? originUrlOf(ordinary.dir, effective.branch.remote) : null,
|
|
13578
|
-
cloneScheme: cfg.ship.cloneScheme,
|
|
13579
|
-
...target.forgeHost ? { forgeHost: target.forgeHost } : {},
|
|
13580
|
-
...cache ? { mirror: { cache } } : {}
|
|
13581
|
-
});
|
|
13582
|
-
}
|
|
13583
|
-
}
|
|
13584
|
-
return specs;
|
|
13585
|
-
}
|
|
13586
|
-
function syncAllPassengerCheckouts(cfg, onRefused) {
|
|
13587
|
-
return passengerCheckoutSyncSpecs(cfg, void 0, onRefused).filter((spec) => !spec.mirror).map((spec) => ({
|
|
13588
|
-
name: spec.name,
|
|
13589
|
-
workspaceId: spec.workspaceId,
|
|
13590
|
-
outcome: syncPassengerCheckout(spec.dir, spec.remote, spec.gitRemoteName, spec.base, { originUrl: spec.originUrl, scheme: spec.cloneScheme, host: spec.forgeHost })
|
|
13591
|
-
}));
|
|
13592
|
-
}
|
|
13593
|
-
|
|
13594
|
-
// src/sandbox-image.ts
|
|
13595
|
-
var SANDBOX_BASE_IMAGE = "nvcr.io/nvidia/base/ubuntu:24.04";
|
|
13596
|
-
var SANDBOX_OPENSHELL_VERSION = "0.1.6";
|
|
13597
|
-
var SANDBOX_CLAUDE_VERSION = "2.1.309";
|
|
13598
|
-
var SANDBOX_CLAUDE_DIST = "https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases";
|
|
13599
|
-
var SANDBOX_CLAUDE_SHA256 = {
|
|
13600
|
-
x86_64: { platform: "linux-x64", sha256: "4d704a8aecbe038affa3000f498ae17c1b4f753add8facb8764120affc99b658" },
|
|
13601
|
-
aarch64: { platform: "linux-arm64", sha256: "9796dd26899337f687739a0b39a7353b639f062a3436a7b941fcf19a1b757a9b" }
|
|
13602
|
-
};
|
|
13603
|
-
var SANDBOX_UID = 1e3;
|
|
13604
|
-
var CREW_PREFIX = "/opt/crew";
|
|
13605
|
-
var SANDBOX_BRIDGE_PATH = `${CREW_PREFIX}/bin/intel-bridge`;
|
|
13606
|
-
function readBridgeBundle() {
|
|
13607
|
-
const here = dirname15(fileURLToPath(import.meta.url));
|
|
13608
|
-
for (const p of [join32(here, "sandbox-intel-bridge.cjs"), join32(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
|
|
13609
|
-
if (existsSync29(p)) return readFileSync28(p, "utf8");
|
|
13639
|
+
async prune(keep) {
|
|
13640
|
+
const have = new Set(keep.map((r) => `${r.host}/${r.path}`));
|
|
13641
|
+
const drop = (await this.list()).map((m) => m.repo).filter((r) => !have.has(`${r.host}/${r.path}`));
|
|
13642
|
+
for (const r of drop) {
|
|
13643
|
+
await this.helper(this.s.helperImage, `rm -rf ${VOLUME_ROOT}/${q(mirrorRelPath(r))} ${VOLUME_ROOT}/${q(depsRelDir(r))} ${VOLUME_ROOT}/${q(intelRelDir(r))}`, []);
|
|
13644
|
+
}
|
|
13645
|
+
return drop;
|
|
13646
|
+
}
|
|
13647
|
+
/** Recreates the volume empty; the next pass refreshes every mirror. */
|
|
13648
|
+
async reset() {
|
|
13649
|
+
try {
|
|
13650
|
+
await this.engine(["volume", "rm", "--force", this.s.volume]);
|
|
13651
|
+
} catch (e) {
|
|
13652
|
+
throw new Error(`could not remove volume ${this.s.volume}: ${describe(e)}`);
|
|
13653
|
+
}
|
|
13654
|
+
await this.ensureVolume();
|
|
13610
13655
|
}
|
|
13611
|
-
return void 0;
|
|
13612
|
-
}
|
|
13613
|
-
var SANDBOX_UV_VERSION = "0.13.6";
|
|
13614
|
-
var SANDBOX_SERENA_VERSION = "2.1.0";
|
|
13615
|
-
var SERENA_IMAGE_HOME = `${CREW_PREFIX}/serena`;
|
|
13616
|
-
var SERENA_LANGUAGE_SERVERS_ENV = "CREW_SERENA_LANGUAGE_SERVERS";
|
|
13617
|
-
var SANDBOX_RETRY_AFTER_MS = 60 * 60 * 1e3;
|
|
13618
|
-
var KEEP_TAGS = 2;
|
|
13619
|
-
var CREDENTIAL_HELPER = `#!/bin/sh
|
|
13620
|
-
# git credential helper: answers from the environment the runner passes in, so
|
|
13621
|
-
# no token is ever written into an image layer.
|
|
13622
|
-
[ "$1" = get ] || exit 0
|
|
13623
|
-
[ -n "$CREW_FORGE_TOKEN" ] || exit 0
|
|
13624
|
-
echo "username=\${CREW_FORGE_USER:-x-access-token}"
|
|
13625
|
-
echo "password=$CREW_FORGE_TOKEN"
|
|
13626
|
-
`;
|
|
13627
|
-
var MCP_CONFIG = `${JSON.stringify({ mcpServers: {} }, null, 2)}
|
|
13628
|
-
`;
|
|
13629
|
-
var hash = (parts) => createHash7("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 12);
|
|
13630
|
-
var slug = (s) => s.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "repo";
|
|
13631
|
-
var run2 = (cmd) => `RUN ["/bin/bash", "-c", ${JSON.stringify(`set -euo pipefail; ${cmd}`)}]`;
|
|
13632
|
-
var CREW_ENV = {
|
|
13633
|
-
CREW_SANDBOX: "1",
|
|
13634
|
-
CREW_CACHE_DIR: `${CREW_PREFIX}/cache`,
|
|
13635
|
-
XDG_CACHE_HOME: `${CREW_PREFIX}/cache`,
|
|
13636
|
-
npm_config_cache: `${CREW_PREFIX}/cache/npm`,
|
|
13637
|
-
npm_config_store_dir: `${CREW_PREFIX}/pnpm-store`,
|
|
13638
|
-
// pnpm 11 ignores npm_config_store_dir and reads only this spelling (CREW-2973): without it `pnpm fetch`
|
|
13639
|
-
// at build time fills the builder's home store, and a run's offline install finds /opt/crew/pnpm-store empty.
|
|
13640
|
-
pnpm_config_store_dir: `${CREW_PREFIX}/pnpm-store`,
|
|
13641
|
-
PNPM_HOME: `${CREW_PREFIX}/pnpm`,
|
|
13642
|
-
// A run cannot reach the download host, so an in-run update attempt is only noise.
|
|
13643
|
-
DISABLE_AUTOUPDATER: "1"
|
|
13644
13656
|
};
|
|
13645
|
-
function
|
|
13646
|
-
const
|
|
13647
|
-
|
|
13648
|
-
|
|
13649
|
-
|
|
13657
|
+
function describe(e) {
|
|
13658
|
+
const err3 = e;
|
|
13659
|
+
const lines2 = (err3.stderr?.trim() || err3.message || String(e)).split("\n");
|
|
13660
|
+
const tail3 = lines2.slice(-3);
|
|
13661
|
+
const first = lines2.find((l) => /^(fatal|error):/.test(l.trim()));
|
|
13662
|
+
return (first && !tail3.includes(first) ? [first, ...tail3] : tail3).join(" / ");
|
|
13663
|
+
}
|
|
13664
|
+
function cacheSettingsOf(cfg) {
|
|
13665
|
+
if (!cfg?.cacheVolume) return null;
|
|
13666
|
+
return {
|
|
13667
|
+
engine: cfg.engine ?? DEFAULT_CACHE_SETTINGS.engine,
|
|
13668
|
+
volume: cfg.cacheVolume,
|
|
13669
|
+
workspace: cfg.cacheWorkspace ?? DEFAULT_CACHE_SETTINGS.workspace,
|
|
13670
|
+
helperImage: cfg.cacheImage ?? DEFAULT_CACHE_SETTINGS.helperImage,
|
|
13671
|
+
depsImage: cfg.depsImage ?? cfg.image,
|
|
13672
|
+
depsCommand: cfg.depsCommand,
|
|
13673
|
+
depsLockfile: cfg.depsLockfile ?? DEFAULT_CACHE_SETTINGS.depsLockfile
|
|
13650
13674
|
};
|
|
13651
|
-
return Object.entries(vars).map(([k, v]) => `${k}=${v}; export ${k}; `).join("");
|
|
13652
13675
|
}
|
|
13653
|
-
|
|
13654
|
-
|
|
13655
|
-
|
|
13656
|
-
|
|
13657
|
-
`mkdir -p ${CREW_PREFIX}/bin`,
|
|
13658
|
-
`curl -fsSL --retry 3 -o ${CREW_PREFIX}/bin/claude "${SANDBOX_CLAUDE_DIST}/${SANDBOX_CLAUDE_VERSION}/$p/claude"`,
|
|
13659
|
-
`echo "$sum ${CREW_PREFIX}/bin/claude" | sha256sum -c -`,
|
|
13660
|
-
`chmod 0755 ${CREW_PREFIX}/bin/claude`,
|
|
13661
|
-
`${CREW_PREFIX}/bin/claude --version | grep -F "${SANDBOX_CLAUDE_VERSION}"`
|
|
13662
|
-
].join("; ");
|
|
13676
|
+
var sandboxCacheKey = (volume, r) => `sandbox_cache:${volume}:${r.host}/${r.path}`;
|
|
13677
|
+
function unmirroredRepos(served, mirrors) {
|
|
13678
|
+
const have = new Set(mirrors.map((m) => `${m.repo.host}/${m.repo.path}`));
|
|
13679
|
+
return served.map((r) => `${r.host}/${r.path}`).filter((k, i, a) => !have.has(k) && a.indexOf(k) === i);
|
|
13663
13680
|
}
|
|
13664
|
-
|
|
13665
|
-
|
|
13666
|
-
|
|
13667
|
-
|
|
13668
|
-
|
|
13669
|
-
|
|
13670
|
-
|
|
13671
|
-
|
|
13681
|
+
var CACHE_REFRESH_INTERVAL_MS = 6e4;
|
|
13682
|
+
function makeCachePass(o) {
|
|
13683
|
+
const now = o.now ?? Date.now;
|
|
13684
|
+
let last = -Infinity;
|
|
13685
|
+
return async () => {
|
|
13686
|
+
if (now() - last < CACHE_REFRESH_INTERVAL_MS) return [];
|
|
13687
|
+
last = now();
|
|
13688
|
+
const all = [];
|
|
13689
|
+
for (const r of o.repos()) {
|
|
13690
|
+
let release;
|
|
13691
|
+
try {
|
|
13692
|
+
release = o.lock(r.dir);
|
|
13693
|
+
all.push(...await o.cache.refresh([r]));
|
|
13694
|
+
} catch (e) {
|
|
13695
|
+
all.push({ repo: r, ok: false, detail: describe(e) });
|
|
13696
|
+
} finally {
|
|
13697
|
+
release?.();
|
|
13698
|
+
}
|
|
13699
|
+
}
|
|
13700
|
+
for (const out of all) {
|
|
13701
|
+
const key = sandboxCacheKey(o.volume, out.repo);
|
|
13702
|
+
if (out.ok) o.ok(key);
|
|
13703
|
+
else await o.fail(key, `sandbox cache: ${out.repo.host}/${out.repo.path} did not refresh (${out.detail}); runs use the previous mirror. Resumes automatically when a later pass refreshes it`, new Date(now()).toISOString());
|
|
13704
|
+
}
|
|
13705
|
+
return all;
|
|
13706
|
+
};
|
|
13672
13707
|
}
|
|
13673
|
-
|
|
13674
|
-
|
|
13675
|
-
|
|
13676
|
-
|
|
13677
|
-
|
|
13708
|
+
|
|
13709
|
+
// src/passenger-containers.ts
|
|
13710
|
+
var realExec = (cmd, args, opts) => {
|
|
13711
|
+
try {
|
|
13712
|
+
return execFileSync9(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: opts?.timeoutMs });
|
|
13713
|
+
} catch (e) {
|
|
13714
|
+
const err3 = e;
|
|
13715
|
+
const why = [err3.stderr, err3.stdout].map((x) => (x ?? "").trim()).filter(Boolean).join(" / ");
|
|
13716
|
+
throw new Error(`${cmd} ${args.join(" ")}: ${why || err3.message.trim()}`);
|
|
13717
|
+
}
|
|
13718
|
+
};
|
|
13719
|
+
var DOCKER_INFO_TIMEOUT_MS = 1e4;
|
|
13720
|
+
function dockerAvailable(exec = realExec) {
|
|
13721
|
+
try {
|
|
13722
|
+
exec("docker", ["info"], { timeoutMs: DOCKER_INFO_TIMEOUT_MS });
|
|
13723
|
+
return true;
|
|
13724
|
+
} catch {
|
|
13725
|
+
return false;
|
|
13726
|
+
}
|
|
13678
13727
|
}
|
|
13679
|
-
|
|
13680
|
-
|
|
13681
|
-
|
|
13682
|
-
`LABEL io.crew.sandbox.layer="base" io.crew.sandbox.openshell="${SANDBOX_OPENSHELL_VERSION}"`,
|
|
13683
|
-
""
|
|
13684
|
-
].join("\n");
|
|
13685
|
-
return { name: "base", tag: `crew-sandbox-base:${hash({ SANDBOX_BASE_IMAGE, SANDBOX_OPENSHELL_VERSION })}`, dockerfile, files: {} };
|
|
13728
|
+
var PASSENGER_IMAGE_REPO = "tablation/crew-passenger-mcp";
|
|
13729
|
+
function passengerImageRef(cfg) {
|
|
13730
|
+
return process.env.CREW_PASSENGER_IMAGE || cfg.ship.passengerImage || `${PASSENGER_IMAGE_REPO}:${crewVersion(cfg.crewHome)}`;
|
|
13686
13731
|
}
|
|
13687
|
-
|
|
13688
|
-
|
|
13689
|
-
|
|
13690
|
-
|
|
13691
|
-
|
|
13692
|
-
|
|
13693
|
-
return readFileSync28(path, "utf8");
|
|
13694
|
-
} catch {
|
|
13695
|
-
}
|
|
13732
|
+
function imagePresent(image, exec = realExec) {
|
|
13733
|
+
try {
|
|
13734
|
+
exec("docker", ["image", "inspect", image]);
|
|
13735
|
+
return true;
|
|
13736
|
+
} catch {
|
|
13737
|
+
return false;
|
|
13696
13738
|
}
|
|
13697
|
-
return "";
|
|
13698
13739
|
}
|
|
13699
|
-
function
|
|
13700
|
-
|
|
13701
|
-
const env = Object.entries(CREW_ENV).map(([k, v]) => `${k}=${v}`).join(" ");
|
|
13702
|
-
const dockerfile = [
|
|
13703
|
-
`FROM ${base.tag}`,
|
|
13704
|
-
"USER root",
|
|
13705
|
-
`COPY ${CA_BUNDLE_FILE} /etc/ssl/certs/ca-certificates.crt`,
|
|
13706
|
-
run2(APT_HTTPS_COMMAND),
|
|
13707
|
-
run2(`apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git${intel ? " python3 python3-venv nodejs" : ""} && rm -rf /var/lib/apt/lists/*`),
|
|
13708
|
-
`COPY credential-helper ${CREW_PREFIX}/bin/credential-helper`,
|
|
13709
|
-
`COPY mcp.json ${CREW_PREFIX}/mcp/mcp.json`,
|
|
13710
|
-
...bridge ? [`COPY intel-bridge ${SANDBOX_BRIDGE_PATH}`] : [],
|
|
13711
|
-
run2(claudeInstallCommand()),
|
|
13712
|
-
...intel ? [run2(`mkdir -p ${CREW_PREFIX}/cache && ${serenaInstallCommand()}`)] : [],
|
|
13713
|
-
run2(`chmod 0755 ${CREW_PREFIX}/bin/credential-helper && git config --system credential.helper ${CREW_PREFIX}/bin/credential-helper`),
|
|
13714
|
-
run2(`mkdir -p ${CREW_PREFIX}/cache ${CREW_PREFIX}/pnpm-store ${CREW_PREFIX}/pnpm /sandbox && chown -R ${SANDBOX_UID}:${SANDBOX_UID} ${CREW_PREFIX} /sandbox`),
|
|
13715
|
-
...intel ? [`ENV ${SERENA_LANGUAGE_SERVERS_ENV}=${SERENA_IMAGE_HOME}/language_servers UV_PYTHON_INSTALL_DIR=${CREW_PREFIX}/uv/python`] : [],
|
|
13716
|
-
`ENV ${env} PATH=${CREW_PREFIX}/pnpm:${CREW_PREFIX}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,
|
|
13717
|
-
`LABEL io.crew.sandbox.layer="crew" io.crew.sandbox.claude="${SANDBOX_CLAUDE_VERSION}"`,
|
|
13718
|
-
""
|
|
13719
|
-
].join("\n");
|
|
13720
|
-
return { name: "crew", tag: `crew-sandbox-crew:${hash({ base: base.tag, dockerfile, files })}`, dockerfile, files, caBundleFile: CA_BUNDLE_FILE };
|
|
13740
|
+
function ensureImage(image, exec = realExec) {
|
|
13741
|
+
if (!imagePresent(image, exec)) exec("docker", ["pull", image]);
|
|
13721
13742
|
}
|
|
13722
|
-
|
|
13723
|
-
|
|
13724
|
-
var globToRegExp = (glob) => new RegExp(`^${glob.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")}$`);
|
|
13725
|
-
function readWarmFiles(dir, ref, patterns) {
|
|
13726
|
-
if (patterns.length === 0) return {};
|
|
13727
|
-
const git2 = (args) => execFileSync9("git", ["-C", dir, ...args], { encoding: "utf8", maxBuffer: WARM_MAX_BYTES, stdio: ["ignore", "pipe", "pipe"] });
|
|
13728
|
-
const all = git2(["ls-tree", "-r", "--name-only", ref]).split("\n").filter(Boolean);
|
|
13729
|
-
const res = patterns.map(globToRegExp);
|
|
13730
|
-
const out = {};
|
|
13731
|
-
let total = 0;
|
|
13732
|
-
for (const path of all.filter((f) => res.some((re) => re.test(f))).sort()) {
|
|
13733
|
-
const content = git2(["show", `${ref}:${path}`]);
|
|
13734
|
-
total += content.length;
|
|
13735
|
-
if (total > WARM_MAX_BYTES) throw new Error(`sandbox.warm files exceed ${WARM_MAX_BYTES} bytes`);
|
|
13736
|
-
out[path] = content;
|
|
13737
|
-
}
|
|
13738
|
-
return out;
|
|
13743
|
+
function containerNameFor(workspaceId) {
|
|
13744
|
+
return `crew-passenger-${workspaceId}`;
|
|
13739
13745
|
}
|
|
13740
|
-
function
|
|
13741
|
-
const
|
|
13742
|
-
|
|
13743
|
-
|
|
13744
|
-
|
|
13745
|
-
|
|
13746
|
-
|
|
13747
|
-
|
|
13748
|
-
|
|
13749
|
-
|
|
13750
|
-
|
|
13751
|
-
|
|
13752
|
-
|
|
13753
|
-
|
|
13754
|
-
|
|
13755
|
-
|
|
13756
|
-
|
|
13757
|
-
|
|
13758
|
-
|
|
13759
|
-
|
|
13760
|
-
|
|
13761
|
-
|
|
13762
|
-
|
|
13763
|
-
|
|
13764
|
-
|
|
13765
|
-
|
|
13766
|
-
|
|
13767
|
-
|
|
13768
|
-
|
|
13769
|
-
|
|
13770
|
-
|
|
13771
|
-
if (warming) lines2.push("WORKDIR /sandbox", run2(`rm -rf ${WARM_DIR}`));
|
|
13772
|
-
lines2.push(`LABEL io.crew.sandbox.layer="repo" io.crew.sandbox.repo=${JSON.stringify(repo)}`, "");
|
|
13773
|
-
const dockerfile = lines2.join("\n");
|
|
13774
|
-
return { name: "repo", tag: `crew-sandbox/${slug(repo)}:${hash({ crew: crew.tag, dockerfile, files })}`, dockerfile, files };
|
|
13746
|
+
function portFor(workspaceId, base = 28765, span = 1e3) {
|
|
13747
|
+
const digest = createHash7("sha256").update(workspaceId).digest();
|
|
13748
|
+
return base + digest.readUInt32BE(0) % span;
|
|
13749
|
+
}
|
|
13750
|
+
function mountsDigest(mounts, image) {
|
|
13751
|
+
const sorted2 = [...mounts].sort((a, b) => a.containerPath.localeCompare(b.containerPath));
|
|
13752
|
+
return createHash7("sha256").update(JSON.stringify({ mounts: sorted2, image })).digest("hex").slice(0, 16);
|
|
13753
|
+
}
|
|
13754
|
+
function planContainers(cfg) {
|
|
13755
|
+
const byWorkspace = /* @__PURE__ */ new Map();
|
|
13756
|
+
const image = passengerImageRef(cfg);
|
|
13757
|
+
for (const route2 of cfg.routes) {
|
|
13758
|
+
if (!route2.enabled || !route2.hostPassengers || !route2.resolved?.workspaceId) continue;
|
|
13759
|
+
const workspaceId = route2.resolved.workspaceId;
|
|
13760
|
+
const mounts = byWorkspace.get(workspaceId) ?? /* @__PURE__ */ new Map();
|
|
13761
|
+
for (const target of passengerCheckoutTargets(route2, passengerMirrorArea(cfg.ship))) {
|
|
13762
|
+
mounts.set(target.name, { hostPath: target.dir, containerPath: `/workspace/${target.name}` });
|
|
13763
|
+
}
|
|
13764
|
+
byWorkspace.set(workspaceId, mounts);
|
|
13765
|
+
}
|
|
13766
|
+
return [...byWorkspace.entries()].filter(([, mounts]) => mounts.size > 0).map(([workspaceId, mounts]) => {
|
|
13767
|
+
const mountList = [...mounts.values()];
|
|
13768
|
+
return {
|
|
13769
|
+
workspaceId,
|
|
13770
|
+
containerName: containerNameFor(workspaceId),
|
|
13771
|
+
port: portFor(workspaceId),
|
|
13772
|
+
image,
|
|
13773
|
+
mounts: mountList,
|
|
13774
|
+
mountsHash: mountsDigest(mountList, image)
|
|
13775
|
+
};
|
|
13776
|
+
});
|
|
13775
13777
|
}
|
|
13776
|
-
function
|
|
13777
|
-
const
|
|
13778
|
-
|
|
13779
|
-
|
|
13780
|
-
|
|
13778
|
+
function listPassengerContainers(exec = realExec) {
|
|
13779
|
+
const out = exec("docker", ["ps", "-a", "--filter", "name=crew-passenger-", "--format", "{{.Names}} {{.State}}"]);
|
|
13780
|
+
return out.split("\n").map((l) => l.trim()).filter(Boolean).map((line) => {
|
|
13781
|
+
const [name, state] = line.split(" ");
|
|
13782
|
+
return { name, running: state === "running" };
|
|
13783
|
+
});
|
|
13781
13784
|
}
|
|
13782
|
-
|
|
13783
|
-
var shipSandboxRef = () => ({ name: SHIP_SANDBOX_KEY, decl: { packages: [], setup: [] } });
|
|
13784
|
-
var sandboxStatePath = (stateDir) => join32(stateDir, "sandbox-images.json");
|
|
13785
|
-
function readSandboxState(stateDir) {
|
|
13785
|
+
function currentMountsHash(name, exec) {
|
|
13786
13786
|
try {
|
|
13787
|
-
const
|
|
13788
|
-
|
|
13787
|
+
const out = exec("docker", ["inspect", "--format", '{{ index .Config.Labels "crew.mounts.hash" }}', name]);
|
|
13788
|
+
const hash2 = out.trim();
|
|
13789
|
+
return hash2 || void 0;
|
|
13789
13790
|
} catch {
|
|
13790
|
-
return
|
|
13791
|
+
return void 0;
|
|
13791
13792
|
}
|
|
13792
13793
|
}
|
|
13793
|
-
function
|
|
13794
|
-
|
|
13795
|
-
|
|
13796
|
-
|
|
13797
|
-
|
|
13798
|
-
renameSync3(`${file}.tmp`, file);
|
|
13794
|
+
function stopContainer(name, exec = realExec) {
|
|
13795
|
+
try {
|
|
13796
|
+
exec("docker", ["rm", "-f", name]);
|
|
13797
|
+
} catch {
|
|
13798
|
+
}
|
|
13799
13799
|
}
|
|
13800
|
-
function
|
|
13801
|
-
|
|
13800
|
+
function startContainer(plan, tablationApiBaseUrl, sync, exec = realExec) {
|
|
13801
|
+
const args = [
|
|
13802
|
+
"run",
|
|
13803
|
+
"-d",
|
|
13804
|
+
"--name",
|
|
13805
|
+
plan.containerName,
|
|
13806
|
+
"--restart",
|
|
13807
|
+
"unless-stopped",
|
|
13808
|
+
"-p",
|
|
13809
|
+
`${plan.port}:8765`,
|
|
13810
|
+
"-e",
|
|
13811
|
+
`PASSENGER_MCP_WORKSPACE_ID=${plan.workspaceId}`,
|
|
13812
|
+
"-e",
|
|
13813
|
+
`TABLATION_API_BASE_URL=${tablationApiBaseUrl}`,
|
|
13814
|
+
"--label",
|
|
13815
|
+
`crew.mounts.hash=${plan.mountsHash}`
|
|
13816
|
+
];
|
|
13817
|
+
if (sync) {
|
|
13818
|
+
args.push(
|
|
13819
|
+
"--add-host",
|
|
13820
|
+
"host.docker.internal:host-gateway",
|
|
13821
|
+
"-e",
|
|
13822
|
+
`PASSENGER_SYNC_URL=http://${sync.host}:${sync.port}/sync`,
|
|
13823
|
+
"-e",
|
|
13824
|
+
`PASSENGER_SYNC_SECRET=${sync.secret}`,
|
|
13825
|
+
"-e",
|
|
13826
|
+
`PASSENGER_MCP_SECRET=${sync.secret}`
|
|
13827
|
+
);
|
|
13828
|
+
}
|
|
13829
|
+
for (const m of plan.mounts) args.push("-v", `${m.hostPath}:${m.containerPath}:ro`);
|
|
13830
|
+
args.push(plan.image);
|
|
13831
|
+
exec("docker", args);
|
|
13802
13832
|
}
|
|
13803
|
-
function
|
|
13804
|
-
|
|
13833
|
+
function syncPassengerContainers(cfg, tablationApiBaseUrl, exec = realExec, syncEndpoints = /* @__PURE__ */ new Map()) {
|
|
13834
|
+
const plans = planContainers(cfg);
|
|
13835
|
+
const plannedByName = new Map(plans.map((p) => [p.containerName, p]));
|
|
13836
|
+
const existing = listPassengerContainers(exec);
|
|
13837
|
+
const existingByName = new Map(existing.map((c) => [c.name, c]));
|
|
13838
|
+
const started = [];
|
|
13839
|
+
const recreated = [];
|
|
13840
|
+
const stopped = [];
|
|
13841
|
+
const ensured = /* @__PURE__ */ new Set();
|
|
13842
|
+
const start = (plan, sync) => {
|
|
13843
|
+
if (!ensured.has(plan.image)) {
|
|
13844
|
+
ensureImage(plan.image, exec);
|
|
13845
|
+
ensured.add(plan.image);
|
|
13846
|
+
}
|
|
13847
|
+
startContainer(plan, tablationApiBaseUrl, sync, exec);
|
|
13848
|
+
};
|
|
13849
|
+
for (const plan of plans) {
|
|
13850
|
+
const sync = syncEndpoints.get(plan.workspaceId);
|
|
13851
|
+
const current = existingByName.get(plan.containerName);
|
|
13852
|
+
if (!current) {
|
|
13853
|
+
start(plan, sync);
|
|
13854
|
+
started.push(plan.containerName);
|
|
13855
|
+
} else if (!current.running) {
|
|
13856
|
+
stopContainer(plan.containerName, exec);
|
|
13857
|
+
start(plan, sync);
|
|
13858
|
+
started.push(plan.containerName);
|
|
13859
|
+
} else if (currentMountsHash(plan.containerName, exec) !== plan.mountsHash) {
|
|
13860
|
+
stopContainer(plan.containerName, exec);
|
|
13861
|
+
start(plan, sync);
|
|
13862
|
+
recreated.push(plan.containerName);
|
|
13863
|
+
}
|
|
13864
|
+
}
|
|
13865
|
+
for (const { name } of existing) {
|
|
13866
|
+
if (!plannedByName.has(name)) {
|
|
13867
|
+
stopContainer(name, exec);
|
|
13868
|
+
stopped.push(name);
|
|
13869
|
+
}
|
|
13870
|
+
}
|
|
13871
|
+
return { started, recreated, stopped };
|
|
13805
13872
|
}
|
|
13806
|
-
function
|
|
13807
|
-
const
|
|
13808
|
-
const
|
|
13809
|
-
|
|
13810
|
-
|
|
13873
|
+
function passengerCheckoutSyncSpecs(cfg, workspaceId, onRefused) {
|
|
13874
|
+
const specs = [];
|
|
13875
|
+
for (const route2 of cfg.routes) {
|
|
13876
|
+
if (!route2.enabled || !route2.hostPassengers || !route2.resolved?.workspaceId) continue;
|
|
13877
|
+
if (workspaceId && route2.resolved.workspaceId !== workspaceId) continue;
|
|
13878
|
+
const routeWorkspaceId = route2.resolved.workspaceId;
|
|
13879
|
+
const mirrorArea = passengerMirrorArea(cfg.ship);
|
|
13880
|
+
const cache = mirrorArea ? cacheSettingsOf(cfg.ship.sandbox) : null;
|
|
13881
|
+
const ordinaryByName = new Map(reposOf(route2).map((t) => [t.name, t]));
|
|
13882
|
+
for (const target of passengerCheckoutTargets(route2, mirrorArea)) {
|
|
13883
|
+
const ordinary = ordinaryByName.get(target.name);
|
|
13884
|
+
const override = route2.repoOverrides[target.name];
|
|
13885
|
+
let refused = false;
|
|
13886
|
+
const declared = ordinary ? loadRepoConfigTolerant(ordinary.dir, (e) => {
|
|
13887
|
+
refused = true;
|
|
13888
|
+
onRefused?.(target.name, e);
|
|
13889
|
+
}) : null;
|
|
13890
|
+
if (refused) continue;
|
|
13891
|
+
const effective = resolveRepoConfig(
|
|
13892
|
+
declared,
|
|
13893
|
+
{ branch: { ...route2.branch, ...override?.branch } },
|
|
13894
|
+
ordinary?.dir ?? target.dir
|
|
13895
|
+
);
|
|
13896
|
+
specs.push({
|
|
13897
|
+
name: target.name,
|
|
13898
|
+
workspaceId: routeWorkspaceId,
|
|
13899
|
+
dir: target.dir,
|
|
13900
|
+
remote: target.remote,
|
|
13901
|
+
gitRemoteName: effective.branch.remote,
|
|
13902
|
+
base: effective.branch.base,
|
|
13903
|
+
originUrl: ordinary ? originUrlOf(ordinary.dir, effective.branch.remote) : null,
|
|
13904
|
+
cloneScheme: cfg.ship.cloneScheme,
|
|
13905
|
+
...target.forgeHost ? { forgeHost: target.forgeHost } : {},
|
|
13906
|
+
...cache ? { mirror: { cache } } : {}
|
|
13907
|
+
});
|
|
13908
|
+
}
|
|
13811
13909
|
}
|
|
13812
|
-
|
|
13813
|
-
if (current.tag !== plan.tag) return { status: "stale", detail: `running ${current.tag} (claude ${current.claude ?? "unknown"}), declaration now builds ${plan.tag} (claude ${plan.claude})` };
|
|
13814
|
-
return { status: "ok", detail: `${current.tag} built ${current.builtAt}, claude ${current.claude ?? "unknown"}` };
|
|
13910
|
+
return specs;
|
|
13815
13911
|
}
|
|
13816
|
-
|
|
13817
|
-
|
|
13818
|
-
|
|
13819
|
-
|
|
13820
|
-
|
|
13821
|
-
|
|
13822
|
-
|
|
13823
|
-
|
|
13824
|
-
|
|
13825
|
-
|
|
13826
|
-
child.on("error", (e) => done(127, `${e.message}
|
|
13827
|
-
`));
|
|
13828
|
-
child.on("close", (code) => done(code ?? 1));
|
|
13829
|
-
});
|
|
13830
|
-
var engineHasImage = (engine = "docker", exec = realExec2) => (tag) => {
|
|
13912
|
+
function syncAllPassengerCheckouts(cfg, onRefused) {
|
|
13913
|
+
return passengerCheckoutSyncSpecs(cfg, void 0, onRefused).filter((spec) => !spec.mirror).map((spec) => ({
|
|
13914
|
+
name: spec.name,
|
|
13915
|
+
workspaceId: spec.workspaceId,
|
|
13916
|
+
outcome: syncPassengerCheckout(spec.dir, spec.remote, spec.gitRemoteName, spec.base, { originUrl: spec.originUrl, scheme: spec.cloneScheme, host: spec.forgeHost })
|
|
13917
|
+
}));
|
|
13918
|
+
}
|
|
13919
|
+
|
|
13920
|
+
// src/sandbox-hooks.ts
|
|
13921
|
+
var imageHasBinary = (engine = "docker", exec = realExec) => (image, bin) => {
|
|
13831
13922
|
try {
|
|
13832
|
-
exec(engine, ["
|
|
13923
|
+
exec(engine, ["run", "--rm", "--entrypoint", "sh", image, "-c", `command -v ${bin}`], { timeoutMs: 6e4 });
|
|
13833
13924
|
return true;
|
|
13834
13925
|
} catch {
|
|
13835
13926
|
return false;
|
|
13836
13927
|
}
|
|
13837
13928
|
};
|
|
13838
|
-
|
|
13839
|
-
|
|
13840
|
-
|
|
13841
|
-
|
|
13842
|
-
|
|
13843
|
-
|
|
13844
|
-
var sandboxLogDir = (stateDir) => join32(stateDir, "sandbox-logs");
|
|
13845
|
-
async function buildSandboxImage(plan, deps) {
|
|
13846
|
-
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
13847
|
-
const state = readSandboxState(deps.stateDir);
|
|
13848
|
-
const entry = state[plan.repo] ?? { tags: [] };
|
|
13849
|
-
if (entry.tags[0]?.tag === plan.tag && deps.hasImage(plan.tag)) {
|
|
13850
|
-
return { kind: "reused", tag: plan.tag };
|
|
13851
|
-
}
|
|
13852
|
-
const logDir = sandboxLogDir(deps.stateDir);
|
|
13853
|
-
mkdirSync19(logDir, { recursive: true });
|
|
13854
|
-
const logPath = join32(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
|
|
13855
|
-
const builtLayers = [];
|
|
13856
|
-
for (const layer of plan.layers) {
|
|
13857
|
-
if (deps.hasImage(layer.tag)) continue;
|
|
13858
|
-
const ctx = join32(tmpdir3(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
|
|
13859
|
-
mkdirSync19(ctx, { recursive: true });
|
|
13860
|
-
try {
|
|
13861
|
-
writeFileSync20(join32(ctx, "Dockerfile"), layer.dockerfile);
|
|
13862
|
-
for (const [name, content] of Object.entries(layer.files)) {
|
|
13863
|
-
mkdirSync19(dirname15(join32(ctx, name)), { recursive: true });
|
|
13864
|
-
writeFileSync20(join32(ctx, name), content);
|
|
13865
|
-
}
|
|
13866
|
-
if (layer.caBundleFile) writeFileSync20(join32(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
|
|
13867
|
-
const code = await deps.run(["build", "--tag", layer.tag, "--file", join32(ctx, "Dockerfile"), ctx], logPath);
|
|
13868
|
-
if (code !== 0) {
|
|
13869
|
-
state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
|
|
13870
|
-
writeSandboxState(deps.stateDir, state);
|
|
13871
|
-
return { kind: "failed", tag: plan.tag, logPath, layer: layer.name };
|
|
13872
|
-
}
|
|
13873
|
-
builtLayers.push(layer.name);
|
|
13874
|
-
} finally {
|
|
13875
|
-
rmSync15(ctx, { recursive: true, force: true });
|
|
13876
|
-
}
|
|
13877
|
-
}
|
|
13878
|
-
const tags = [{ tag: plan.tag, builtAt: now().toISOString(), claude: plan.claude }, ...entry.tags.filter((t) => t.tag !== plan.tag)];
|
|
13879
|
-
const dropped = tags.slice(KEEP_TAGS);
|
|
13880
|
-
state[plan.repo] = { tags: tags.slice(0, KEEP_TAGS) };
|
|
13881
|
-
writeSandboxState(deps.stateDir, state);
|
|
13882
|
-
for (const t of dropped) deps.removeImage(t.tag);
|
|
13883
|
-
return { kind: "built", tag: plan.tag, builtLayers };
|
|
13884
|
-
}
|
|
13885
|
-
var sandboxFailedKey = (repo) => `sandbox_build_failed:${repo}`;
|
|
13886
|
-
function sandboxFailedItem(repo, tag, layer, logPath, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
13887
|
-
return {
|
|
13888
|
-
kind: "sandbox_build_failed",
|
|
13889
|
-
key: sandboxFailedKey(repo),
|
|
13890
|
-
since: nowIso,
|
|
13891
|
-
message: `${repo}: sandbox image ${tag} failed to build at the ${layer} layer (log: ${logPath}); sandboxes keep running the previous image. Retries automatically after the declaration changes or in an hour; \`crew sandbox build\` forces it`
|
|
13929
|
+
function sandboxHookGaps(o) {
|
|
13930
|
+
if (!o.image) return [];
|
|
13931
|
+
const seen = /* @__PURE__ */ new Map();
|
|
13932
|
+
const has = (bin) => {
|
|
13933
|
+
if (!seen.has(bin)) seen.set(bin, o.hasBinary(o.image, bin));
|
|
13934
|
+
return seen.get(bin);
|
|
13892
13935
|
};
|
|
13893
|
-
|
|
13894
|
-
|
|
13895
|
-
|
|
13896
|
-
|
|
13897
|
-
|
|
13898
|
-
const
|
|
13899
|
-
|
|
13900
|
-
|
|
13901
|
-
|
|
13902
|
-
|
|
13903
|
-
|
|
13904
|
-
|
|
13905
|
-
deps.log(`sandbox image for ${r.name}: building ${plan.tag}`);
|
|
13906
|
-
const out = await buildSandboxImage(plan, deps);
|
|
13907
|
-
if (out.kind === "failed") {
|
|
13908
|
-
deps.raise(sandboxFailedItem(r.name, out.tag, out.layer, out.logPath));
|
|
13909
|
-
deps.log(`sandbox image for ${r.name}: build failed at the ${out.layer} layer, log ${out.logPath}`);
|
|
13910
|
-
} else {
|
|
13911
|
-
deps.clear(sandboxFailedKey(r.name));
|
|
13912
|
-
deps.log(`sandbox image for ${r.name}: ${out.kind === "built" ? `built ${out.tag}` : `${out.tag} already built`}`);
|
|
13913
|
-
}
|
|
13914
|
-
return r.name;
|
|
13936
|
+
const gaps = [];
|
|
13937
|
+
for (const hook2 of ["setup", "test", "build", "deploy"]) {
|
|
13938
|
+
const script = o.hooks[hook2];
|
|
13939
|
+
const command2 = script ? hookCommand(script) : null;
|
|
13940
|
+
if (!command2 || has(command2)) continue;
|
|
13941
|
+
const remedy = o.declares ? `add the package that provides \`${command2}\` to sandbox.packages or sandbox.setup in ${o.repo}'s .crew.yaml, then \`crew sandbox build ${o.repo}\`` : `${o.repo} declares no sandbox: section, so it runs in the ship's crew image; add a sandbox: section to its .crew.yaml providing \`${command2}\``;
|
|
13942
|
+
gaps.push({
|
|
13943
|
+
hook: hook2,
|
|
13944
|
+
command: command2,
|
|
13945
|
+
remedy,
|
|
13946
|
+
message: `${o.route}/${o.repo}: the ${hook2} hook runs \`${command2}\`, which is not in its sandbox image ${o.image} \u2014 ${remedy}`
|
|
13947
|
+
});
|
|
13915
13948
|
}
|
|
13916
|
-
return
|
|
13949
|
+
return gaps;
|
|
13917
13950
|
}
|
|
13918
13951
|
|
|
13919
13952
|
// src/doctor-checks.ts
|
|
@@ -31318,6 +31351,15 @@ watermark: ${state.watermark()}
|
|
|
31318
31351
|
base: doctorBaseReport(r, r.config.branch.base, baseHealth),
|
|
31319
31352
|
hooks: r.config.hooks,
|
|
31320
31353
|
onPath: (cmd) => !!findOnPath(cmd, doctorSchedulerPath),
|
|
31354
|
+
// CREW-3007: on a sandbox ship the hooks run in the image, so the host PATH is not asked.
|
|
31355
|
+
sandboxGaps: cfg.ship.runner === "sandbox" ? sandboxHookGaps({
|
|
31356
|
+
route: c.route,
|
|
31357
|
+
repo: r.name,
|
|
31358
|
+
hooks: r.config.hooks,
|
|
31359
|
+
declares: Boolean(r.config.sandbox),
|
|
31360
|
+
image: sandboxImageForRun(readSandboxState(cfg.ship.stateDir), r.name, Boolean(r.config.sandbox)),
|
|
31361
|
+
hasBinary: imageHasBinary()
|
|
31362
|
+
}) : void 0,
|
|
31321
31363
|
mapFile: mapFilePath(r.config.hooks.map) ? inspectMapFile(r.dir, mapFilePath(r.config.hooks.map)) : void 0,
|
|
31322
31364
|
intelSyntax: r.config.hooks.intel && !intelFlavor(r.config.hooks.intel) ? checkHookSyntax(r.config.hooks.intel, r.config.shell) : void 0,
|
|
31323
31365
|
intelFlavor: intelFlavor(r.config.hooks.intel) ? { name: intelFlavor(r.config.hooks.intel), missing: [
|
|
@@ -31793,11 +31835,30 @@ crew manifest: ${seats2.length ? seats2.map((c) => c.name).join(", ") : "non
|
|
|
31793
31835
|
continue;
|
|
31794
31836
|
}
|
|
31795
31837
|
for (const r of repos) {
|
|
31838
|
+
const gaps = cfg.ship.runner === "sandbox" ? sandboxHookGaps({
|
|
31839
|
+
route: c.route,
|
|
31840
|
+
repo: r.name,
|
|
31841
|
+
hooks: r.config.hooks,
|
|
31842
|
+
declares: Boolean(r.config.sandbox),
|
|
31843
|
+
image: sandboxImageForRun(readSandboxState(cfg.ship.stateDir), r.name, Boolean(r.config.sandbox)),
|
|
31844
|
+
hasBinary: imageHasBinary()
|
|
31845
|
+
}) : [];
|
|
31796
31846
|
for (const name of ["setup", "test", "build", "deploy"]) {
|
|
31797
31847
|
const script = r.config.hooks[name];
|
|
31798
31848
|
const cmd = script ? hookCommand(script) : null;
|
|
31799
31849
|
if (!cmd) continue;
|
|
31800
31850
|
const key = `hook_missing:${c.route}/${r.name}/${name}`;
|
|
31851
|
+
if (cfg.ship.runner === "sandbox") {
|
|
31852
|
+
const gap = gaps.find((g) => g.hook === name);
|
|
31853
|
+
if (!gap) {
|
|
31854
|
+
clearShipAttention(state, key);
|
|
31855
|
+
continue;
|
|
31856
|
+
}
|
|
31857
|
+
process.stdout.write(`hook ${c.route}/${r.name} ${name}: \`${cmd}\` NOT FOUND in the sandbox image
|
|
31858
|
+
`);
|
|
31859
|
+
await raiseShipAttention({ state, emit, route: c, ship: cfg.ship }, { kind: "hook_missing", key, message: gap.message, since: (/* @__PURE__ */ new Date()).toISOString() });
|
|
31860
|
+
continue;
|
|
31861
|
+
}
|
|
31801
31862
|
if (findOnPath(cmd, schedulerPath)) {
|
|
31802
31863
|
clearShipAttention(state, key);
|
|
31803
31864
|
continue;
|