@ulm0/gonogo 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +24 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-BqCn1SM7.js +50 -0
- package/dist/client/assets/index-KZtFVMJG.css +1 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/audited.js +133 -0
- package/dist/server/blackbox.js +261 -0
- package/dist/server/board.js +123 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/clearance.js +158 -0
- package/dist/server/cli.js +763 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +465 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/hangar.js +311 -0
- package/dist/server/home.js +520 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2642 -0
- package/dist/server/launcher.js +547 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logchart.js +58 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/massbudget.js +169 -0
- package/dist/server/mcp.js +228 -0
- package/dist/server/migrate.js +122 -0
- package/dist/server/missionlog.js +211 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +199 -0
- package/dist/server/recorder.js +176 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/relief.js +226 -0
- package/dist/server/rollout.js +172 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/telemetry.js +110 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1607 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +245 -0
- package/package.json +84 -3
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine Bay (docs/engine-bay-spec.md): how each agent CLI other than Claude Code and the custom command is started.
|
|
3
|
+
* Claude Code stays in launcher.ts as it was. An adapter names the arguments, the extra environment and the files it
|
|
4
|
+
* needs in the agent's own folder; what the hub does with the CLI (hooks or output activity, mail or none) is
|
|
5
|
+
* PROVIDER_INFO in protocol.ts. Nothing here touches the owner's project or the CLI's own home folder.
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { accessSync, constants as fsConstants, statSync } from 'node:fs';
|
|
9
|
+
import { delimiter, join } from 'node:path';
|
|
10
|
+
import { MCP_SERVER_NAME, PROVIDER_INFO, PROVIDERS } from '../shared/protocol.js';
|
|
11
|
+
import { ENGINE_VERSION_CHARS, ENGINE_VERSION_MS, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_PATH } from './constants.js';
|
|
12
|
+
/** Gemini CLI hook event to the hub's own hook event: the hub handles both CLIs with one set of rules. */
|
|
13
|
+
export const GEMINI_HOOKS = {
|
|
14
|
+
BeforeAgent: 'UserPromptSubmit',
|
|
15
|
+
BeforeTool: 'PreToolUse',
|
|
16
|
+
AfterTool: 'PostToolUse',
|
|
17
|
+
Notification: 'Notification',
|
|
18
|
+
AfterAgent: 'Stop',
|
|
19
|
+
};
|
|
20
|
+
export const GEMINI_SETTINGS_FILE = 'gemini-settings.json';
|
|
21
|
+
// shortcut: 'auto' is Claude Code's own classifier; the other CLIs have none, so it maps to their nearest mode (edits run, the rest asks). Give them their own mode if they ever ship one.
|
|
22
|
+
const GEMINI_MODES = { default: 'default', acceptEdits: 'auto_edit', auto: 'auto_edit', bypassPermissions: 'yolo' };
|
|
23
|
+
const CODEX_MODES = {
|
|
24
|
+
default: [],
|
|
25
|
+
acceptEdits: ['--full-auto'],
|
|
26
|
+
auto: ['--full-auto'],
|
|
27
|
+
bypassPermissions: ['--dangerously-bypass-approvals-and-sandbox'],
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Gemini CLI runs only command hooks, so each one runs this with `node -e`: it reads the hook input from stdin, forwards
|
|
31
|
+
* the fields the hub reads to the hook URL with the token from the token file, and prints the hub's answer (a Stop
|
|
32
|
+
* block becomes Gemini's AfterAgent block). The transcript path is not forwarded: Propellant reads only Claude's.
|
|
33
|
+
* Any failure prints `{}`, which lets Gemini go on. No single quote inside: it is passed in single quotes.
|
|
34
|
+
*/
|
|
35
|
+
export const HOOK_SHIM = [
|
|
36
|
+
'let d="";process.stdin.on("data",c=>d+=c).on("end",async()=>{try{',
|
|
37
|
+
'const i=JSON.parse(d||"{}"),b={};',
|
|
38
|
+
'for(const k of ["prompt","tool_name","tool_input","notification_type","message"])if(i[k]!==undefined)b[k]=i[k];',
|
|
39
|
+
'const t=require("fs").readFileSync(process.argv[2],"utf8").trim();',
|
|
40
|
+
'const r=await fetch(process.argv[1],{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},',
|
|
41
|
+
`body:JSON.stringify(b),signal:AbortSignal.timeout(${HOOK_TIMEOUT_S * 1000})});`,
|
|
42
|
+
'process.stdout.write(r.ok?await r.text():"{}")}catch{process.stdout.write("{}")}})',
|
|
43
|
+
].join('');
|
|
44
|
+
/** One shell word: Gemini runs a hook command through the shell. */
|
|
45
|
+
export const shellQuote = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
|
|
46
|
+
export function buildGeminiSettings(ctx, node = process.execPath) {
|
|
47
|
+
const hooks = {};
|
|
48
|
+
for (const [event, ours] of Object.entries(GEMINI_HOOKS)) {
|
|
49
|
+
const url = `${ctx.hubUrl}${HOOK_PATH_PREFIX}${ctx.name}/${ours}`;
|
|
50
|
+
const command = [node, '-e', HOOK_SHIM, url, ctx.tokenFile].map(shellQuote).join(' ');
|
|
51
|
+
// Gemini's timeout is in milliseconds; the shim gives up one second earlier and answers {}.
|
|
52
|
+
hooks[event] = [{ hooks: [{ type: 'command', command, timeout: (HOOK_TIMEOUT_S + 1) * 1000 }] }];
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
// trust: the gonogo tools run without a confirmation, like the --allowedTools of a Claude agent.
|
|
56
|
+
// Payload servers come first and carry no `trust`: Gemini asks before their tools run. Its schema takes the mcp.json fields as they are.
|
|
57
|
+
mcpServers: { ...ctx.servers, [MCP_SERVER_NAME]: { httpUrl: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: 'Bearer ${GONOGO_TOKEN}' }, trust: true } },
|
|
58
|
+
hooks,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** The MCP entry for a CLI that reads Claude's mcp.json shape but may not expand variables: the token is written in. */
|
|
62
|
+
function mcpJson(ctx, extra = {}) {
|
|
63
|
+
const server = { type: 'http', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: `Bearer ${ctx.token}` }, ...extra };
|
|
64
|
+
return JSON.stringify({ mcpServers: { ...ctx.servers, [MCP_SERVER_NAME]: server } }, null, 2);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Every start of these CLIs is a new session: none of them is resumed by gonogo.
|
|
68
|
+
* shortcut: a restart loses the conversation, upgrade when a CLI's resume by id is checked against a real run.
|
|
69
|
+
*/
|
|
70
|
+
export function buildProviderStart(provider, ctx) {
|
|
71
|
+
const file = (name) => join(ctx.agentDir, name);
|
|
72
|
+
// Every engine with a model setting takes `--model <name>` (PROVIDER_INFO.model); the name is one argument, never a shell word.
|
|
73
|
+
const model = ctx.model ? ['--model', ctx.model] : [];
|
|
74
|
+
switch (provider) {
|
|
75
|
+
case 'gemini':
|
|
76
|
+
// GEMINI_CLI_SYSTEM_SETTINGS_PATH is read before the owner's ~/.gemini settings and wins over them; their login stays.
|
|
77
|
+
return {
|
|
78
|
+
args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), ...model, '--prompt-interactive', ctx.roleText],
|
|
79
|
+
env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: file(GEMINI_SETTINGS_FILE) },
|
|
80
|
+
files: { [GEMINI_SETTINGS_FILE]: JSON.stringify(buildGeminiSettings(ctx), null, 2) },
|
|
81
|
+
};
|
|
82
|
+
case 'codex':
|
|
83
|
+
// -c overrides config.toml for this run only, so CODEX_HOME (and the owner's login in it) stays as it is.
|
|
84
|
+
return {
|
|
85
|
+
args: [
|
|
86
|
+
'-c',
|
|
87
|
+
`mcp_servers.${MCP_SERVER_NAME}.url=${JSON.stringify(`${ctx.hubUrl}${MCP_PATH}`)}`,
|
|
88
|
+
'-c',
|
|
89
|
+
`mcp_servers.${MCP_SERVER_NAME}.bearer_token_env_var="GONOGO_TOKEN"`,
|
|
90
|
+
...CODEX_MODES[ctx.mode],
|
|
91
|
+
...model,
|
|
92
|
+
ctx.roleText,
|
|
93
|
+
],
|
|
94
|
+
env: {},
|
|
95
|
+
files: {},
|
|
96
|
+
};
|
|
97
|
+
case 'opencode':
|
|
98
|
+
// OPENCODE_CONFIG is merged over the owner's config; {env:...} is opencode's own substitution.
|
|
99
|
+
return {
|
|
100
|
+
args: ['--prompt', ctx.roleText],
|
|
101
|
+
env: { OPENCODE_CONFIG: file('opencode.json') },
|
|
102
|
+
files: {
|
|
103
|
+
'opencode.json': JSON.stringify({ mcp: { [MCP_SERVER_NAME]: { type: 'remote', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: 'Bearer {env:GONOGO_TOKEN}' }, enabled: true } } }, null, 2),
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
case 'kimi':
|
|
107
|
+
return { args: ['--mcp-config-file', file('kimi-mcp.json'), ...model], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
|
|
108
|
+
case 'copilot':
|
|
109
|
+
return { args: ['--additional-mcp-config', `@${file('copilot-mcp.json')}`], env: {}, files: { 'copilot-mcp.json': mcpJson(ctx, { tools: ['*'] }) } };
|
|
110
|
+
case 'pi':
|
|
111
|
+
// pi reads MCP servers only from its own files, so it gets no gonogo tools: the role alone, without the preamble about them.
|
|
112
|
+
return { args: ['--append-system-prompt', ctx.role, ...model], env: {}, files: {} };
|
|
113
|
+
case 'cursor':
|
|
114
|
+
return { args: model, env: {}, files: {} };
|
|
115
|
+
case 'qwen':
|
|
116
|
+
case 'grok':
|
|
117
|
+
case 'crush':
|
|
118
|
+
// No documented per-session MCP config and no checked way to pass a role: a terminal with a lamp, started by name.
|
|
119
|
+
return { args: [], env: {}, files: {} };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** The path of `name` when it is an executable file in one of the PATH directories, else null. */
|
|
123
|
+
export function findOnPath(name, pathVar) {
|
|
124
|
+
if (name === '')
|
|
125
|
+
return null;
|
|
126
|
+
for (const dir of (pathVar ?? '').split(delimiter)) {
|
|
127
|
+
if (dir === '')
|
|
128
|
+
continue;
|
|
129
|
+
try {
|
|
130
|
+
const file = join(dir, name);
|
|
131
|
+
accessSync(file, fsConstants.X_OK);
|
|
132
|
+
if (statSync(file).isFile())
|
|
133
|
+
return file;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
// not in this directory
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
/** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
|
|
142
|
+
export const onPath = (name, pathVar) => findOnPath(name, pathVar) !== null;
|
|
143
|
+
// A terminal sequence (colour, title) whole, then what is left of control, C1 and text-direction characters: the line goes to a terminal and a web page.
|
|
144
|
+
const TERMINAL_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?)/g;
|
|
145
|
+
const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
|
|
146
|
+
/** Pad Check: the first line a program prints for `--version`, with terminal sequences and control characters taken out and cut short. */
|
|
147
|
+
export const versionLine = (output) => {
|
|
148
|
+
const line = output.split('\n').map((l) => l.replace(TERMINAL_SEQUENCE, '').replace(CONTROL, '').trim()).find((l) => l !== '');
|
|
149
|
+
return line === undefined ? null : line.slice(0, ENGINE_VERSION_CHARS);
|
|
150
|
+
};
|
|
151
|
+
/** Versions already read, by path and modification time: a program that was updated is asked again, one that failed is asked every time. */
|
|
152
|
+
const versionCache = new Map();
|
|
153
|
+
/**
|
|
154
|
+
* `<file> --version`, no shell, a few seconds at most, and an environment of PATH, HOME and LANG only, so that no key or token of
|
|
155
|
+
* gonogo's environment reaches a program that is merely asked its version. null when it did not answer or printed nothing.
|
|
156
|
+
*/
|
|
157
|
+
async function versionOf(file, env) {
|
|
158
|
+
const key = `${file}\0${statSync(file).mtimeMs}`;
|
|
159
|
+
const known = versionCache.get(key);
|
|
160
|
+
if (known !== undefined)
|
|
161
|
+
return known;
|
|
162
|
+
const output = await new Promise((done) => {
|
|
163
|
+
execFile(file, ['--version'], { timeout: ENGINE_VERSION_MS, maxBuffer: 64 * 1024, env: { PATH: env.PATH, HOME: env.HOME, LANG: env.LANG, NO_COLOR: '1' } }, (error, stdout) => done(error === null ? stdout : ''));
|
|
164
|
+
});
|
|
165
|
+
const line = versionLine(output);
|
|
166
|
+
if (line !== null)
|
|
167
|
+
versionCache.set(key, line);
|
|
168
|
+
return line;
|
|
169
|
+
}
|
|
170
|
+
/** Pad Check: every engine but the custom command, where it was found and what it calls itself. Runs nothing but `--version`; never installs. */
|
|
171
|
+
export function checkEngines(env) {
|
|
172
|
+
return Promise.all(PROVIDERS.filter((provider) => provider !== 'custom').map(async (provider) => {
|
|
173
|
+
const { label, bin, install, docs } = PROVIDER_INFO[provider];
|
|
174
|
+
const path = findOnPath(bin, env.PATH);
|
|
175
|
+
return { provider, label, bin, path, version: path === null ? null : await versionOf(path, env).catch(() => null), install, docs };
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
/** What `gonogo doctor` prints: one line per engine, and under a missing one the vendor's install command to copy. */
|
|
179
|
+
export function formatDoctor(checks, agentCmd) {
|
|
180
|
+
const lines = ['gonogo doctor: which agent CLIs are on the PATH', ''];
|
|
181
|
+
for (const check of checks) {
|
|
182
|
+
if (check.path !== null) {
|
|
183
|
+
lines.push(`ok ${check.label} (${check.bin}) ${check.version ?? 'no version printed'} ${check.path}`);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
lines.push(`-- ${check.label} (${check.bin}) not found`);
|
|
187
|
+
lines.push(check.install === null ? ` no install command was checked; see ${check.docs}` : ` install: ${check.install}`);
|
|
188
|
+
if (check.install !== null)
|
|
189
|
+
lines.push(` docs: ${check.docs}`);
|
|
190
|
+
}
|
|
191
|
+
if (agentCmd !== null)
|
|
192
|
+
lines.push('', `GONOGO_AGENT_CMD is set (${agentCmd}): it replaces claude.`);
|
|
193
|
+
lines.push('', 'gonogo never runs an install command: copy the one you want.');
|
|
194
|
+
return lines.join('\n') + '\n';
|
|
195
|
+
}
|
|
196
|
+
/** ServerInfo.installed: what the hire form lists first. GONOGO_AGENT_CMD stands in for claude. */
|
|
197
|
+
export function installedProviders(path, agentCmd) {
|
|
198
|
+
return PROVIDERS.filter((p) => p === 'custom' || (p === 'claude' && agentCmd) || onPath(PROVIDER_INFO[p].bin, path));
|
|
199
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recorder (docs/recorder-spec.md): git for one agent's folder, or its Clean Room worktree, for the Director's browser.
|
|
3
|
+
* Status, a diff (read-only), the last 50 commits, and a commit of all changes or of what is staged, with a message the
|
|
4
|
+
* Director wrote and the author from his own git config. No push, pull, checkout, reset or any other command. Git runs
|
|
5
|
+
* through execFile with an argument list, hooks off, no prompt, a time limit and an output cap.
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { realpath } from 'node:fs/promises';
|
|
9
|
+
import { RECORDER_LOG_MAX, RECORDER_MESSAGE_MAX_CHARS, RECORDER_SCOPES } from '../shared/protocol.js';
|
|
10
|
+
import { GIT_BIN } from './constants.js';
|
|
11
|
+
import { HubError } from './hub.js';
|
|
12
|
+
import { inside, pathParts } from './hangar.js';
|
|
13
|
+
export const RECORDER_READ_MS = 15_000;
|
|
14
|
+
export const RECORDER_WRITE_MS = 30_000;
|
|
15
|
+
/** Output of a read: status and log are cut at 1 MiB, a diff at 256 KiB. */
|
|
16
|
+
export const RECORDER_LIST_CAP = 1024 * 1024;
|
|
17
|
+
export const RECORDER_DIFF_CAP = 256 * 1024;
|
|
18
|
+
export const RECORDER_FILES_MAX = 1000;
|
|
19
|
+
/** Hooks off, and the programs a repository's own config could name for a read (the file system monitor, an external diff) off. */
|
|
20
|
+
const BASE_ARGS = ['--literal-pathspecs', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.quotepath=false'];
|
|
21
|
+
/** What git may see of the environment: no GIT_DIR or GIT_WORK_TREE or GIT_EXTERNAL_DIFF from gonogo's own, no credential. */
|
|
22
|
+
const KEEP_ENV = ['PATH', 'HOME', 'USER', 'LOGNAME', 'XDG_CONFIG_HOME', 'TMPDIR'];
|
|
23
|
+
class GitFailure extends Error {
|
|
24
|
+
status;
|
|
25
|
+
constructor(status, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.status = status;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
31
|
+
export function createRecorder(roots, env) {
|
|
32
|
+
const gitEnv = { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' };
|
|
33
|
+
for (const key of KEEP_ENV) {
|
|
34
|
+
const value = env[key];
|
|
35
|
+
if (value !== undefined)
|
|
36
|
+
gitEnv[key] = value;
|
|
37
|
+
}
|
|
38
|
+
/** Runs git in the root. A call over its time is stopped with SIGTERM, not SIGKILL: git then removes its own index.lock, which a kill would leave to block every later add and commit. Output over `cap` is cut and `truncated` says so; a failure is a GitFailure with the first line git printed on stderr. */
|
|
39
|
+
function git(at, args, cap, timeout) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
execFile(GIT_BIN, [...BASE_ARGS, ...args], { cwd: at.root, env: gitEnv, timeout, killSignal: 'SIGTERM', maxBuffer: cap + 1, encoding: 'utf8' }, (error, stdout, stderr) => {
|
|
42
|
+
if (error === null)
|
|
43
|
+
return resolve({ out: stdout.slice(0, cap), truncated: stdout.length > cap });
|
|
44
|
+
const code = error.code;
|
|
45
|
+
if (code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
|
|
46
|
+
return resolve({ out: String(stdout).slice(0, cap), truncated: true });
|
|
47
|
+
if (code === 'ENOENT')
|
|
48
|
+
return reject(new HubError('unavailable', 'git was not found on PATH'));
|
|
49
|
+
if (error.killed)
|
|
50
|
+
return reject(new HubError('unavailable', 'git did not answer in time'));
|
|
51
|
+
const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? `git exited with ${String(code)}`;
|
|
52
|
+
reject(new GitFailure(typeof code === 'number' || typeof code === 'string' ? code : null, line.slice(0, 300)));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** The repository at the root, or why not. It must be the top of a repository, and gonogo's own folder must not be inside it. */
|
|
57
|
+
async function repoProblem(at) {
|
|
58
|
+
let top;
|
|
59
|
+
try {
|
|
60
|
+
top = (await git(at, ['rev-parse', '--show-toplevel'], 4096, RECORDER_READ_MS)).out.trim();
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (e instanceof GitFailure)
|
|
64
|
+
return /not a git repository/i.test(e.message) ? 'this folder is not in a git repository' : `git said: ${e.message}`;
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
if ((await realpath(top).catch(() => top)) !== at.root)
|
|
68
|
+
return `this folder is inside the repository at ${top}: the Recorder works at the top of a repository`;
|
|
69
|
+
if (inside(at.root, at.home))
|
|
70
|
+
return 'gonogo\'s own folder is inside this repository, and the Recorder will not commit it';
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
async function author(at) {
|
|
74
|
+
const get = (key) => git(at, ['config', '--get', key], 1024, RECORDER_READ_MS).then((r) => r.out.trim(), (e) => {
|
|
75
|
+
if (e instanceof GitFailure)
|
|
76
|
+
return ''; // exit 1: the key is not set
|
|
77
|
+
throw e;
|
|
78
|
+
});
|
|
79
|
+
const [name, email] = await Promise.all([get('user.name'), get('user.email')]);
|
|
80
|
+
return name === '' || email === '' ? null : { name, email };
|
|
81
|
+
}
|
|
82
|
+
async function ready(name) {
|
|
83
|
+
const at = await roots(name);
|
|
84
|
+
const problem = await repoProblem(at);
|
|
85
|
+
if (problem !== null)
|
|
86
|
+
throw new HubError('conflict', problem);
|
|
87
|
+
return at;
|
|
88
|
+
}
|
|
89
|
+
async function lastCommits(at, count) {
|
|
90
|
+
let out;
|
|
91
|
+
try {
|
|
92
|
+
out = (await git(at, ['log', '-n', String(count), '--no-color', '--no-decorate', '-z', '--format=%H%x1f%an%x1f%at%x1f%s'], RECORDER_LIST_CAP, RECORDER_READ_MS)).out;
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
if (e instanceof GitFailure && /does not have any commits yet/.test(e.message))
|
|
96
|
+
return [];
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
return out.split('\0').filter((r) => r !== '').map((record) => {
|
|
100
|
+
const [hash = '', who = '', at2 = '0', ...subject] = record.split('\x1f');
|
|
101
|
+
return { hash, author: who.slice(0, 200), at: Number(at2) * 1000, subject: subject.join('\x1f').slice(0, 300) };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
async status(name) {
|
|
106
|
+
const at = await roots(name);
|
|
107
|
+
const problem = await repoProblem(at);
|
|
108
|
+
if (problem !== null)
|
|
109
|
+
return { repo: false, reason: problem };
|
|
110
|
+
const { out } = await git(at, ['status', '--porcelain=v1', '-z', '--branch', '--untracked-files=normal'], RECORDER_LIST_CAP, RECORDER_READ_MS);
|
|
111
|
+
const records = out.split('\0');
|
|
112
|
+
const files = [];
|
|
113
|
+
let branch = '';
|
|
114
|
+
for (let i = 0; i < records.length; i += 1) {
|
|
115
|
+
const record = records[i] ?? '';
|
|
116
|
+
if (record.startsWith('## '))
|
|
117
|
+
branch = record.slice(3, 203);
|
|
118
|
+
else if (record.length > 3) {
|
|
119
|
+
const file = { path: record.slice(3), index: record[0] ?? ' ', tree: record[1] ?? ' ' };
|
|
120
|
+
if (file.index === 'R' || file.index === 'C')
|
|
121
|
+
file.from = records[(i += 1)];
|
|
122
|
+
files.push(file);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { repo: true, branch, files: files.slice(0, RECORDER_FILES_MAX), more: Math.max(0, files.length - RECORDER_FILES_MAX), author: await author(at) };
|
|
126
|
+
},
|
|
127
|
+
async diff(name, raw, staged) {
|
|
128
|
+
const parts = pathParts(raw ?? '');
|
|
129
|
+
const at = await ready(name);
|
|
130
|
+
const args = ['diff', '--no-ext-diff', '--no-textconv', '--no-color', ...(staged ? ['--cached'] : []), '--', ...(parts.length === 0 ? [] : [parts.join('/')])];
|
|
131
|
+
const { out, truncated } = await git(at, args, RECORDER_DIFF_CAP, RECORDER_READ_MS);
|
|
132
|
+
return { diff: out, truncated };
|
|
133
|
+
},
|
|
134
|
+
async log(name) {
|
|
135
|
+
return lastCommits(await ready(name), RECORDER_LOG_MAX);
|
|
136
|
+
},
|
|
137
|
+
async commit(name, input) {
|
|
138
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input))
|
|
139
|
+
throw bad('the body must be an object');
|
|
140
|
+
const { message, scope } = input;
|
|
141
|
+
if (typeof message !== 'string' || message.trim() === '')
|
|
142
|
+
throw bad('write a message for the commit', 'message');
|
|
143
|
+
if (message.length > RECORDER_MESSAGE_MAX_CHARS)
|
|
144
|
+
throw bad(`the message is longer than ${RECORDER_MESSAGE_MAX_CHARS} characters`, 'message');
|
|
145
|
+
if (message.includes('\0'))
|
|
146
|
+
throw bad('the message has a NUL character', 'message');
|
|
147
|
+
if (scope !== 'all' && scope !== 'staged')
|
|
148
|
+
throw bad(`scope must be one of ${RECORDER_SCOPES.join(', ')}`, 'scope');
|
|
149
|
+
const at = await ready(name);
|
|
150
|
+
if ((await author(at)) === null) {
|
|
151
|
+
throw new HubError('conflict', 'git has no author: set user.name and user.email (git config --global user.name "Your Name"), then commit again', 'author');
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
if (scope === 'all')
|
|
155
|
+
await git(at, ['add', '-A'], 4096, RECORDER_WRITE_MS);
|
|
156
|
+
const staged = await git(at, ['diff', '--cached', '--quiet', '--no-ext-diff'], 4096, RECORDER_READ_MS).then(() => false, (e) => {
|
|
157
|
+
if (e instanceof GitFailure && e.status === 1)
|
|
158
|
+
return true; // exit 1: the index differs from HEAD
|
|
159
|
+
throw e;
|
|
160
|
+
});
|
|
161
|
+
if (!staged)
|
|
162
|
+
throw new HubError('conflict', scope === 'all' ? 'nothing to commit: the folder has no changes' : 'nothing is staged', 'scope');
|
|
163
|
+
await git(at, ['-c', 'user.useConfigOnly=true', 'commit', '-m', message], 4096, RECORDER_WRITE_MS);
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
if (e instanceof GitFailure)
|
|
167
|
+
throw new HubError('conflict', `git refused: ${e.message}`);
|
|
168
|
+
throw e;
|
|
169
|
+
}
|
|
170
|
+
const [commit] = await lastCommits(at, 1);
|
|
171
|
+
if (commit === undefined)
|
|
172
|
+
throw new HubError('internal', 'the commit was made but git does not list it');
|
|
173
|
+
return { commit };
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|