@carrieros/cli-staging 0.0.0-stage → 0.4.1
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/README.md +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +26 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +160 -0
- package/dist/commands/update.js +285 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +229 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +364 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +132 -0
- package/dist/services/api.js +441 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +384 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +416 -0
- package/dist/services/device-auth.js +288 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +42 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +115 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +730 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1622 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +414 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { compileIgnorePattern, toPosix } from "./glob-match.js";
|
|
2
|
+
/**
|
|
3
|
+
* The vocabulary of what counts as noise in a codebase.
|
|
4
|
+
*
|
|
5
|
+
* Mirrored deliberately from the backend rather than written fresh:
|
|
6
|
+
* `SPA_ZIP_SKIP_DIRS` in api.carrieros.ai `src/routes/spa.js`, and the file
|
|
7
|
+
* filter in `src/services/ragService.js`. Those lists are already tuned against
|
|
8
|
+
* real archives and real embedding cost, and the reason to copy them exactly is
|
|
9
|
+
* that a local repository and an uploaded ZIP of the SAME project must resolve
|
|
10
|
+
* to the same set of files. Two vocabularies would mean the CLI and the web
|
|
11
|
+
* answering questions from different views of one codebase, which is far worse
|
|
12
|
+
* than either view being slightly wrong.
|
|
13
|
+
*
|
|
14
|
+
* NOTHING WALKS A DIRECTORY YET. This module exists so that when local
|
|
15
|
+
* traversal lands, there is already one place holding the policy — and so the
|
|
16
|
+
* policy is not quietly reinvented at that point. Keep it in step with the
|
|
17
|
+
* backend; do not extend it here unilaterally.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Directories whose contents are build output, vendored code, or VCS
|
|
21
|
+
* bookkeeping. Stored without the trailing slash the backend uses, because a
|
|
22
|
+
* traversal matches directory NAMES rather than path prefixes.
|
|
23
|
+
*/
|
|
24
|
+
export const IGNORED_DIRECTORIES = [
|
|
25
|
+
"node_modules",
|
|
26
|
+
".git",
|
|
27
|
+
"dist",
|
|
28
|
+
"build",
|
|
29
|
+
".next",
|
|
30
|
+
"out",
|
|
31
|
+
"vendor",
|
|
32
|
+
"__pycache__",
|
|
33
|
+
".venv",
|
|
34
|
+
"venv",
|
|
35
|
+
"target",
|
|
36
|
+
"coverage",
|
|
37
|
+
".idea",
|
|
38
|
+
".vscode",
|
|
39
|
+
"bower_components",
|
|
40
|
+
".cache",
|
|
41
|
+
"__macosx"
|
|
42
|
+
];
|
|
43
|
+
/** Extensions the backend treats as low-signal — assets and generated maps. */
|
|
44
|
+
export const LOW_SIGNAL_EXTENSIONS = [
|
|
45
|
+
".scss",
|
|
46
|
+
".less",
|
|
47
|
+
".svg",
|
|
48
|
+
".map",
|
|
49
|
+
".lock",
|
|
50
|
+
".png",
|
|
51
|
+
".jpg",
|
|
52
|
+
".jpeg",
|
|
53
|
+
".ico",
|
|
54
|
+
".woff",
|
|
55
|
+
".woff2"
|
|
56
|
+
];
|
|
57
|
+
/** Lockfiles and boilerplate manifests — present in every project, meaningful in none. */
|
|
58
|
+
export const IGNORED_FILENAMES = [
|
|
59
|
+
"package-lock.json",
|
|
60
|
+
"yarn.lock",
|
|
61
|
+
"pnpm-lock.yaml",
|
|
62
|
+
".gitignore",
|
|
63
|
+
".dockerignore"
|
|
64
|
+
];
|
|
65
|
+
/** Directory names are compared case-insensitively — Windows, and `__MACOSX`. */
|
|
66
|
+
const IGNORED_DIR_SET = new Set(IGNORED_DIRECTORIES.map((d) => d.toLowerCase()));
|
|
67
|
+
export function isIgnoredDirectory(name) {
|
|
68
|
+
return IGNORED_DIR_SET.has(name.toLowerCase());
|
|
69
|
+
}
|
|
70
|
+
export function ignorePolicy() {
|
|
71
|
+
return {
|
|
72
|
+
directories: IGNORED_DIRECTORIES,
|
|
73
|
+
extensions: LOW_SIGNAL_EXTENSIONS,
|
|
74
|
+
filenames: IGNORED_FILENAMES,
|
|
75
|
+
isIgnoredDirectory
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Parse .gitignore text into rules.
|
|
80
|
+
*
|
|
81
|
+
* Implements the parts of the format that actually decide matches: comments,
|
|
82
|
+
* blank lines, `!` negation, a trailing slash for directory-only, a leading
|
|
83
|
+
* slash or an interior slash for anchoring, and `\` escapes. Trailing
|
|
84
|
+
* whitespace is stripped unless escaped, which is the rule that bites anyone
|
|
85
|
+
* who writes `*.log ` with a stray space.
|
|
86
|
+
*/
|
|
87
|
+
export function parseGitignore(text, base) {
|
|
88
|
+
const rules = [];
|
|
89
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
90
|
+
let line = raw.replace(/(?<!\\)\s+$/, "");
|
|
91
|
+
if (!line || line.startsWith("#"))
|
|
92
|
+
continue;
|
|
93
|
+
let negated = false;
|
|
94
|
+
if (line.startsWith("!")) {
|
|
95
|
+
negated = true;
|
|
96
|
+
line = line.slice(1);
|
|
97
|
+
}
|
|
98
|
+
// An escaped leading '#' or '!' is a literal.
|
|
99
|
+
if (line.startsWith("\\#") || line.startsWith("\\!"))
|
|
100
|
+
line = line.slice(1);
|
|
101
|
+
if (!line)
|
|
102
|
+
continue;
|
|
103
|
+
let dirOnly = false;
|
|
104
|
+
if (line.endsWith("/")) {
|
|
105
|
+
dirOnly = true;
|
|
106
|
+
line = line.slice(0, -1);
|
|
107
|
+
if (!line)
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
// Anchored when the pattern says where it lives: a leading slash, or a
|
|
111
|
+
// slash anywhere inside it. A bare `*.log` floats to any depth.
|
|
112
|
+
const anchored = line.startsWith("/") || line.slice(0, -1).includes("/");
|
|
113
|
+
if (line.startsWith("/"))
|
|
114
|
+
line = line.slice(1);
|
|
115
|
+
if (!line)
|
|
116
|
+
continue;
|
|
117
|
+
rules.push({ negated, dirOnly, re: compileIgnorePattern(line, anchored) });
|
|
118
|
+
}
|
|
119
|
+
return { base, rules };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The ignore decision for one walk, as a stack of rule sets.
|
|
123
|
+
*
|
|
124
|
+
* A stack rather than a single list because .gitignore nests: a file's fate is
|
|
125
|
+
* decided by every .gitignore at or above it, nearest last. The walker pushes a
|
|
126
|
+
* set when it descends into a directory that has one and pops it on the way
|
|
127
|
+
* out, so the cost is one parse per .gitignore actually encountered — and it
|
|
128
|
+
* sees them for free, since the directory listing already names them.
|
|
129
|
+
*/
|
|
130
|
+
export class IgnoreMatcher {
|
|
131
|
+
#stack = [];
|
|
132
|
+
/** Add the rules from one .gitignore, scoped to `base` and everything under it. */
|
|
133
|
+
push(text, base) {
|
|
134
|
+
this.#stack.push(parseGitignore(text, toPosix(base)));
|
|
135
|
+
}
|
|
136
|
+
/** How many rule sets are active — the walker's restore point. */
|
|
137
|
+
get depth() {
|
|
138
|
+
return this.#stack.length;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Drop rule sets back to a previous depth, used when leaving a subtree.
|
|
142
|
+
*
|
|
143
|
+
* By recorded depth rather than by path prefix: at the root the base is the
|
|
144
|
+
* empty string, and every base starts with that, so a prefix-based pop would
|
|
145
|
+
* clear the entire stack the first time the walker unwound.
|
|
146
|
+
*/
|
|
147
|
+
truncate(depth) {
|
|
148
|
+
if (depth < this.#stack.length)
|
|
149
|
+
this.#stack.length = depth;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Should this path be skipped?
|
|
153
|
+
*
|
|
154
|
+
* `relPath` is POSIX and relative to the walk root. Hard excludes are checked
|
|
155
|
+
* first and cannot be negated by a repository — a project that un-ignores
|
|
156
|
+
* `node_modules` still should not have it walked, because the reason to skip
|
|
157
|
+
* it is cost, not the author's preference.
|
|
158
|
+
*/
|
|
159
|
+
shouldIgnore(relPath, opts) {
|
|
160
|
+
const posix = toPosix(relPath);
|
|
161
|
+
const name = posix.slice(posix.lastIndexOf("/") + 1);
|
|
162
|
+
if (opts.isDirectory && isIgnoredDirectory(name))
|
|
163
|
+
return true;
|
|
164
|
+
let ignored = false;
|
|
165
|
+
for (const set of this.#stack) {
|
|
166
|
+
// A rule set only governs its own subtree.
|
|
167
|
+
if (set.base && !(posix === set.base || posix.startsWith(`${set.base}/`)))
|
|
168
|
+
continue;
|
|
169
|
+
const scoped = set.base ? posix.slice(set.base.length + 1) : posix;
|
|
170
|
+
if (!scoped)
|
|
171
|
+
continue;
|
|
172
|
+
for (const rule of set.rules) {
|
|
173
|
+
if (rule.dirOnly && !opts.isDirectory)
|
|
174
|
+
continue;
|
|
175
|
+
if (rule.re.test(scoped))
|
|
176
|
+
ignored = !rule.negated;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return ignored;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** True for files the backend treats as low-signal — assets, maps, lockfiles. */
|
|
183
|
+
export function isLowSignalFile(name) {
|
|
184
|
+
const lower = name.toLowerCase();
|
|
185
|
+
if (IGNORED_FILENAMES.includes(lower))
|
|
186
|
+
return true;
|
|
187
|
+
const dot = lower.lastIndexOf(".");
|
|
188
|
+
return dot >= 0 && LOW_SIGNAL_EXTENSIONS.includes(lower.slice(dot));
|
|
189
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
/** Repository instruction sources, ordered from general to specific. */
|
|
4
|
+
export const INSTRUCTION_FILE_NAMES = ["AGENTS.md", "CLAUDE.md"];
|
|
5
|
+
/**
|
|
6
|
+
* Resolve instruction files that apply to a set of repository-relative
|
|
7
|
+
* directories. Results are ordered root-to-leaf, with AGENTS.md before
|
|
8
|
+
* CLAUDE.md at each scope, so later, narrower guidance can take precedence.
|
|
9
|
+
*
|
|
10
|
+
* This only discovers paths; callers still read the files through the normal
|
|
11
|
+
* containment-checked file reader. In particular, a symlink outside the
|
|
12
|
+
* selected repository is never treated as project guidance.
|
|
13
|
+
*/
|
|
14
|
+
export function instructionPathsForDirectories(repositoryRoot, directories) {
|
|
15
|
+
const root = fs.realpathSync.native(repositoryRoot);
|
|
16
|
+
const scopes = new Set(["."]);
|
|
17
|
+
for (const directory of directories) {
|
|
18
|
+
if (typeof directory !== "string" || !directory.trim() || path.isAbsolute(directory) || /[:\0]/.test(directory)) {
|
|
19
|
+
throw new Error("Instruction scopes must be repository-relative paths.");
|
|
20
|
+
}
|
|
21
|
+
const normalized = path.normalize(directory);
|
|
22
|
+
const parts = normalized.split(path.sep).filter((part) => part && part !== ".");
|
|
23
|
+
if (parts.includes(".."))
|
|
24
|
+
throw new Error("Instruction scopes must stay inside the repository.");
|
|
25
|
+
let current = ".";
|
|
26
|
+
for (const part of parts) {
|
|
27
|
+
current = current === "." ? part : path.join(current, part);
|
|
28
|
+
scopes.add(current);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const orderedScopes = [...scopes].sort((a, b) => {
|
|
32
|
+
const depth = (value) => value === "." ? 0 : value.split(path.sep).length;
|
|
33
|
+
return depth(a) - depth(b) || a.localeCompare(b);
|
|
34
|
+
});
|
|
35
|
+
const found = [];
|
|
36
|
+
for (const scope of orderedScopes) {
|
|
37
|
+
for (const name of INSTRUCTION_FILE_NAMES) {
|
|
38
|
+
const absolute = path.join(root, scope, name);
|
|
39
|
+
try {
|
|
40
|
+
if (!fs.statSync(absolute).isFile())
|
|
41
|
+
continue;
|
|
42
|
+
const actual = fs.realpathSync.native(absolute);
|
|
43
|
+
const relative = path.relative(root, actual);
|
|
44
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
45
|
+
continue;
|
|
46
|
+
found.push(path.relative(root, absolute).split(path.sep).join("/"));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Missing, unreadable and broken-link instruction files are ignored.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return found;
|
|
54
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ConfigStore } from "./config.js";
|
|
6
|
+
import { damagedInstallMessage, findPrebuiltHelper } from "./helper-bin.js";
|
|
7
|
+
import { isPackaged } from "./packaged.js";
|
|
8
|
+
/**
|
|
9
|
+
* The Windows process-containment helper.
|
|
10
|
+
*
|
|
11
|
+
* Node has no API for Job Objects, and without one a cancelled or timed-out
|
|
12
|
+
* command leaves its grandchildren running: measured on this CLI's target
|
|
13
|
+
* platform, `child.kill()`, a spawnSync timeout and the CLI exiting all left a
|
|
14
|
+
* `cmd -> ping` grandchild alive, and `taskkill /T` misses anything whose
|
|
15
|
+
* parent already exited.
|
|
16
|
+
*
|
|
17
|
+
* So commands start through this tiny launcher. It creates a Job Object with
|
|
18
|
+
* KILL_ON_JOB_CLOSE and NO breakaway, starts the program suspended, assigns it,
|
|
19
|
+
* then resumes it — nothing it starts can escape. The launcher holds the only
|
|
20
|
+
* job handle, and Node's own job kills the launcher when the CLI dies, so every
|
|
21
|
+
* way the CLI or the command ends takes the whole tree with it.
|
|
22
|
+
*
|
|
23
|
+
* The source is below and compiled on first use with the C# compiler that ships
|
|
24
|
+
* with Windows (.NET Framework 4.x, `csc.exe`) — no binary is downloaded or
|
|
25
|
+
* bundled. The result is cached per source hash in the CLI's LOCAL app data and
|
|
26
|
+
* its hash is checked before every use. That check catches corruption and a
|
|
27
|
+
* stale build; it is NOT a defence against other code running as the same
|
|
28
|
+
* user, which could replace any file this user can write.
|
|
29
|
+
*/
|
|
30
|
+
export const JOB_HELPER_FAILURE_EXIT = 32431;
|
|
31
|
+
export const JOB_HELPER_SOURCE = String.raw `using System;
|
|
32
|
+
using System.ComponentModel;
|
|
33
|
+
using System.Runtime.InteropServices;
|
|
34
|
+
using System.Text;
|
|
35
|
+
|
|
36
|
+
// cos-job-runner: start ONE program inside a Windows Job Object that kills
|
|
37
|
+
// every process in it when the job's last handle closes. This process holds the
|
|
38
|
+
// only handle, so however it ends — normal exit, TerminateProcess, or its own
|
|
39
|
+
// parent dying — the whole tree it started ends with it.
|
|
40
|
+
//
|
|
41
|
+
// Usage: cos-job-runner.exe <absolute-program-path> [args...]
|
|
42
|
+
// The program is started SUSPENDED, assigned to the job, then resumed, so no
|
|
43
|
+
// descendant can be created outside the job. No shell is involved: the argv is
|
|
44
|
+
// re-quoted with the MSVC rules and passed to CreateProcess with the program
|
|
45
|
+
// path as lpApplicationName (no search).
|
|
46
|
+
static class CosJobRunner
|
|
47
|
+
{
|
|
48
|
+
const int HelperFailure = 32431;
|
|
49
|
+
|
|
50
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
51
|
+
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
|
|
52
|
+
{
|
|
53
|
+
public long PerProcessUserTimeLimit;
|
|
54
|
+
public long PerJobUserTimeLimit;
|
|
55
|
+
public uint LimitFlags;
|
|
56
|
+
public UIntPtr MinimumWorkingSetSize;
|
|
57
|
+
public UIntPtr MaximumWorkingSetSize;
|
|
58
|
+
public uint ActiveProcessLimit;
|
|
59
|
+
public UIntPtr Affinity;
|
|
60
|
+
public uint PriorityClass;
|
|
61
|
+
public uint SchedulingClass;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
65
|
+
struct IO_COUNTERS
|
|
66
|
+
{
|
|
67
|
+
public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount;
|
|
68
|
+
public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
72
|
+
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
|
73
|
+
{
|
|
74
|
+
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
|
75
|
+
public IO_COUNTERS IoInfo;
|
|
76
|
+
public UIntPtr ProcessMemoryLimit;
|
|
77
|
+
public UIntPtr JobMemoryLimit;
|
|
78
|
+
public UIntPtr PeakProcessMemoryUsed;
|
|
79
|
+
public UIntPtr PeakJobMemoryUsed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
83
|
+
struct STARTUPINFO
|
|
84
|
+
{
|
|
85
|
+
public int cb;
|
|
86
|
+
public string lpReserved, lpDesktop, lpTitle;
|
|
87
|
+
public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
|
|
88
|
+
public short wShowWindow, cbReserved2;
|
|
89
|
+
public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
93
|
+
struct PROCESS_INFORMATION
|
|
94
|
+
{
|
|
95
|
+
public IntPtr hProcess, hThread;
|
|
96
|
+
public int dwProcessId, dwThreadId;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
100
|
+
static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
|
|
101
|
+
|
|
102
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
103
|
+
static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length);
|
|
104
|
+
|
|
105
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
106
|
+
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
107
|
+
|
|
108
|
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
109
|
+
static extern bool CreateProcessW(string app, StringBuilder cmdLine, IntPtr procAttr, IntPtr threadAttr,
|
|
110
|
+
bool inheritHandles, uint flags, IntPtr env, string cwd, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
|
|
111
|
+
|
|
112
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
113
|
+
static extern uint ResumeThread(IntPtr thread);
|
|
114
|
+
|
|
115
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
116
|
+
static extern bool TerminateProcess(IntPtr process, uint code);
|
|
117
|
+
|
|
118
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
119
|
+
static extern bool TerminateJobObject(IntPtr job, uint code);
|
|
120
|
+
|
|
121
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
122
|
+
static extern uint WaitForSingleObject(IntPtr handle, uint ms);
|
|
123
|
+
|
|
124
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
125
|
+
static extern bool GetExitCodeProcess(IntPtr process, out uint code);
|
|
126
|
+
|
|
127
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
128
|
+
static extern IntPtr GetStdHandle(int which);
|
|
129
|
+
|
|
130
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
131
|
+
static extern bool CloseHandle(IntPtr handle);
|
|
132
|
+
|
|
133
|
+
const int JobObjectExtendedLimitInformation = 9;
|
|
134
|
+
const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000;
|
|
135
|
+
const uint JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x400;
|
|
136
|
+
const uint CREATE_SUSPENDED = 0x4;
|
|
137
|
+
const uint CREATE_NO_WINDOW = 0x08000000;
|
|
138
|
+
const int STARTF_USESTDHANDLES = 0x100;
|
|
139
|
+
const uint INFINITE = 0xFFFFFFFF;
|
|
140
|
+
|
|
141
|
+
static int Fail(string what)
|
|
142
|
+
{
|
|
143
|
+
Console.Error.WriteLine("cos-job-runner: " + what + ": " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
|
|
144
|
+
return HelperFailure;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// MSVC / CommandLineToArgvW quoting, so the child sees exactly these args.
|
|
148
|
+
static string Quote(string arg)
|
|
149
|
+
{
|
|
150
|
+
if (arg.Length > 0 && arg.IndexOfAny(new[] { ' ', '\t', '\n', '\v', '"' }) < 0) return arg;
|
|
151
|
+
var sb = new StringBuilder("\"");
|
|
152
|
+
for (int i = 0; ; i++)
|
|
153
|
+
{
|
|
154
|
+
int slashes = 0;
|
|
155
|
+
while (i < arg.Length && arg[i] == '\\') { slashes++; i++; }
|
|
156
|
+
if (i == arg.Length) { sb.Append('\\', slashes * 2); break; }
|
|
157
|
+
if (arg[i] == '"') { sb.Append('\\', slashes * 2 + 1); sb.Append('"'); }
|
|
158
|
+
else { sb.Append('\\', slashes); sb.Append(arg[i]); }
|
|
159
|
+
}
|
|
160
|
+
sb.Append('"');
|
|
161
|
+
return sb.ToString();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static int Main(string[] argv)
|
|
165
|
+
{
|
|
166
|
+
if (argv.Length < 1 || !System.IO.Path.IsPathRooted(argv[0]))
|
|
167
|
+
{
|
|
168
|
+
Console.Error.WriteLine("cos-job-runner: an absolute program path is required");
|
|
169
|
+
return HelperFailure;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
IntPtr job = CreateJobObjectW(IntPtr.Zero, null);
|
|
173
|
+
if (job == IntPtr.Zero) return Fail("CreateJobObject");
|
|
174
|
+
|
|
175
|
+
var limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
|
|
176
|
+
// No BREAKAWAY_OK flags: nothing started inside may leave the job.
|
|
177
|
+
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
|
|
178
|
+
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, ref limits, (uint)Marshal.SizeOf(limits)))
|
|
179
|
+
return Fail("SetInformationJobObject");
|
|
180
|
+
|
|
181
|
+
var cmd = new StringBuilder();
|
|
182
|
+
for (int i = 0; i < argv.Length; i++)
|
|
183
|
+
{
|
|
184
|
+
if (i > 0) cmd.Append(' ');
|
|
185
|
+
cmd.Append(Quote(argv[i]));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
var si = new STARTUPINFO();
|
|
189
|
+
si.cb = Marshal.SizeOf(si);
|
|
190
|
+
si.dwFlags = STARTF_USESTDHANDLES;
|
|
191
|
+
si.hStdInput = GetStdHandle(-10);
|
|
192
|
+
si.hStdOutput = GetStdHandle(-11);
|
|
193
|
+
si.hStdError = GetStdHandle(-12);
|
|
194
|
+
|
|
195
|
+
PROCESS_INFORMATION pi;
|
|
196
|
+
// CREATE_NO_WINDOW: a hidden console of its own — descendants never draw
|
|
197
|
+
// on, or receive Ctrl+C from, the user's terminal.
|
|
198
|
+
if (!CreateProcessW(argv[0], cmd, IntPtr.Zero, IntPtr.Zero, true, CREATE_SUSPENDED | CREATE_NO_WINDOW,
|
|
199
|
+
IntPtr.Zero, null, ref si, out pi))
|
|
200
|
+
return Fail("CreateProcess");
|
|
201
|
+
|
|
202
|
+
if (!AssignProcessToJobObject(job, pi.hProcess))
|
|
203
|
+
{
|
|
204
|
+
string reason = new Win32Exception(Marshal.GetLastWin32Error()).Message;
|
|
205
|
+
TerminateProcess(pi.hProcess, HelperFailure);
|
|
206
|
+
Console.Error.WriteLine("cos-job-runner: AssignProcessToJobObject: " + reason);
|
|
207
|
+
return HelperFailure;
|
|
208
|
+
}
|
|
209
|
+
if (ResumeThread(pi.hThread) == 0xFFFFFFFF)
|
|
210
|
+
{
|
|
211
|
+
int failure = Fail("ResumeThread");
|
|
212
|
+
TerminateJobObject(job, HelperFailure);
|
|
213
|
+
CloseHandle(pi.hThread);
|
|
214
|
+
CloseHandle(pi.hProcess);
|
|
215
|
+
CloseHandle(job);
|
|
216
|
+
return failure;
|
|
217
|
+
}
|
|
218
|
+
CloseHandle(pi.hThread);
|
|
219
|
+
|
|
220
|
+
if (WaitForSingleObject(pi.hProcess, INFINITE) != 0)
|
|
221
|
+
{
|
|
222
|
+
int failure = Fail("WaitForSingleObject");
|
|
223
|
+
TerminateJobObject(job, HelperFailure);
|
|
224
|
+
CloseHandle(pi.hProcess);
|
|
225
|
+
CloseHandle(job);
|
|
226
|
+
return failure;
|
|
227
|
+
}
|
|
228
|
+
uint code;
|
|
229
|
+
if (!GetExitCodeProcess(pi.hProcess, out code))
|
|
230
|
+
{
|
|
231
|
+
int failure = Fail("GetExitCodeProcess");
|
|
232
|
+
TerminateJobObject(job, HelperFailure);
|
|
233
|
+
CloseHandle(pi.hProcess);
|
|
234
|
+
CloseHandle(job);
|
|
235
|
+
return failure;
|
|
236
|
+
}
|
|
237
|
+
CloseHandle(pi.hProcess);
|
|
238
|
+
|
|
239
|
+
// Whatever the program left running dies with it.
|
|
240
|
+
TerminateJobObject(job, code);
|
|
241
|
+
CloseHandle(job);
|
|
242
|
+
return unchecked((int)code);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
`;
|
|
246
|
+
export class JobHelperError extends Error {
|
|
247
|
+
code;
|
|
248
|
+
constructor(code, message) {
|
|
249
|
+
super(message);
|
|
250
|
+
this.code = code;
|
|
251
|
+
this.name = "JobHelperError";
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
|
|
255
|
+
function helperDir() {
|
|
256
|
+
const local = process.env.LOCALAPPDATA;
|
|
257
|
+
return local ? path.join(local, "CarrierOS", "bin") : path.join(ConfigStore.resolveDir(), "bin");
|
|
258
|
+
}
|
|
259
|
+
/** The .NET Framework C# compiler, by absolute path under the Windows directory. */
|
|
260
|
+
function findCompiler() {
|
|
261
|
+
const windir = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
262
|
+
for (const fw of ["Framework64", "Framework"]) {
|
|
263
|
+
const csc = path.join(windir, "Microsoft.NET", fw, "v4.0.30319", "csc.exe");
|
|
264
|
+
if (fs.existsSync(csc))
|
|
265
|
+
return csc;
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Absolute path to a verified helper, compiling it if needed.
|
|
271
|
+
* Throws JobHelperError when containment cannot be provided — callers must then
|
|
272
|
+
* refuse to run the command rather than run it uncontained.
|
|
273
|
+
*/
|
|
274
|
+
export function ensureJobHelper() {
|
|
275
|
+
if (process.platform !== "win32") {
|
|
276
|
+
throw new JobHelperError("UNSUPPORTED_PLATFORM", "Command execution is only available on Windows for now.");
|
|
277
|
+
}
|
|
278
|
+
// Packaged builds ship the helper prebuilt beside the executable — no
|
|
279
|
+
// compiler, source or npm involved. Use it when present and intact.
|
|
280
|
+
const prebuilt = findPrebuiltHelper("cos-job-runner");
|
|
281
|
+
if (prebuilt) {
|
|
282
|
+
return prebuilt;
|
|
283
|
+
}
|
|
284
|
+
// A packaged build never compiles: no prebuilt helper means a damaged install.
|
|
285
|
+
if (isPackaged()) {
|
|
286
|
+
throw new JobHelperError("HELPER_UNAVAILABLE", `${damagedInstallMessage("cos-job-runner.exe")} Nothing was run.`);
|
|
287
|
+
}
|
|
288
|
+
const tag = sha256(JOB_HELPER_SOURCE).slice(0, 16);
|
|
289
|
+
const dir = helperDir();
|
|
290
|
+
const exe = path.join(dir, `cos-job-runner-${tag}.exe`);
|
|
291
|
+
const stamp = `${exe}.sha256`;
|
|
292
|
+
if (fs.existsSync(exe) && fs.existsSync(stamp)) {
|
|
293
|
+
if (sha256(fs.readFileSync(exe)) === fs.readFileSync(stamp, "utf8").trim()) {
|
|
294
|
+
return exe;
|
|
295
|
+
}
|
|
296
|
+
// Corrupt or tampered: rebuild rather than run it.
|
|
297
|
+
fs.rmSync(exe, { force: true });
|
|
298
|
+
fs.rmSync(stamp, { force: true });
|
|
299
|
+
}
|
|
300
|
+
const csc = findCompiler();
|
|
301
|
+
if (!csc) {
|
|
302
|
+
throw new JobHelperError("HELPER_UNAVAILABLE", "The .NET Framework C# compiler was not found, so commands cannot be contained. Nothing was run.");
|
|
303
|
+
}
|
|
304
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
305
|
+
const nonce = crypto.randomBytes(6).toString("hex");
|
|
306
|
+
const srcFile = path.join(dir, `cos-job-runner-${tag}-${nonce}.cs`);
|
|
307
|
+
const tmpExe = path.join(dir, `cos-job-runner-${tag}-${nonce}.exe`);
|
|
308
|
+
fs.writeFileSync(srcFile, JOB_HELPER_SOURCE, "utf8");
|
|
309
|
+
try {
|
|
310
|
+
execFileSync(csc, ["/nologo", "/target:exe", "/optimize+", `/out:${tmpExe}`, srcFile], {
|
|
311
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
312
|
+
windowsHide: true,
|
|
313
|
+
timeout: 60_000
|
|
314
|
+
});
|
|
315
|
+
const hash = sha256(fs.readFileSync(tmpExe));
|
|
316
|
+
fs.renameSync(tmpExe, exe);
|
|
317
|
+
fs.writeFileSync(stamp, hash, "utf8");
|
|
318
|
+
}
|
|
319
|
+
catch (err) {
|
|
320
|
+
fs.rmSync(tmpExe, { force: true });
|
|
321
|
+
const out = String(err.stdout ?? "").slice(0, 400);
|
|
322
|
+
throw new JobHelperError("HELPER_UNAVAILABLE", `The command helper could not be built. Nothing was run. ${out}`.trim());
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
fs.rmSync(srcFile, { force: true });
|
|
326
|
+
}
|
|
327
|
+
return exe;
|
|
328
|
+
}
|