code60-transmission-server 0.0.0-stage → 0.1.0-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +291 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +104 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,177 @@
1
+ import { filesystemToolDefinitions } from "../broker/filesystem.js";
2
+ import { canonical, digest, jsonCopy } from "../broker/policy.js";
3
+ import { BrokerError } from "../broker/types.js";
4
+ import { WorkspaceService } from "../workspaces/index.js";
5
+ import { HttpTool, HTTP_TOOL_CONFIGURATION_SCHEMA } from "./http.js";
6
+ export * from "./checks.js";
7
+ export * from "./worker-check.js";
8
+ export * from "./http.js";
9
+ export * from "./http-contract.js";
10
+ export const FILE_TOOL_CONFIGURATION_SCHEMA = { type: "object", properties: {
11
+ root: { enum: ["workspace", "scratch", "deployment"] }, rootId: { type: "string", minLength: 1, maxLength: 200 },
12
+ scratchIndex: { type: "integer", minimum: 0, maximum: 63 },
13
+ }, additionalProperties: false, allOf: [
14
+ { if: { properties: { root: { const: "deployment" } }, required: ["root"] }, then: { required: ["rootId"] },
15
+ else: { not: { required: ["rootId"] } } },
16
+ ] };
17
+ const contextScope = (context) => ({ workspaceId: context.workspaceId, leaseId: context.leaseId,
18
+ instructionSnapshotId: context.instructionSnapshotId, workspaceRevisionId: context.workspaceRevisionId ?? null });
19
+ /** Server-private context selects all FDs and credentials. Model root labels are
20
+ * selectors among already assigned capabilities, never authority or host paths. */
21
+ export class ToolFactory {
22
+ options;
23
+ http;
24
+ constructor(options) {
25
+ this.options = options;
26
+ const provider = options.http?.credentials;
27
+ if (provider?.resolve.constructor.name === "AsyncFunction" || provider?.describe.constructor.name === "AsyncFunction") {
28
+ throw new BrokerError("async_credential_provider_unsupported", 422);
29
+ }
30
+ this.http = new HttpTool({ ...options.http, validateBinding: binding => {
31
+ const context = this.context(binding);
32
+ this.options.http?.validateBinding?.(binding);
33
+ this.configuration(context, "http_request");
34
+ }, ...(provider === undefined ? {} : { credentials: {
35
+ describe: (binding, origin) => {
36
+ const context = this.context(binding), reference = this.configuration(context, "http_request").credentialRefs?.authorization;
37
+ if (!reference)
38
+ return undefined;
39
+ const descriptor = provider.describe(binding, origin);
40
+ if (!descriptor || descriptor.referenceId !== reference)
41
+ throw new BrokerError("unauthorized_credential_reference", 422);
42
+ return descriptor;
43
+ },
44
+ resolve: (binding, credential) => provider.resolve(binding, credential),
45
+ } }) });
46
+ }
47
+ context(binding, expected) {
48
+ const context = this.options.resolveContext(binding);
49
+ for (const key of ["runId", "stepExecutionId", "sessionId", "epoch", "profileVersionId", "role"]) {
50
+ if (context.binding[key] !== binding[key])
51
+ throw new BrokerError("stale_tool_context");
52
+ }
53
+ if (expected && canonical(contextScope(context)) !== canonical(contextScope(expected)))
54
+ throw new BrokerError("stale_tool_context");
55
+ if (!context.instructionSnapshotId)
56
+ throw new BrokerError("instruction_snapshot_required");
57
+ this.options.workspaces.assertContext(context);
58
+ return { ...context, binding: Object.freeze(jsonCopy(binding)) };
59
+ }
60
+ configuration(context, name) {
61
+ const tool = this.options.resolveConfiguration?.(context, name) ?? { configuration: {} };
62
+ const value = tool.configuration;
63
+ if (!value || typeof value !== "object" || Array.isArray(value))
64
+ throw new BrokerError("invalid_tool_configuration", 422);
65
+ const configuration = value;
66
+ const refs = tool.credentialRefs ?? {};
67
+ if (name === "http_request") {
68
+ if (Object.keys(configuration).length || Object.keys(refs).some(slot => slot !== "authorization") ||
69
+ (refs.authorization !== undefined && (!refs.authorization || !this.options.http?.credentials)))
70
+ throw new BrokerError("unsupported_tool_configuration", 422);
71
+ }
72
+ else {
73
+ if (Object.keys(refs).length || Object.keys(configuration).some(key => !["root", "rootId", "scratchIndex"].includes(key)) ||
74
+ (configuration.root !== undefined && !["workspace", "scratch", "deployment"].includes(String(configuration.root))) ||
75
+ (configuration.scratchIndex !== undefined && (!Number.isInteger(configuration.scratchIndex) ||
76
+ Number(configuration.scratchIndex) < 0 || Number(configuration.scratchIndex) > 63)) ||
77
+ (configuration.root === "deployment" ? typeof configuration.rootId !== "string" || !configuration.rootId ||
78
+ !this.options.workspaces.deploymentRootIds().includes(configuration.rootId) : configuration.rootId !== undefined)) {
79
+ throw new BrokerError("unsupported_tool_configuration", 422);
80
+ }
81
+ }
82
+ return jsonCopy(tool);
83
+ }
84
+ toolConfigurations() {
85
+ return [...filesystemToolDefinitions().keys()].map(toolId => ({ toolId, configurationSchema: jsonCopy(FILE_TOOL_CONFIGURATION_SCHEMA), credentialSlots: [] }))
86
+ .concat([{ toolId: this.http.name, configurationSchema: jsonCopy(HTTP_TOOL_CONFIGURATION_SCHEMA),
87
+ credentialSlots: this.options.http?.credentials ? ["authorization"] : [] }]);
88
+ }
89
+ /** Pure registry for the global broker, available before a session exists. */
90
+ registry() { return this.create(); }
91
+ catalog(context) {
92
+ this.options.coordinator.assertOutsideTransaction();
93
+ this.context(context.binding, context);
94
+ for (const name of context.binding.configuredTools) {
95
+ if (!this.create().has(name))
96
+ throw new BrokerError("unsupported_tool", 422);
97
+ this.configuration(context, name);
98
+ }
99
+ return new Map([...this.create(context)].filter(([name]) => context.binding.configuredTools.includes(name)));
100
+ }
101
+ create(expected) {
102
+ const tools = new Map();
103
+ for (const [name, metadata] of filesystemToolDefinitions()) {
104
+ const schema = metadata.inputSchema, properties = schema.properties;
105
+ tools.set(name, { ...metadata, inputSchema: { ...schema, properties: { ...properties, root: { enum: ["workspace", "scratch", "deployment"] } } },
106
+ prepare: (input, binding) => {
107
+ this.options.coordinator.assertOutsideTransaction();
108
+ if (!binding || !input || typeof input !== "object" || Array.isArray(input))
109
+ throw new BrokerError("invalid_tool_arguments", 400);
110
+ const context = this.context(binding, expected), config = this.configuration(context, name).configuration;
111
+ if (!binding.configuredTools.includes(name))
112
+ throw new BrokerError("unsupported_tool", 422);
113
+ const kind = input.root ?? config.root ?? "workspace";
114
+ if (!["workspace", "scratch", "deployment"].includes(String(kind)) || (config.root !== undefined && kind !== config.root) ||
115
+ (kind === "deployment" && config.root !== "deployment"))
116
+ throw new BrokerError("unassigned_tool_root", 403);
117
+ const files = kind === "deployment" ? this.options.workspaces.toolDeploymentRoot(context, String(config.rootId)) :
118
+ this.options.workspaces.toolRoot(context, kind, Number(config.scratchIndex ?? 0));
119
+ try {
120
+ const { root: _root, ...arguments_ } = jsonCopy(input), tool = files.catalog().get(name);
121
+ if (!tool)
122
+ throw new BrokerError("unsupported_tool", 422);
123
+ const prepared = tool.prepare(arguments_, binding);
124
+ if (prepared && "then" in prepared)
125
+ throw new BrokerError("async_native_prepare", 500);
126
+ const mutation = name === "write_file" ? { kind: "write", path: String(arguments_.path), content: Buffer.from(String(arguments_.content)) } :
127
+ name === "delete_file" ? { kind: "delete", path: String(arguments_.path) } :
128
+ name === "move_file" ? { kind: "move", path: String(arguments_.path), destination: String(arguments_.destination) } : undefined;
129
+ return this.wrap(prepared, binding, context, () => files.close(), kind === "workspace" ? mutation : undefined);
130
+ }
131
+ catch (error) {
132
+ files.close();
133
+ throw error;
134
+ }
135
+ } });
136
+ }
137
+ tools.set(this.http.name, { name: this.http.name, description: this.http.description, inputSchema: this.http.inputSchema,
138
+ prepare: (input, binding) => {
139
+ this.options.coordinator.assertOutsideTransaction();
140
+ if (!binding)
141
+ throw new BrokerError("missing_trusted_binding");
142
+ const context = this.context(binding, expected);
143
+ this.configuration(context, this.http.name);
144
+ return this.wrap(this.http.prepare(input, binding), binding, context);
145
+ } });
146
+ return tools;
147
+ }
148
+ wrap(prepared, binding, context, close, mutation) {
149
+ let disposed = false, used = false;
150
+ const resources = (actual) => actual.map(resource => ({ ...resource,
151
+ identityDigest: digest({ resourceIdentity: resource.identityDigest, context: contextScope(context) }) }));
152
+ const validate = () => {
153
+ if (disposed)
154
+ throw new BrokerError("tool_effect_disposed");
155
+ this.context(binding, context);
156
+ };
157
+ return { resources: resources(prepared.resources), revalidate: () => { validate(); return resources(prepared.revalidate()); },
158
+ execute: dispatchId => {
159
+ this.options.coordinator.assertOutsideTransaction();
160
+ validate();
161
+ if (used)
162
+ throw new BrokerError("tool_effect_reused");
163
+ used = true;
164
+ return mutation ? this.options.workspaces.applyMutation(context, mutation, () => prepared.execute(dispatchId)) : prepared.execute(dispatchId);
165
+ },
166
+ dispose: () => { if (!disposed) {
167
+ disposed = true;
168
+ try {
169
+ prepared.dispose?.();
170
+ }
171
+ finally {
172
+ close?.();
173
+ }
174
+ } },
175
+ };
176
+ }
177
+ }
@@ -0,0 +1,73 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { canonical, jsonCopy } from "../broker/policy.js";
3
+ import { CheckRegistryError } from "./checks.js";
4
+ /** Only deployment registrations select fixed predicates. No workflow/model
5
+ * command, inline function, arbitrary script/module path or shell is accepted.
6
+ * Actual predicate execution and Ajv compilation are OFF the coordinator.
7
+ * This promise settles only AFTER the Worker physically exits. */
8
+ export function createPureArtifactCheck(definition, options) {
9
+ const spec = jsonCopy(definition), predicate = spec.predicate;
10
+ if ([spec.id, spec.description, spec.version].some(value => typeof value !== "string" || !value || value.length > 4096) ||
11
+ Object.keys(spec).some(key => !["id", "description", "version", "predicate"].includes(key)) ||
12
+ Object.keys(predicate).some(key => !(predicate.kind === "text_includes" ? ["kind", "needle"] :
13
+ predicate.kind === "json_pointer_equals" ? ["kind", "pointer", "expected"] : ["kind", "schema"]).includes(key)) ||
14
+ canonical(predicate).length > 65536 ||
15
+ (predicate.kind === "text_includes" ? typeof predicate.needle !== "string" || !predicate.needle || predicate.needle.length > 4096 :
16
+ predicate.kind === "json_pointer_equals" ? typeof predicate.pointer !== "string" || !/^(?:|\/(?:[^~]|~[01])*)$/.test(predicate.pointer) :
17
+ predicate.kind === "json_schema" ? !(typeof predicate.schema === "boolean" ||
18
+ !!predicate.schema && typeof predicate.schema === "object" && !Array.isArray(predicate.schema)) : true)) {
19
+ throw new CheckRegistryError("invalid_pure_check_registration");
20
+ }
21
+ return Object.freeze({ id: spec.id, description: spec.description, version: spec.version,
22
+ execute: (request, signal) => {
23
+ options.coordinator.assertOutsideTransaction();
24
+ if (signal.aborted || request.deadlineAt <= Date.now())
25
+ return Promise.resolve({ status: "infrastructure_error", code: "check_aborted",
26
+ retryable: true, explanation: "Registered check was cancelled before execution." });
27
+ return new Promise(resolve => {
28
+ const entry = new URL(import.meta.url.endsWith(".ts") ? "./check-worker.ts" : "./check-worker.js", import.meta.url);
29
+ const worker = new Worker(entry, { workerData: { artifact: request.artifact, predicate }, execArgv: [],
30
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, resourceLimits: { maxOldGenerationSizeMb: 64, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 } });
31
+ let result, aborted = false, timer;
32
+ const abort = () => { aborted = true; void worker.terminate().catch(() => { }); };
33
+ const arm = () => {
34
+ const remaining = request.deadlineAt - Date.now();
35
+ if (remaining <= 0)
36
+ abort();
37
+ else {
38
+ timer = setTimeout(arm, Math.min(2_147_483_647, Math.ceil(remaining)));
39
+ timer.unref();
40
+ }
41
+ };
42
+ worker.on("message", (value) => {
43
+ if ("event" in value) {
44
+ try {
45
+ options.onWorkerReady?.();
46
+ }
47
+ catch {
48
+ abort();
49
+ }
50
+ }
51
+ else
52
+ result = value;
53
+ });
54
+ worker.on("error", () => {
55
+ result = { status: "infrastructure_error", code: "check_worker_error", retryable: true,
56
+ explanation: "Registered pure check worker failed." };
57
+ });
58
+ worker.on("exit", code => {
59
+ if (timer)
60
+ clearTimeout(timer);
61
+ signal.removeEventListener("abort", abort);
62
+ resolve(aborted ? { status: "infrastructure_error", code: "check_worker_aborted", retryable: true,
63
+ explanation: "Registered pure check worker was cancelled or exceeded its deadline." } :
64
+ code === 0 && result ? result : { status: "infrastructure_error", code: "check_worker_failed", retryable: true,
65
+ explanation: "Registered pure check did not produce a completed result." });
66
+ });
67
+ signal.addEventListener("abort", abort, { once: true });
68
+ arm();
69
+ if (signal.aborted)
70
+ abort();
71
+ });
72
+ } });
73
+ }
@@ -0,0 +1,227 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { fstatSync, lstatSync } from "node:fs";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { startupLockIdentity } from "../broker/startup-lock.js";
6
+ export class WorkspaceError extends Error {
7
+ code;
8
+ status;
9
+ detail;
10
+ constructor(code, status = 409, detail) {
11
+ super(code);
12
+ this.code = code;
13
+ this.status = status;
14
+ this.detail = detail;
15
+ }
16
+ }
17
+ const DENIED_REASONS = {
18
+ missing_git_dir: {
19
+ code: "git_directory_missing",
20
+ status: 422,
21
+ detail: "Repository path does not contain a standalone .git directory.",
22
+ },
23
+ unsupported_worktree: {
24
+ code: "git_unsupported_worktree",
25
+ status: 422,
26
+ detail: "Repository .git must be a real directory, not a symlink or linked git worktree file.",
27
+ },
28
+ unsafe_permissions: {
29
+ code: "git_unsafe_permissions",
30
+ status: 422,
31
+ detail: "Repository and .git contents must be owned by the current user and not group- or world-writable.",
32
+ },
33
+ hardlink: {
34
+ code: "git_hardlinked_file",
35
+ status: 422,
36
+ detail: "Repository .git contains hardlinked files (st_nlink > 1), such as leftover tmp_obj_* files from a no-delete sandbox or a local hardlinked git clone. Remove leftover tmp_obj_* files or clone with --no-hardlinks.",
37
+ },
38
+ unsupported_file_type: {
39
+ code: "git_unsupported_file_type",
40
+ status: 422,
41
+ detail: "Repository .git contains a symlink or non-regular file.",
42
+ },
43
+ too_complex: {
44
+ code: "git_repository_too_complex",
45
+ status: 422,
46
+ detail: "Repository .git directory exceeds maximum depth or entry count limits.",
47
+ },
48
+ lock_file: {
49
+ code: "git_lock_file_present",
50
+ status: 409,
51
+ detail: "Repository .git contains a lock file (index.lock, HEAD.lock, or packed-refs.lock). Wait for other Git commands to finish or remove stale lock files.",
52
+ },
53
+ operation_in_progress: {
54
+ code: "git_operation_in_progress",
55
+ status: 409,
56
+ detail: "Repository has an unfinished Git merge, rebase, cherry-pick, revert, or bisect in progress.",
57
+ },
58
+ unsupported_feature: {
59
+ code: "git_unsupported_repository_feature",
60
+ status: 422,
61
+ detail: "Repository uses an unsupported Git feature (such as linked worktrees, shallow clone, alternates, grafts, replace refs, or sparse-checkout).",
62
+ },
63
+ };
64
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
65
+ const quote = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
66
+ const ancestors = (path) => path === dirname(path) ? [path] : [path, ...ancestors(dirname(path))];
67
+ /** Fixed local bare-plumbing interface. No working-tree checkout/add/filter,
68
+ * shell, network, credential helper, hook, signing or repository command. */
69
+ export class WorkspaceGit {
70
+ options;
71
+ identity;
72
+ environment;
73
+ profile;
74
+ lockIdentity;
75
+ constructor(options) {
76
+ this.options = options;
77
+ this.lockIdentity = options.startupLockFd === undefined ? undefined : startupLockIdentity(options.startupLockFd);
78
+ if (!isAbsolute(options.helperPath))
79
+ throw new WorkspaceError("untrusted_git_helper", 422);
80
+ const executable = lstatSync(options.helperPath);
81
+ if (!executable.isFile() || executable.isSymbolicLink() || executable.uid !== process.geteuid?.() ||
82
+ executable.nlink !== 1 || (executable.mode & 0o6022))
83
+ throw new WorkspaceError("untrusted_git_helper", 422);
84
+ const root = fstatSync(options.rootFd);
85
+ if (!root.isDirectory())
86
+ throw new WorkspaceError("workspace_identity_changed");
87
+ this.environment = { PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC", GIT_TERMINAL_PROMPT: "0",
88
+ GIT_CONFIG_NOSYSTEM: "1", GIT_OPTIONAL_LOCKS: "0", GIT_ALLOW_PROTOCOL: "" };
89
+ // Preserve configured identity unchanged. Never supply invented user.*, -c
90
+ // identity, or changed GIT_AUTHOR/COMMITTER identity environment variables.
91
+ for (const name of ["HOME", "XDG_CONFIG_HOME", "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL"]) {
92
+ if (process.env[name] !== undefined)
93
+ this.environment[name] = process.env[name];
94
+ }
95
+ const probed = this.raw("probe", [], undefined, false).toString("utf8").trim();
96
+ if (!/^\d+:\d+$/.test(probed) || (options.expectedIdentity !== undefined && probed !== options.expectedIdentity)) {
97
+ throw new WorkspaceError("workspace_git_identity_changed");
98
+ }
99
+ this.identity = probed;
100
+ const git = join(options.repositoryPath, ".git");
101
+ const globalConfigs = this.environment.HOME ? [join(this.environment.HOME, ".gitconfig"),
102
+ join(this.environment.XDG_CONFIG_HOME ?? join(this.environment.HOME, ".config"), "git", "config")] : [];
103
+ const metadata = [...new Set([...ancestors(options.repositoryPath), ...globalConfigs.flatMap(ancestors),
104
+ ...ancestors(options.helperPath), "/etc", "/private/etc", "/private/var", "/dev"])];
105
+ this.profile = `(version 1)
106
+ (deny default)
107
+ (allow process-fork)
108
+ (allow process-info* (target same-sandbox))
109
+ (allow signal (target same-sandbox))
110
+ (allow sysctl-read)
111
+ (allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))
112
+ (allow file-read-metadata file-test-existence ${metadata.map(path => `(literal ${quote(path)})`).join(" ")})
113
+ (allow file-read* file-test-existence (literal "/") (subpath "/usr") (subpath "/bin")
114
+ (subpath "/System")
115
+ (subpath "/Library/Developer/CommandLineTools") (subpath "/private/var/db/dyld")
116
+ (literal "/dev/null") (literal "/dev/urandom") (literal "/dev/random")
117
+ (literal ${quote(options.repositoryPath)}) (subpath ${quote(git)})
118
+ (literal ${quote(options.helperPath)}) ${globalConfigs.map(path => `(literal ${quote(path)})`).join(" ")})
119
+ (allow file-write* (subpath ${quote(git)}) (literal "/dev/null"))
120
+ (allow process-exec (literal ${quote(options.helperPath)})
121
+ (literal "/Library/Developer/CommandLineTools/usr/bin/git"))
122
+ `;
123
+ this.validateConfiguration();
124
+ }
125
+ raw(verb, args = [], input, contained = true) {
126
+ if (this.options.startupLockFd !== undefined && startupLockIdentity(this.options.startupLockFd) !== this.lockIdentity) {
127
+ throw new WorkspaceError("startup_lock_changed");
128
+ }
129
+ const argv = [verb, ...(verb === "probe" ? [] : [this.identity]), ...args];
130
+ const result = spawnSync(contained ? "/usr/bin/sandbox-exec" : this.options.helperPath, contained ? ["-p", this.profile, this.options.helperPath, ...argv] : argv, {
131
+ input, stdio: ["pipe", "pipe", "pipe", this.options.rootFd,
132
+ ...(this.options.startupLockFd === undefined ? [] : [this.options.startupLockFd])], env: this.environment,
133
+ cwd: this.options.repositoryPath, timeout: 5000, maxBuffer: 16 * 1_048_576,
134
+ });
135
+ if (result.error || result.status !== 0 || result.signal) {
136
+ if (result.status === 74 && result.stderr) {
137
+ const match = /^git_helper_denied:([a-z_]+)$/.exec(result.stderr.toString("utf8").trim());
138
+ const reason = match?.[1];
139
+ if (reason && Object.hasOwn(DENIED_REASONS, reason)) {
140
+ const mapped = DENIED_REASONS[reason];
141
+ throw new WorkspaceError(mapped.code, mapped.status, mapped.detail);
142
+ }
143
+ }
144
+ if (verb === "identity" || verb === "committer") {
145
+ throw new WorkspaceError("git_identity_unconfigured", 409, "Git author/committer identity is not configured for this user.");
146
+ }
147
+ if (verb === "head" && result.status === 128) {
148
+ throw new WorkspaceError("git_head_unborn", 422, "Repository HEAD does not point to a commit yet. Create at least one commit before registering the workspace.");
149
+ }
150
+ throw new WorkspaceError("git_operation_failed");
151
+ }
152
+ return result.stdout;
153
+ }
154
+ validateConfiguration() {
155
+ const config = this.raw("config", [], undefined, false).toString("utf8");
156
+ if (/^\s*\[\s*(?:include|includeif|filter|extensions)\b/im.test(config) ||
157
+ /^\s*(?:worktree|gitproxy|sshcommand)\s*=/im.test(config) ||
158
+ config.split("\n").some(line => {
159
+ const match = /^\s*(?:bare|sharedrepository|fsmonitor)\s*=\s*(.*)$/i.exec(line);
160
+ return match && !/^(?:false|0|no|off)$/i.test(match[1].trim());
161
+ })) {
162
+ throw new WorkspaceError("unsupported_git_configuration", 422);
163
+ }
164
+ return hash(config);
165
+ }
166
+ head() { return this.object(this.raw("head").toString("ascii").trim()); }
167
+ branch() {
168
+ const ref = this.raw("branch").toString("utf8").trim();
169
+ if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9/_.-]*$/.test(ref) || ref.includes(".."))
170
+ throw new WorkspaceError("unsupported_git_head", 422);
171
+ return ref;
172
+ }
173
+ assertIdentity() { this.raw("identity"); this.raw("committer"); }
174
+ index() {
175
+ const result = this.raw("index", [], undefined, false), newline = result.indexOf(10);
176
+ if (newline < 0)
177
+ throw new WorkspaceError("git_index_unavailable");
178
+ return { identity: result.subarray(0, newline).toString("ascii"), bytes: result.subarray(newline + 1),
179
+ contentDigest: hash(result.subarray(newline + 1)) };
180
+ }
181
+ tree(commit) {
182
+ const entries = this.raw("ls-tree", [this.object(commit)]).toString("utf8").split("\0").filter(Boolean);
183
+ return entries.map(entry => {
184
+ const match = /^(100644|100755) blob ([a-f0-9]{40})\t([\s\S]+)$/.exec(entry);
185
+ if (!match)
186
+ throw new WorkspaceError("unsupported_git_tree", 422);
187
+ return { path: match[3], object: match[2], mode: Number.parseInt(match[1], 8) };
188
+ });
189
+ }
190
+ indexEntries() { return this.raw("index-tree").toString("utf8").split("\0").filter(Boolean); }
191
+ blob(bytes) { return this.object(this.raw("hash", [], bytes).toString("ascii").trim()); }
192
+ makeTree(files) {
193
+ const root = { files: [], directories: new Map() };
194
+ for (const file of files) {
195
+ const parts = file.path.split("/");
196
+ let tree = root;
197
+ for (const part of parts.slice(0, -1)) {
198
+ if (!tree.directories.has(part))
199
+ tree.directories.set(part, { files: [], directories: new Map() });
200
+ tree = tree.directories.get(part);
201
+ }
202
+ tree.files.push({ name: parts.at(-1), object: this.blob(file.bytes), mode: file.mode & 0o100 ? 0o100755 : 0o100644 });
203
+ }
204
+ const write = (tree) => {
205
+ const records = [...tree.files.map(file => ({ name: file.name, data: `${file.mode.toString(8)} blob ${file.object}\t${file.name}\0` })),
206
+ ...[...tree.directories].map(([name, child]) => ({ name: `${name}/`, data: `040000 tree ${write(child)}\t${name}\0` }))];
207
+ records.sort((a, b) => Buffer.compare(Buffer.from(a.name), Buffer.from(b.name)));
208
+ return this.object(this.raw("tree", [], Buffer.from(records.map(record => record.data).join(""))).toString("ascii").trim());
209
+ };
210
+ return write(root);
211
+ }
212
+ commit(tree, parent, message) {
213
+ this.assertIdentity();
214
+ return this.object(this.raw("commit", [this.object(tree), this.object(parent)], Buffer.from(message)).toString("ascii").trim());
215
+ }
216
+ updateRef(ref, next, expected) { this.raw("ref", [ref, this.object(next), this.object(expected)]); }
217
+ installIndex(commit, expectedIdentity) {
218
+ const token = randomUUID();
219
+ this.raw("read-tree", [this.object(commit), token]);
220
+ this.raw("install-index", [token, expectedIdentity]);
221
+ }
222
+ object(value) {
223
+ if (!/^[a-f0-9]{40}$/.test(value))
224
+ throw new WorkspaceError("unsupported_git_object_format", 422);
225
+ return value;
226
+ }
227
+ }