code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.18

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 (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +54 -340
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +103 -0
  5. package/dist/src/engine.js +506 -0
  6. package/dist/src/main.js +72 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +728 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -1,205 +0,0 @@
1
- #define _DARWIN_C_SOURCE
2
- #define _POSIX_C_SOURCE 200809L
3
- #include <sys/types.h>
4
- #include <sys/stat.h>
5
- #include <sys/file.h>
6
- #include <dirent.h>
7
- #include <errno.h>
8
- #include <fcntl.h>
9
- #include <inttypes.h>
10
- #include <stdio.h>
11
- #include <stdlib.h>
12
- #include <string.h>
13
- #include <unistd.h>
14
-
15
- /* Trusted engine plumbing only, never an agent tool. fd3 is a pinned workspace.
16
- * No arbitrary executable, Git subcommand, option, path, environment or shell.
17
- * Effects additionally run under the Git driver's deny-default Seatbelt policy. */
18
- static void die(void) { fputs("git_helper_denied\n", stderr); exit(74); }
19
- static void die_reason(const char *reason) {
20
- fputs("git_helper_denied:", stderr);
21
- fputs(reason, stderr);
22
- fputc('\n', stderr);
23
- exit(74);
24
- }
25
- static int directory(int fd) {
26
- struct stat s;
27
- return fstat(fd, &s) == 0 && S_ISDIR(s.st_mode) && s.st_uid == geteuid() && !(s.st_mode & 022);
28
- }
29
- static int regular(const struct stat *s) {
30
- return S_ISREG(s->st_mode) && s->st_uid == geteuid() && s->st_nlink == 1 && !(s->st_mode & 022);
31
- }
32
- static int hex(const char *s) {
33
- if (strlen(s) != 40) return 0;
34
- for (; *s; s++) if (!((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'f'))) return 0;
35
- return 1;
36
- }
37
- static int token(const char *s) {
38
- if (strlen(s) != 36) return 0;
39
- for (; *s; s++) if (!((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'f') || *s == '-')) return 0;
40
- return 1;
41
- }
42
- static int ref(const char *s) {
43
- if (strncmp(s, "refs/heads/", 11) && strncmp(s, "refs/code60/", 12)) return 0;
44
- if (strlen(s) > 512 || strstr(s, "..") || strstr(s, "//") || strstr(s, "@{") || s[strlen(s)-1] == '/') return 0;
45
- for (; *s; s++) if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
46
- (*s >= '0' && *s <= '9') || strchr("/-_.", *s))) return 0;
47
- return 1;
48
- }
49
- static unsigned entries;
50
- static void inspect(int fd, unsigned depth) {
51
- if (depth > 64) die_reason("too_complex");
52
- if (!directory(fd)) die_reason("unsafe_permissions");
53
- int copy = openat(fd, ".", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
54
- if (copy < 0) die();
55
- DIR *dir = fdopendir(copy); if (!dir) die();
56
- struct dirent *entry;
57
- while ((entry = readdir(dir))) {
58
- if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
59
- if (++entries > 100000) die_reason("too_complex");
60
- struct stat s;
61
- if (fstatat(fd, entry->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) die();
62
- if (S_ISDIR(s.st_mode)) {
63
- int child = openat(fd, entry->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
64
- if (child < 0) die();
65
- inspect(child, depth + 1); close(child);
66
- } else if (!regular(&s)) {
67
- if (!S_ISREG(s.st_mode)) die_reason("unsupported_file_type");
68
- if (s.st_nlink != 1) die_reason("hardlink");
69
- die_reason("unsafe_permissions");
70
- }
71
- }
72
- closedir(dir);
73
- }
74
- static void identity(char *out, size_t capacity, const struct stat *s) {
75
- int n = snprintf(out, capacity, "%ju:%ju:%ju:%jd:%jd:%ld:%jd:%ld",
76
- (uintmax_t)s->st_dev, (uintmax_t)s->st_ino, (uintmax_t)s->st_mode, (intmax_t)s->st_size,
77
- (intmax_t)s->st_mtimespec.tv_sec, s->st_mtimespec.tv_nsec, (intmax_t)s->st_ctimespec.tv_sec, s->st_ctimespec.tv_nsec);
78
- if (n < 0 || (size_t)n >= capacity) die();
79
- }
80
- static void read_file(int git, const char *name, int index) {
81
- int fd = openat(git, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
82
- if (fd < 0) { if (index && errno == ENOENT) { puts("absent"); return; } die(); }
83
- struct stat s;
84
- if (fstat(fd, &s) < 0 || !regular(&s) || s.st_size < 0 || s.st_size > (index ? 16777216 : 65536)) die();
85
- if (index) { char id[256]; identity(id, sizeof(id), &s); puts(id); fflush(stdout); }
86
- char buffer[8192]; ssize_t n;
87
- while ((n = read(fd, buffer, sizeof(buffer))) > 0) if (write(STDOUT_FILENO, buffer, (size_t)n) != n) die();
88
- if (n < 0) die();
89
- struct stat after; char before_id[256], after_id[256];
90
- if (fstat(fd, &after) < 0) die();
91
- identity(before_id, sizeof(before_id), &s); identity(after_id, sizeof(after_id), &after);
92
- if (strcmp(before_id, after_id)) die();
93
- close(fd);
94
- }
95
- static void install_index(int git, const char *id, const char *expected) {
96
- if (!token(id)) die();
97
- char candidate[80], backup[80], actual[256];
98
- snprintf(candidate, sizeof(candidate), ".code60-index-%s", id);
99
- snprintf(backup, sizeof(backup), ".code60-index-backup-%s", id);
100
- struct stat next, before, captured;
101
- if (fstatat(git, candidate, &next, AT_SYMLINK_NOFOLLOW) < 0 || !regular(&next)) die();
102
- int exists = fstatat(git, "index", &before, AT_SYMLINK_NOFOLLOW) == 0;
103
- if (exists) { if (!regular(&before)) die(); identity(actual, sizeof(actual), &before); }
104
- else strcpy(actual, "absent");
105
- if (strcmp(actual, expected)) die();
106
- if (exists) {
107
- if (renameatx_np(git, "index", git, backup, RENAME_EXCL) < 0) die();
108
- if (fstatat(git, backup, &captured, AT_SYMLINK_NOFOLLOW) < 0 || !regular(&captured) ||
109
- captured.st_dev != before.st_dev || captured.st_ino != before.st_ino ||
110
- captured.st_size != before.st_size || captured.st_mode != before.st_mode ||
111
- captured.st_mtimespec.tv_sec != before.st_mtimespec.tv_sec || captured.st_mtimespec.tv_nsec != before.st_mtimespec.tv_nsec) {
112
- (void)renameatx_np(git, backup, git, "index", RENAME_EXCL); die();
113
- }
114
- }
115
- if (renameatx_np(git, candidate, git, "index", RENAME_EXCL) < 0) {
116
- if (exists) (void)renameatx_np(git, backup, git, "index", RENAME_EXCL);
117
- die();
118
- }
119
- if (fsync(git) < 0) die();
120
- /* Backups are deliberately retained; never erase an unexpected index. */
121
- }
122
- int main(int argc, char **argv) {
123
- if (argc == 2 && !strcmp(argv[1], "startup-lock")) {
124
- /* fd3 is an engine-private O_NOFOLLOW opened, empty mode-0600 lock file.
125
- * flock belongs to the shared OPEN DESCRIPTION, not this helper's PID.
126
- * NEVER LOCK_UN: the engine and every effect child retain this description. */
127
- struct stat lock;
128
- if (fstat(3, &lock) < 0 || !regular(&lock) || (lock.st_mode & 077) || lock.st_size) die();
129
- if (flock(3, LOCK_EX | LOCK_NB) < 0) {
130
- if (errno == EWOULDBLOCK || errno == EAGAIN) return 75;
131
- die();
132
- }
133
- puts("locked"); return 0;
134
- }
135
- if (argc < 2 || argc > 7) die();
136
- if (!directory(3)) die_reason("unsafe_permissions");
137
- int git = openat(3, ".git", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
138
- if (git < 0) {
139
- if (errno == ENOENT) die_reason("missing_git_dir");
140
- if (errno == ENOTDIR || errno == ELOOP) die_reason("unsupported_worktree");
141
- die();
142
- }
143
- if (!directory(git)) die_reason("unsafe_permissions");
144
- struct stat s; if (fstat(git, &s) < 0) die();
145
- char git_id[128]; snprintf(git_id, sizeof(git_id), "%ju:%ju", (uintmax_t)s.st_dev, (uintmax_t)s.st_ino);
146
- if (!strcmp(argv[1], "probe") && argc == 2) { puts(git_id); return 0; }
147
- if (argc < 3 || strcmp(argv[2], git_id)) die();
148
- inspect(git, 0);
149
- const char *locks[] = {"index.lock", "HEAD.lock", "packed-refs.lock", NULL};
150
- for (size_t i = 0; locks[i]; i++) {
151
- struct stat feature;
152
- if (fstatat(git, locks[i], &feature, AT_SYMLINK_NOFOLLOW) == 0) die_reason("lock_file");
153
- if (errno != ENOENT) die();
154
- }
155
- const char *in_progress[] = {"MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-apply", "rebase-merge", "BISECT_LOG", NULL};
156
- for (size_t i = 0; in_progress[i]; i++) {
157
- struct stat feature;
158
- if (fstatat(git, in_progress[i], &feature, AT_SYMLINK_NOFOLLOW) == 0) die_reason("operation_in_progress");
159
- if (errno != ENOENT) die();
160
- }
161
- const char *unsupported[] = {"commondir", "shallow", "info/grafts", "objects/info/alternates", "objects/info/http-alternates",
162
- "info/sparse-checkout", "refs/replace", "worktrees", NULL};
163
- for (size_t i = 0; unsupported[i]; i++) {
164
- struct stat feature;
165
- if (fstatat(git, unsupported[i], &feature, AT_SYMLINK_NOFOLLOW) == 0) die_reason("unsupported_feature");
166
- if (errno != ENOENT) die();
167
- }
168
- if (!strcmp(argv[1], "config") && argc == 3) { read_file(git, "config", 0); return 0; }
169
- if (!strcmp(argv[1], "index") && argc == 3) { read_file(git, "index", 1); return 0; }
170
- if (!strcmp(argv[1], "install-index") && argc == 5) { install_index(git, argv[3], argv[4]); return 0; }
171
- char *args[64] = {"/Library/Developer/CommandLineTools/usr/bin/git", "--git-dir=.",
172
- "-c", "core.bare=true", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
173
- "-c", "core.attributesFile=/dev/null", "-c", "core.excludesFile=/dev/null",
174
- "-c", "core.sparseCheckout=false", "-c", "index.sparse=false",
175
- "-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "submodule.recurse=false",
176
- "-c", "commit.gpgSign=false", "-c", "gc.auto=0", "-c", "maintenance.auto=false",
177
- "-c", "user.useConfigOnly=true", NULL};
178
- int n = 30; /* first unused slot above */
179
- while (args[n]) n++;
180
- const char *verb = argv[1];
181
- if (!strcmp(verb, "head") && argc == 3) { args[n++] = "rev-parse"; args[n++] = "--verify"; args[n++] = "HEAD"; }
182
- else if (!strcmp(verb, "branch") && argc == 3) { args[n++] = "symbolic-ref"; args[n++] = "--quiet"; args[n++] = "HEAD"; }
183
- else if (!strcmp(verb, "identity") && argc == 3) { args[n++] = "var"; args[n++] = "GIT_AUTHOR_IDENT"; }
184
- else if (!strcmp(verb, "committer") && argc == 3) { args[n++] = "var"; args[n++] = "GIT_COMMITTER_IDENT"; }
185
- else if (!strcmp(verb, "hash") && argc == 3) { args[n++] = "hash-object"; args[n++] = "-w"; args[n++] = "--stdin"; }
186
- else if (!strcmp(verb, "tree") && argc == 3) { args[n++] = "mktree"; args[n++] = "-z"; }
187
- else if (!strcmp(verb, "ls-tree") && argc == 4 && hex(argv[3])) {
188
- args[n++] = "ls-tree"; args[n++] = "-rz"; args[n++] = "--full-tree"; args[n++] = argv[3];
189
- } else if (!strcmp(verb, "index-tree") && argc == 3) { args[n++] = "ls-files"; args[n++] = "--stage"; args[n++] = "-z"; }
190
- else if (!strcmp(verb, "commit") && argc == 5 && hex(argv[3]) && hex(argv[4])) {
191
- args[n++] = "commit-tree"; args[n++] = argv[3]; args[n++] = "-p"; args[n++] = argv[4];
192
- } else if (!strcmp(verb, "ref") && argc == 6 && ref(argv[3]) && hex(argv[4]) && hex(argv[5])) {
193
- args[n++] = "update-ref"; args[n++] = "--no-deref"; args[n++] = "-m"; args[n++] = "Code60 journal";
194
- args[n++] = argv[3]; args[n++] = argv[4]; args[n++] = argv[5];
195
- } else if (!strcmp(verb, "read-tree") && argc == 5 && hex(argv[3]) && token(argv[4])) {
196
- char index[80]; snprintf(index, sizeof(index), ".code60-index-%s", argv[4]);
197
- if (setenv("GIT_INDEX_FILE", index, 1) < 0) die();
198
- args[n++] = "read-tree"; args[n++] = "--reset"; args[n++] = argv[3];
199
- } else die();
200
- args[n] = NULL;
201
- if (fchdir(git) < 0) die();
202
- close(3); close(git);
203
- execv("/Library/Developer/CommandLineTools/usr/bin/git", args);
204
- die();
205
- }
@@ -1,149 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { isIP } from "node:net";
3
- import { domainToASCII } from "node:url";
4
- import { BrokerError } from "./types.js";
5
- export function canonical(value) {
6
- const ancestors = new Set();
7
- const visit = (v) => {
8
- if (v === null || typeof v === "string" || typeof v === "boolean")
9
- return JSON.stringify(v);
10
- if (typeof v === "number" && Number.isFinite(v))
11
- return JSON.stringify(v);
12
- if (typeof v !== "object" || v === null || ancestors.has(v))
13
- throw new BrokerError("invalid_json", 400);
14
- if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) {
15
- throw new BrokerError("invalid_json", 400);
16
- }
17
- ancestors.add(v);
18
- let result;
19
- if (Array.isArray(v)) {
20
- if (Object.keys(v).length !== v.length)
21
- throw new BrokerError("invalid_json", 400);
22
- result = `[${v.map(visit).join(",")}]`;
23
- }
24
- else {
25
- result = `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${visit(v[k])}`).join(",")}}`;
26
- }
27
- ancestors.delete(v);
28
- return result;
29
- };
30
- return visit(value);
31
- }
32
- export function digest(value) {
33
- return `sha256:${createHash("sha256").update(canonical(value)).digest("hex")}`;
34
- }
35
- export function jsonCopy(value) { return JSON.parse(canonical(value)); }
36
- export function relativePath(path) {
37
- if (path === ".")
38
- return path;
39
- if (!path || /[\\\0]/u.test(path) || path.startsWith("/") ||
40
- path.split("/").some(c => !c || c === "." || c === ".."))
41
- throw new BrokerError("invalid_resource_path", 422);
42
- return path;
43
- }
44
- export function normalizeHost(host) {
45
- const raw = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
46
- if (isIP(raw) === 6)
47
- return new URL(`http://[${raw}]/`).hostname.slice(1, -1);
48
- if (isIP(raw) === 4)
49
- return raw;
50
- if (/[:/%\\\s@?#]/u.test(raw))
51
- throw new BrokerError("invalid_network_host", 422);
52
- const ascii = domainToASCII(raw.toLowerCase().replace(/\.$/u, ""));
53
- if (!ascii || ascii.length > 253 || ascii.split(".").some(l => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(l))) {
54
- throw new BrokerError("invalid_network_host", 422);
55
- }
56
- // Reject alternate numeric IPv4 spellings rather than delegating their interpretation.
57
- if (/^[0-9.]+$/u.test(ascii) || /^0x/iu.test(ascii))
58
- throw new BrokerError("invalid_network_host", 422);
59
- return ascii;
60
- }
61
- export function normalizeResources(resources) {
62
- return resources.map(input => {
63
- const r = jsonCopy(input);
64
- if (!/^sha256:[a-f0-9]{64}$/u.test(r.identityDigest))
65
- throw new BrokerError("invalid_resource_identity", 422);
66
- if (r.kind === "filesystem") {
67
- if (!["workspace", "scratch", "deployment"].includes(r.root) || !["read", "write", "delete"].includes(r.operation) ||
68
- (r.root === "deployment" ? !r.rootId : r.rootId !== undefined))
69
- throw new BrokerError("invalid_resource", 422);
70
- r.path = relativePath(r.path);
71
- }
72
- else if (r.kind === "network") {
73
- if (!["http", "https", "tcp", "udp"].includes(r.protocol) || !Number.isInteger(r.port) || r.port < 1 || r.port > 65535) {
74
- throw new BrokerError("invalid_resource", 422);
75
- }
76
- r.host = normalizeHost(r.host);
77
- }
78
- else
79
- throw new BrokerError("invalid_resource", 422);
80
- return r;
81
- });
82
- }
83
- function strongest(effects) {
84
- return effects.includes("deny") ? "deny" : effects.includes("require_approval") ? "require_approval" : effects.includes("allow") ? "allow" : "deny";
85
- }
86
- export function validatePolicy(policy) {
87
- if (policy.defaultEffect !== "deny" || !Array.isArray(policy.rules))
88
- throw new BrokerError("invalid_policy", 422);
89
- for (const rule of policy.rules) {
90
- if (!["deny", "require_approval", "allow"].includes(rule.effect))
91
- throw new BrokerError("invalid_policy", 422);
92
- if (rule.kind === "tool") {
93
- if (typeof rule.toolId !== "string" || !rule.toolId)
94
- throw new BrokerError("invalid_policy", 422);
95
- }
96
- else if (rule.kind === "filesystem") {
97
- relativePath(rule.path);
98
- if (!["workspace", "scratch", "deployment"].includes(rule.root) || typeof rule.recursive !== "boolean" ||
99
- (rule.root === "deployment" ? !rule.rootId : rule.rootId !== undefined) ||
100
- !Array.isArray(rule.operations) || !rule.operations.length ||
101
- rule.operations.some(op => !["read", "write", "delete"].includes(op)))
102
- throw new BrokerError("invalid_policy", 422);
103
- }
104
- else if (rule.kind === "network") {
105
- if (rule.host !== "*")
106
- normalizeHost(rule.host);
107
- if (!["http", "https", "tcp", "udp"].includes(rule.protocol) || !Number.isInteger(rule.port) ||
108
- rule.port < 1 || rule.port > 65535)
109
- throw new BrokerError("invalid_policy", 422);
110
- }
111
- else
112
- throw new BrokerError("invalid_policy", 422);
113
- }
114
- }
115
- function matches(rule, tool, resource) {
116
- if (tool !== undefined)
117
- return rule.kind === "tool" && (rule.toolId === "*" || rule.toolId === tool);
118
- if (!resource || rule.kind !== resource.kind)
119
- return false;
120
- if (rule.kind === "filesystem" && resource.kind === "filesystem") {
121
- relativePath(rule.path);
122
- return rule.root === resource.root && rule.rootId === resource.rootId && rule.operations.includes(resource.operation) &&
123
- (rule.path === resource.path || (rule.recursive && (rule.path === "." || resource.path.startsWith(`${rule.path}/`))));
124
- }
125
- return rule.kind === "network" && resource.kind === "network" &&
126
- rule.protocol === resource.protocol && rule.port === resource.port &&
127
- (rule.host === "*" || normalizeHost(rule.host) === resource.host);
128
- }
129
- export function evaluatePolicy(policy, toolId, resources) {
130
- validatePolicy(policy);
131
- const each = [strongest(policy.rules.filter(r => matches(r, toolId, undefined)).map(r => r.effect))];
132
- for (const resource of normalizeResources(resources)) {
133
- each.push(strongest(policy.rules.filter(r => matches(r, undefined, resource)).map(r => r.effect)));
134
- }
135
- return strongest(each.includes("deny") ? ["deny"] : each);
136
- }
137
- export function evaluate(binding, toolId, resources) {
138
- const actual = normalizeResources(resources);
139
- if (!binding.configuredTools.includes(toolId) ||
140
- (binding.role === "verifier" && actual.some(r => r.kind === "filesystem" && r.root === "workspace" && r.operation !== "read")))
141
- return "deny";
142
- const effects = [evaluatePolicy(binding.permissions, toolId, actual), evaluatePolicy(binding.deploymentPermissions, toolId, actual)];
143
- return effects.includes("deny") ? "deny" : strongest(effects);
144
- }
145
- export function actionDigests(_binding, toolId, arguments_, resources) {
146
- // Pinned source fixtures hash ActionSpec itself. Scope is independently bound
147
- // by the immutable action/claim row and checked on every admission and dispatch.
148
- return { actionDigest: digest({ toolId, arguments: arguments_, resources }), resourceDigest: digest(resources) };
149
- }
@@ -1,14 +0,0 @@
1
- import { fstatSync } from "node:fs";
2
- import { BrokerError } from "./types.js";
3
- /** Root acquires this SAME open description with git-helper startup-lock BEFORE
4
- * opening/recovering mutable engine state. Borrowed FDs are close-only: never
5
- * LOCK_UN. Every writer child inherits it until that child actually exits. */
6
- export function startupLockIdentity(fd) {
7
- if (!Number.isInteger(fd) || fd < 0)
8
- throw new BrokerError("invalid_startup_lock", 422);
9
- const stat = fstatSync(fd, { bigint: true });
10
- if (!stat.isFile() || stat.uid !== BigInt(process.geteuid()) || stat.nlink !== 1n ||
11
- stat.size !== 0n || (stat.mode & 63n))
12
- throw new BrokerError("invalid_startup_lock", 422);
13
- return `${stat.dev}:${stat.ino}`;
14
- }
@@ -1,11 +0,0 @@
1
- export class BrokerError extends Error {
2
- code;
3
- status;
4
- persist;
5
- constructor(code, status = 409, persist = false) {
6
- super(code);
7
- this.code = code;
8
- this.status = status;
9
- this.persist = persist;
10
- }
11
- }
@@ -1,208 +0,0 @@
1
- import { accessSync, constants, existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, renameSync } from 'node:fs';
2
- import { execFileSync } from 'node:child_process';
3
- import { getServers } from 'node:dns';
4
- import { isIP } from 'node:net';
5
- import { basename, dirname, isAbsolute, join } from 'node:path';
6
- import { parseArgs } from 'node:util';
7
- import { createInterface } from 'node:readline/promises';
8
- import { defaultStateDirectory, initializeStateDirectory, findRunningEngine } from './daemon.js';
9
- import { defaultTemplateConfigurationPath, resolveNativeHelpers } from './helpers.js';
10
- import { loadDeploymentConfiguration, readPrivateFile } from '../config/deployment.js';
11
- import { DEVELOPER_DEFINITIONS } from '../tools/developer.js';
12
- import { DEFAULT_COMMAND_SETTINGS } from '../tools/commands.js';
13
- import { ContainedCodexAppServer, pilotCodexConfig } from '../runtime/codex-app-server.js';
14
- import { ValidationPool } from '../config/validation-pool.js';
15
- import Database from 'better-sqlite3';
16
- import { SqliteCoordinator } from '../storage/coordinator.js';
17
- import { ProviderTransport } from '../runtime/provider-transport.js';
18
- import { ProviderCredentials } from '../runtime/provider-credentials.js';
19
- import { missingCodingPermissions } from '../config/coding-policy.js';
20
- import { assertRuntimeBuild } from './runtime-build.js';
21
- import { resolveCodexExecutable } from '../runtime/codex-executable.js';
22
- const usage = `Usage:
23
- code60 configure [--state-directory PATH] [--listen-port PORT] [--model-port PORT] [--check-file PATH] [--executable PATH] [--provider openrouter|openai|local] [--endpoint HTTPS_URL] [--model MODEL] [--credential-file PATH] [--toolchain PATH ...]
24
- code60 doctor [--state-directory PATH] [--repository PATH] [--check-provider]
25
- Use configure --coding-only to enable coding tools and commands while preserving all runtime, provider, model, and credential settings.
26
- Credentials are read from an existing private file, never from command arguments or ambient logins.
27
- `;
28
- const which = (name) => { try {
29
- return realpathSync(execFileSync('/usr/bin/which', [name], { encoding: 'utf8', timeout: 3000 }).trim());
30
- }
31
- catch {
32
- return undefined;
33
- } };
34
- export async function configurationCli(argv) {
35
- const command = argv[0];
36
- const { values } = parseArgs({ args: argv.slice(1), options: { help: { type: 'boolean' }, 'state-directory': { type: 'string' }, 'coding-only': { type: 'boolean' }, 'listen-port': { type: 'string' }, 'model-port': { type: 'string' }, 'check-file': { type: 'string' }, executable: { type: 'string' }, provider: { type: 'string' }, endpoint: { type: 'string' }, model: { type: 'string' }, 'credential-file': { type: 'string' }, toolchain: { type: 'string', multiple: true }, repository: { type: 'string' }, 'check-provider': { type: 'boolean' } } });
37
- if (values.help) {
38
- process.stdout.write(usage);
39
- return;
40
- }
41
- if (values['coding-only'] && (command !== 'configure' || ['executable', 'provider', 'endpoint', 'model', 'credential-file'].some(key => values[key] !== undefined)))
42
- throw new Error('--coding-only preserves provider/runtime settings; do not combine it with provider or runtime selection flags.');
43
- const paths = initializeStateDirectory(values['state-directory'] ?? defaultStateDirectory(), defaultTemplateConfigurationPath());
44
- if (command === 'configure') {
45
- if (findRunningEngine(paths.stateDirectory))
46
- throw new Error('Stop this state directory’s engine with code60 stop before changing its configuration.');
47
- const config = JSON.parse(readFileSync(paths.configurationFile, 'utf8'));
48
- const readline = process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
49
- try {
50
- if (!values['coding-only']) {
51
- const ask = async (label, value) => value ?? (readline ? (await readline.question(label + ': ')).trim() : undefined);
52
- const executable = await ask('Absolute Codex executable path', values.executable ?? (existsSync(config.runtime.executable) ? config.runtime.executable : which('codex')));
53
- if (!executable || !isAbsolute(executable))
54
- throw new Error('Supply --executable with the absolute Codex executable path.');
55
- accessSync(executable, constants.X_OK);
56
- const provider = await ask('Provider (openrouter, openai, local)', values.provider ?? config.providers?.[0]?.id) ?? 'openrouter';
57
- const model = await ask('Model ID', values.model ?? config.providers?.[0]?.models[0]?.id);
58
- if (!model)
59
- throw new Error('Supply --model with your provider’s model ID.');
60
- config.runtime = { ...config.runtime, enabled: true, executable: resolveCodexExecutable(executable), models: [{ id: model, effortLevels: ['low'] }] };
61
- if (provider === 'local') {
62
- delete config.providers;
63
- delete config.providerCredentials;
64
- }
65
- else {
66
- const endpoint = values.endpoint ?? (provider === 'openai' ? 'https://api.openai.com/v1/responses' : provider === 'openrouter' ? 'https://openrouter.ai/api/v1/responses' : undefined);
67
- if (!endpoint || new URL(endpoint).protocol !== 'https:')
68
- throw new Error('Select openai/openrouter or supply --endpoint with a fixed HTTPS Responses URL.');
69
- const credentialFile = await ask('Absolute private credential-file path', values['credential-file'] ?? config.providerCredentials?.[0]?.file);
70
- if (!credentialFile)
71
- throw new Error('Supply --credential-file with an existing owned mode-0600 API-key file.');
72
- readPrivateFile(credentialFile, 8192);
73
- const resolver = getServers().find(server => isIP(server)) ?? '8.8.8.8';
74
- config.providers = [{ id: provider, endpoint, maxRequestBytes: 67_108_864, timeoutMs: 120_000, dnsResolvers: [{ address: resolver, port: 53 }], models: [{ id: model, effortLevels: ['low'], defaultEffort: 'low' }], networkPolicy: { defaultEffect: 'deny', rules: [
75
- { kind: 'network', protocol: 'https', host: '*', port: 443, effect: 'allow' }, { kind: 'network', protocol: 'udp', host: resolver, port: 53, effect: 'allow' }, { kind: 'network', protocol: 'tcp', host: resolver, port: 53, effect: 'allow' }
76
- ] } }];
77
- config.providerCredentials = [{ referenceId: 'coding-provider', version: 'configured-v1', providerId: provider, origin: new URL(endpoint).origin, file: realpathSync(credentialFile) }];
78
- }
79
- }
80
- for (const flag of ['listen-port', 'model-port'])
81
- if (values[flag] !== undefined) {
82
- const port = Number(values[flag]);
83
- if (!/^\d+$/.test(values[flag]) || !Number.isInteger(port) || port < 1 || port > 65535)
84
- throw new Error(`--${flag} must be a port from 1 to 65535.`);
85
- if (flag === 'listen-port')
86
- config.listenPort = port;
87
- else
88
- config.runtime.modelPort = port;
89
- }
90
- if (config.listenPort === config.runtime.modelPort)
91
- throw new Error('The listen and model ports must differ.');
92
- if (values['check-file'])
93
- config.checks = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(readPrivateFile(values['check-file'], 262_144)));
94
- const discovered = ['node', 'npm', 'pnpm', 'yarn', 'bun', 'python3', 'cargo', 'go'].flatMap(name => {
95
- const path = which(name);
96
- if (!path)
97
- return [];
98
- const bin = dirname(path);
99
- return [bin, ...(['node', 'python3', 'go'].includes(name) && basename(bin) === 'bin' || ['npm', 'pnpm', 'yarn'].includes(name) ? [dirname(bin)] : [])];
100
- });
101
- config.commands = { ...DEFAULT_COMMAND_SETTINGS, ...config.commands, enabled: true, network: 'outbound', toolchainPaths: [...new Set([...(config.commands?.toolchainPaths ?? []), ...discovered, ...(values.toolchain ?? [])])].map(p => realpathSync(p)) };
102
- config.deploymentPolicy = { defaultEffect: 'deny', rules: [...config.deploymentPolicy.rules,
103
- ...[...DEVELOPER_DEFINITIONS.keys()].map(toolId => ({ kind: 'tool', toolId, effect: 'allow' })),
104
- { kind: 'filesystem', root: 'workspace', path: '.', recursive: true, operations: ['read', 'write', 'delete'], effect: 'allow' }] };
105
- config.deploymentPolicy.rules = [...new Map(config.deploymentPolicy.rules.map(rule => [JSON.stringify(rule), rule])).values()];
106
- config.contextBytes = 65_536;
107
- const temporary = paths.configurationFile + `.${process.pid}.${Date.now()}.pending`;
108
- writeFileSync(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
109
- const db = new Database(':memory:'), pool = new ValidationPool(new SqliteCoordinator(db));
110
- try {
111
- await loadDeploymentConfiguration(temporary, pool);
112
- renameSync(temporary, paths.configurationFile);
113
- }
114
- finally {
115
- await pool.close();
116
- db.close();
117
- if (existsSync(temporary))
118
- rmSync(temporary);
119
- }
120
- process.stdout.write(`Configured coding tasks in ${paths.configurationFile}. Run code60 doctor, then reconnect your MCP client.\n`);
121
- }
122
- finally {
123
- readline?.close();
124
- }
125
- return;
126
- }
127
- const db = new Database(':memory:'), coordinator = new SqliteCoordinator(db), pool = new ValidationPool(coordinator);
128
- const checks = [];
129
- try {
130
- const config = await loadDeploymentConfiguration(paths.configurationFile, pool);
131
- checks.push({ name: 'configuration', status: 'pass' });
132
- const running = findRunningEngine(paths.stateDirectory);
133
- if (running) {
134
- try {
135
- assertRuntimeBuild(paths.stateDirectory, running.pid);
136
- checks.push({ name: 'running_engine_version', status: 'pass' });
137
- }
138
- catch (error) {
139
- checks.push({ name: 'running_engine_version', status: 'fail', detail: error.message });
140
- }
141
- }
142
- try {
143
- resolveNativeHelpers(paths.stateDirectory);
144
- checks.push({ name: 'native_helpers', status: 'pass' });
145
- }
146
- catch {
147
- checks.push({ name: 'native_helpers', status: 'fail', detail: 'Build or reinstall the native helpers; Xcode Command Line Tools are required for compilation.' });
148
- }
149
- const state = mkdtempSync(join(paths.stateDirectory, 'doctor-'));
150
- let client;
151
- try {
152
- client = new ContainedCodexAppServer({ executable: config.runtime.executable, stateDirectory: state, modelPort: config.runtime.modelPort, config: pilotCodexConfig(config.runtime.modelPort) });
153
- await client.initialize();
154
- checks.push({ name: 'contained_app_server_handshake', status: 'pass' });
155
- }
156
- catch {
157
- checks.push({ name: 'contained_app_server_handshake', status: 'fail', detail: 'Check the executable, Codex app-server compatibility, and macOS sandbox support.' });
158
- }
159
- finally {
160
- await client?.close();
161
- rmSync(state, { recursive: true, force: true });
162
- }
163
- checks.push({ name: 'command_execution', status: config.commands?.enabled ? 'pass' : 'fail', detail: 'Brokered commands require the configured coding preset.' });
164
- const missing = missingCodingPermissions(config.deploymentPolicy);
165
- checks.push({ name: 'coding_permissions', status: missing.length ? 'fail' : 'pass', ...(missing.length ? { detail: `Deployment policy denies ${missing.join(', ')}. Stop the engine and run code60 configure --coding-only. Profile permissions cannot override deployment denials.` } : {}) });
166
- if (values.repository) {
167
- const { SourceRepository } = await import('../workspaces/source.js');
168
- try {
169
- const repository = new SourceRepository(values.repository);
170
- repository.head();
171
- const entries = repository.sourceEntries();
172
- checks.push({ name: 'repository', status: 'pass', detail: `${entries.length} source entries; ignored dependencies excluded; dirty edits are supported.` });
173
- }
174
- catch {
175
- checks.push({ name: 'repository', status: 'fail', detail: 'Use a supported repository root with an existing commit; resolve unfinished Git operations.' });
176
- }
177
- }
178
- if (values['check-provider']) {
179
- const provider = config.providers?.[0], file = config.providerCredentials?.find(c => c.providerId === provider?.id);
180
- if (!provider || !file)
181
- checks.push({ name: 'provider_authentication', status: 'fail', detail: 'Configure an HTTPS provider and credential reference first.' });
182
- else {
183
- const credentials = new ProviderCredentials(config.providerCredentials ?? [], readPrivateFile), credential = credentials.describe(file.referenceId, provider.id, new URL(provider.endpoint).origin);
184
- const transport = new ProviderTransport({ coordinator, endpoint: provider.endpoint, networkPolicy: provider.networkPolicy, ...(provider.dnsResolvers ? { dnsResolvers: provider.dnsResolvers } : {}), timeoutMs: provider.timeoutMs ?? 120_000 });
185
- const bytes = Buffer.from(JSON.stringify({ model: provider.models[0].id, input: 'Reply OK.', reasoning: { effort: provider.models[0].defaultEffort }, max_output_tokens: 32 }));
186
- try {
187
- await transport.post({ body: (async function* () { yield bytes; })(), contentLength: bytes.length, signal: AbortSignal.timeout(provider.timeoutMs ?? 120_000), credential, admit: () => { }, resolveCredential: () => credentials.resolve(credential, provider.id), onHeaders: () => { }, onChunk: async () => { } });
188
- checks.push({ name: 'provider_authentication', status: 'pass' });
189
- }
190
- catch (error) {
191
- checks.push({ name: 'provider_authentication', status: 'fail', detail: error instanceof Error ? error.message : 'Provider probe failed.' });
192
- }
193
- finally {
194
- await transport.close();
195
- }
196
- }
197
- }
198
- else
199
- checks.push({ name: 'provider_authentication', status: 'not_checked', detail: 'Use --check-provider for an explicit billable model probe.' });
200
- process.stdout.write(JSON.stringify({ ready: checks.every(c => c.status !== 'fail'), checks }, null, 2) + '\n');
201
- if (checks.some(c => c.status === 'fail'))
202
- process.exitCode = 1;
203
- }
204
- finally {
205
- await pool.close();
206
- db.close();
207
- }
208
- }