@ignitionai/cogitator 0.5.1 → 0.5.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/CHANGELOG.md +69 -0
- package/LICENSE +21 -0
- package/README.md +80 -56
- package/dist/extensions/index.js +66 -29
- package/dist/src/app-updates.js +15 -0
- package/dist/src/auth-cli.js +18 -8
- package/dist/src/auth-http.js +13 -3
- package/dist/src/auth-state.js +41 -6
- package/dist/src/board.js +3 -1
- package/dist/src/browser-http.js +143 -0
- package/dist/src/classic-configuration.js +12 -4
- package/dist/src/cli.js +29 -2
- package/dist/src/config.js +10 -0
- package/dist/src/cron.js +91 -15
- package/dist/src/db.js +55 -3
- package/dist/src/durable/approvals.js +17 -2
- package/dist/src/durable/effect-gateway.js +23 -16
- package/dist/src/durable/manager.js +13 -4
- package/dist/src/durable/mission-runtime.js +204 -46
- package/dist/src/durable/recovery.js +37 -0
- package/dist/src/durable/workers.js +22 -14
- package/dist/src/execution/confinement.js +2 -1
- package/dist/src/execution/worker-supervisor.js +222 -0
- package/dist/src/git-import.js +187 -0
- package/dist/src/github-login.js +101 -0
- package/dist/src/history.js +6 -1
- package/dist/src/host-pi.js +9 -6
- package/dist/src/json-files.js +7 -4
- package/dist/src/machine-metrics.js +49 -0
- package/dist/src/machine-types.js +1 -0
- package/dist/src/mcp-cli.js +63 -0
- package/dist/src/mcp-http.js +164 -0
- package/dist/src/mcp-oauth.js +502 -0
- package/dist/src/mcp-server.js +6 -136
- package/dist/src/mcp-tokens.js +104 -0
- package/dist/src/mcp-tools.js +264 -0
- package/dist/src/native-auth.js +9 -2
- package/dist/src/packages.js +190 -0
- package/dist/src/paths.js +1 -0
- package/dist/src/pi-child.js +180 -0
- package/dist/src/pi-rpc-wrap.js +84 -0
- package/dist/src/pool.js +58 -7
- package/dist/src/project-setup.js +63 -0
- package/dist/src/provider-login.js +72 -13
- package/dist/src/reap-orphans.js +138 -0
- package/dist/src/registry.js +66 -43
- package/dist/src/schemas.js +19 -4
- package/dist/src/server-compat.js +173 -0
- package/dist/src/server-identity.js +69 -0
- package/dist/src/server.js +534 -41
- package/dist/src/shared-browser.js +357 -0
- package/dist/src/skills-import.js +13 -4
- package/dist/src/skills-upload.js +68 -0
- package/dist/src/spawner.js +20 -4
- package/dist/src/subagents.js +242 -0
- package/dist/src/team-queue.js +262 -0
- package/package.json +8 -3
- package/web/dist/assets/{BrandLogo3D-BvZPXohP.js → BrandLogo3D-CHGXwTbZ.js} +1 -1
- package/web/dist/assets/index-DGLkhrE7.css +1 -0
- package/web/dist/assets/index-P0WoXBgX.js +84 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-7Dyl-4v7.css +0 -1
- package/web/dist/assets/index-CdqzcBU-.js +0 -83
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
import { existsSync, realpathSync } from "node:fs";
|
|
12
12
|
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
13
13
|
import { authenticationRequired } from "../config.js";
|
|
14
|
-
|
|
14
|
+
/** `path` sous `root` (formes déjà canonicalisées des deux côtés). */
|
|
15
|
+
export function isInside(path, root) {
|
|
15
16
|
return path === root || path.startsWith(root + sep);
|
|
16
17
|
}
|
|
17
18
|
/**
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contrôleur de cycle de vie des workers (ticket #47 / IGN-184) : inspect,
|
|
3
|
+
* stop et waitForExit ne s'appuient que sur une identité persistée et
|
|
4
|
+
* re-vérifiée. Un accusé d'arrêt, un objet manquant, un PID réutilisé ou une
|
|
5
|
+
* inspection impossible ne sont jamais une preuve de sortie. Aucun signal n'est
|
|
6
|
+
* envoyé si l'identité n'est pas la nôtre.
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
9
|
+
import { classifyWorker, pidAlive, } from "../durable/workers.js";
|
|
10
|
+
function identityFieldsMatch(expected, observed) {
|
|
11
|
+
return (expected.workerId === observed.workerId &&
|
|
12
|
+
expected.executionId === observed.executionId &&
|
|
13
|
+
expected.missionId === observed.missionId &&
|
|
14
|
+
expected.workspaceDir === observed.workspaceDir &&
|
|
15
|
+
expected.backendId === observed.backendId &&
|
|
16
|
+
expected.immutableHandle === observed.immutableHandle);
|
|
17
|
+
}
|
|
18
|
+
export function intentMatchesIdentity(intent, identity) {
|
|
19
|
+
return (intent.workerId === identity.workerId &&
|
|
20
|
+
intent.executionId === identity.executionId &&
|
|
21
|
+
intent.missionId === identity.missionId &&
|
|
22
|
+
intent.workspaceDir === identity.workspaceDir &&
|
|
23
|
+
intent.backendId === identity.backendId &&
|
|
24
|
+
intent.specBinding === identity.workspaceDir);
|
|
25
|
+
}
|
|
26
|
+
function inspectIsUnsafe(observation) {
|
|
27
|
+
switch (observation.kind) {
|
|
28
|
+
case "running":
|
|
29
|
+
return false;
|
|
30
|
+
case "missing":
|
|
31
|
+
return false;
|
|
32
|
+
case "pid_reuse":
|
|
33
|
+
case "identity_mismatch":
|
|
34
|
+
case "unavailable":
|
|
35
|
+
return true;
|
|
36
|
+
default: {
|
|
37
|
+
const exhaustive = observation;
|
|
38
|
+
return exhaustive;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class WorkerSupervisor {
|
|
43
|
+
backend;
|
|
44
|
+
constructor(backend) {
|
|
45
|
+
this.backend = backend;
|
|
46
|
+
}
|
|
47
|
+
async inspect(record) {
|
|
48
|
+
if (!record.identity)
|
|
49
|
+
return { kind: "unavailable", error: "identité absente" };
|
|
50
|
+
if (record.identity.backendId !== this.backend.id) {
|
|
51
|
+
return { kind: "identity_mismatch", observed: { backendId: this.backend.id } };
|
|
52
|
+
}
|
|
53
|
+
const observation = await this.backend.inspect(record.identity);
|
|
54
|
+
if (observation.kind === "running" && !identityFieldsMatch(record.identity, observation.identity)) {
|
|
55
|
+
return { kind: "identity_mismatch", observed: observation.identity };
|
|
56
|
+
}
|
|
57
|
+
return observation;
|
|
58
|
+
}
|
|
59
|
+
async classify(record) {
|
|
60
|
+
if (record.exitProof?.writingStopped)
|
|
61
|
+
return { kind: "resolved", record };
|
|
62
|
+
if (record.intent && !record.identity) {
|
|
63
|
+
return { kind: "attention", record, reason: "intent_unbound" };
|
|
64
|
+
}
|
|
65
|
+
const observation = await this.inspect(record);
|
|
66
|
+
return classifyWorker(record, observation);
|
|
67
|
+
}
|
|
68
|
+
async stop(record) {
|
|
69
|
+
const observation = await this.inspect(record);
|
|
70
|
+
if (observation.kind !== "running" || inspectIsUnsafe(observation)) {
|
|
71
|
+
return { kind: "refused", reason: observation.kind };
|
|
72
|
+
}
|
|
73
|
+
return this.backend.stop(observation.identity);
|
|
74
|
+
}
|
|
75
|
+
async waitForExit(record) {
|
|
76
|
+
const observation = await this.inspect(record);
|
|
77
|
+
if (inspectIsUnsafe(observation) || !record.identity) {
|
|
78
|
+
return { kind: "refused", reason: observation.kind };
|
|
79
|
+
}
|
|
80
|
+
if (observation.kind !== "running")
|
|
81
|
+
return { kind: "not_exited" };
|
|
82
|
+
return this.backend.waitForExit(record.identity);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Stop then wait. Missing after a verified running inspect of this identity
|
|
86
|
+
* is cessation of that incarnation — not a missing object found cold.
|
|
87
|
+
*/
|
|
88
|
+
async stopThenWait(record) {
|
|
89
|
+
const before = await this.inspect(record);
|
|
90
|
+
if (before.kind !== "running" || !record.identity) {
|
|
91
|
+
return { kind: "refused", reason: before.kind };
|
|
92
|
+
}
|
|
93
|
+
const stopped = await this.stop(record);
|
|
94
|
+
if (stopped.kind !== "acknowledged")
|
|
95
|
+
return { kind: "refused", reason: stopped.reason };
|
|
96
|
+
const after = await this.inspect(record);
|
|
97
|
+
if (inspectIsUnsafe(after))
|
|
98
|
+
return { kind: "refused", reason: after.kind };
|
|
99
|
+
if (after.kind === "missing")
|
|
100
|
+
return { kind: "exited", writingStopped: true };
|
|
101
|
+
return this.backend.waitForExit(record.identity);
|
|
102
|
+
}
|
|
103
|
+
async assertSafeToReplace(records) {
|
|
104
|
+
for (const record of records) {
|
|
105
|
+
const classified = await this.classify(record);
|
|
106
|
+
if (classified.kind !== "resolved") {
|
|
107
|
+
throw new Error(`remplacement refusé avant preuve de sortie: worker ${record.id} (${classified.kind})`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async reconcileCreation(record) {
|
|
112
|
+
if (record.identity)
|
|
113
|
+
return { kind: "created", record };
|
|
114
|
+
if (!record.intent) {
|
|
115
|
+
return { kind: "attention", record, reason: "intent_unbound" };
|
|
116
|
+
}
|
|
117
|
+
const found = await this.backend.discover(record.intent.correlation);
|
|
118
|
+
switch (found.kind) {
|
|
119
|
+
case "one":
|
|
120
|
+
if (!intentMatchesIdentity(record.intent, found.identity)) {
|
|
121
|
+
return { kind: "attention", record, reason: "identity_mismatch" };
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
kind: "created",
|
|
125
|
+
record: {
|
|
126
|
+
...record,
|
|
127
|
+
identity: found.identity,
|
|
128
|
+
pid: found.identity.observationalPid,
|
|
129
|
+
lifecycle: "created",
|
|
130
|
+
revision: (record.revision ?? 0) + 1,
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
case "none":
|
|
134
|
+
return { kind: "attention", record, reason: "intent_unbound" };
|
|
135
|
+
case "ambiguous":
|
|
136
|
+
return { kind: "attention", record, reason: "ambiguous_create" };
|
|
137
|
+
default: {
|
|
138
|
+
const exhaustive = found;
|
|
139
|
+
return exhaustive;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function readProcessStarttime(pid) {
|
|
145
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
146
|
+
return undefined;
|
|
147
|
+
try {
|
|
148
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
149
|
+
const close = stat.lastIndexOf(")");
|
|
150
|
+
if (close < 0)
|
|
151
|
+
return undefined;
|
|
152
|
+
const rest = stat.slice(close + 2).split(" ");
|
|
153
|
+
return rest[19];
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
if (err.code === "ENOENT")
|
|
157
|
+
return undefined;
|
|
158
|
+
throw err;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export class ProcessWorkerBackend {
|
|
162
|
+
id = "process";
|
|
163
|
+
async inspect(identity) {
|
|
164
|
+
if (!existsSync("/proc/self/stat")) {
|
|
165
|
+
return { kind: "unavailable", error: "/proc indisponible" };
|
|
166
|
+
}
|
|
167
|
+
let starttime;
|
|
168
|
+
try {
|
|
169
|
+
starttime = readProcessStarttime(identity.observationalPid);
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
return { kind: "unavailable", error: err.message };
|
|
173
|
+
}
|
|
174
|
+
if (starttime === undefined)
|
|
175
|
+
return { kind: "missing" };
|
|
176
|
+
if (starttime !== identity.starttime)
|
|
177
|
+
return { kind: "pid_reuse" };
|
|
178
|
+
if (!pidAlive(identity.observationalPid))
|
|
179
|
+
return { kind: "missing" };
|
|
180
|
+
return { kind: "running", identity };
|
|
181
|
+
}
|
|
182
|
+
async stop(identity) {
|
|
183
|
+
const observation = await this.inspect(identity);
|
|
184
|
+
if (observation.kind !== "running")
|
|
185
|
+
return { kind: "refused", reason: observation.kind };
|
|
186
|
+
try {
|
|
187
|
+
process.kill(identity.observationalPid, "SIGTERM");
|
|
188
|
+
return { kind: "acknowledged" };
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
return { kind: "refused", reason: err.message };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async waitForExit(identity) {
|
|
195
|
+
const first = await this.inspect(identity);
|
|
196
|
+
if (first.kind !== "running")
|
|
197
|
+
return { kind: "not_exited" };
|
|
198
|
+
const deadline = Date.now() + 10_000;
|
|
199
|
+
while (Date.now() < deadline) {
|
|
200
|
+
const current = await this.inspect(identity);
|
|
201
|
+
switch (current.kind) {
|
|
202
|
+
case "missing":
|
|
203
|
+
return { kind: "exited", writingStopped: true };
|
|
204
|
+
case "running":
|
|
205
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
206
|
+
break;
|
|
207
|
+
case "pid_reuse":
|
|
208
|
+
case "identity_mismatch":
|
|
209
|
+
case "unavailable":
|
|
210
|
+
return { kind: "refused", reason: current.kind };
|
|
211
|
+
default: {
|
|
212
|
+
const exhaustive = current;
|
|
213
|
+
return exhaustive;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { kind: "not_exited" };
|
|
218
|
+
}
|
|
219
|
+
async discover(_correlation) {
|
|
220
|
+
return { kind: "none" };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { isInside } from "./execution/confinement.js";
|
|
5
|
+
import { parseGitHubRepo } from "./skills-import.js";
|
|
6
|
+
// shortcut: clone borné à 25 s pour finir sous le requestTimeout 30 s du serveur en
|
|
7
|
+
// mode auth ; à revoir si l'import de gros dépôts devient un cas d'usage supporté
|
|
8
|
+
// (tâche asynchrone hors requête) ou si le requestTimeout augmente.
|
|
9
|
+
const CLONE_TIMEOUT_MS = 25_000;
|
|
10
|
+
/** true si l'URL embarque des identifiants (`user:token@` sur tout schéma, `token@` sur
|
|
11
|
+
* https, utilisateur scp-like autre que `git` — ex. `ghp_…@hôte:o/r`, R3) — git les écrirait
|
|
12
|
+
* en clair dans `.git/config` du clone ; D1 veut les identifiants du poste, jamais dans
|
|
13
|
+
* l'URL. `git@hote:o/r` (scp-like) et `ssh://git@hote/…` restent légitimes : utilisateur
|
|
14
|
+
* ssh standard, sans mot de passe (L3). */
|
|
15
|
+
export function hasGitCredentials(source) {
|
|
16
|
+
const s = source.trim();
|
|
17
|
+
return /^[^/:]+:\/\/[^/@\s]+:[^@\s]+@/.test(s) || /^https?:\/\/[^/@\s]+@/.test(s) || /^(?!git@)[^/@\s:]+@[^/@\s]+:/.test(s);
|
|
18
|
+
}
|
|
19
|
+
function isValidGitSource(source) {
|
|
20
|
+
return Boolean(source) && !source.startsWith("-") && !/^(ext::|file:)/.test(source) && !hasGitCredentials(source);
|
|
21
|
+
}
|
|
22
|
+
/** Masque les identifiants embarqués dans une URL : `user:token@`, `token@` (PAT en nom
|
|
23
|
+
* d'utilisateur) et l'utilisateur scp-like autre que `git` (`ghp_…@hôte:` — R3). */
|
|
24
|
+
function redactCredentials(url) {
|
|
25
|
+
return url
|
|
26
|
+
.replace(/(\/\/)([^/@\s]*):[^@\s]+@/g, "$1$2:***@")
|
|
27
|
+
.replace(/(\/\/)([^/@\s:]+)@/g, "$1***@")
|
|
28
|
+
.replace(/\b(?!git@)[^/@\s:]+@/g, "***@");
|
|
29
|
+
}
|
|
30
|
+
/** Détail d'échec affichable : identifiants masqués, queue conservée (300 car max). */
|
|
31
|
+
export function gitErrorDetail(stderr) {
|
|
32
|
+
return redactCredentials(stderr.trim()).slice(-300);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* R1 : le raccourci nu `owner/repo` (D3) ne vaut que pour exactement 2 segments ;
|
|
36
|
+
* `gitlab.com/o/r` serait sinon lu { owner: "gitlab.com", repo: "o" } → clone vers
|
|
37
|
+
* github.com faux et fausse équivalence entre `gitlab.com/o/r1` et `/r2`. parseGitHubRepo
|
|
38
|
+
* est partagé avec l'import de skills : la borne vit ici, côté git-import uniquement.
|
|
39
|
+
*/
|
|
40
|
+
function parseGitHubSource(source) {
|
|
41
|
+
if (/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(source))
|
|
42
|
+
return parseGitHubRepo(source);
|
|
43
|
+
if (/^(?:https?:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)/.test(source))
|
|
44
|
+
return parseGitHubRepo(source);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** Un segment de chemin `.` ou `..` n'apparaît nulle part dans la source (S4). */
|
|
48
|
+
function hasDotSegments(source) {
|
|
49
|
+
return source.split(/[/:]/).some((segment) => segment === "." || segment === "..");
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Normalise une source git clonable (D3) : `owner/repo` → `https://github.com/owner/repo` ;
|
|
53
|
+
* https, git@, ssh:// et chemins locaux conservés tels quels. Rejette les segments
|
|
54
|
+
* `.`/`..` (traversée), le backslash, le préfixe `-`, les transports `ext::`/`file://`
|
|
55
|
+
* et les identifiants embarqués dans l'URL (L3).
|
|
56
|
+
*/
|
|
57
|
+
export function normalizeGitUrl(url) {
|
|
58
|
+
const source = url.trim();
|
|
59
|
+
if (!isValidGitSource(source) || source.includes("\\") || hasDotSegments(source))
|
|
60
|
+
return null;
|
|
61
|
+
// https/git@/ssh:// et chemins locaux : conservés tels quels (identifiants ssh du poste).
|
|
62
|
+
if (/^(?:https?:\/\/|git@|ssh:\/\/)/.test(source) || existsSync(source))
|
|
63
|
+
return source;
|
|
64
|
+
const repo = parseGitHubSource(source);
|
|
65
|
+
return repo ? `https://github.com/${repo.owner}/${repo.repo}` : source;
|
|
66
|
+
}
|
|
67
|
+
/** Dernier segment d'une source non GitHub ; vide si le segment serait dangereux (S4). */
|
|
68
|
+
function slugFor(source) {
|
|
69
|
+
const slug = source.replace(/\/+$/, "").split(/[/:]/).pop()?.replace(/\.git$/, "") ?? "";
|
|
70
|
+
return slug === "." || slug === ".." || slug.includes("..") || slug.includes("\\") ? "" : slug;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Destination de clone stable : `<root>/<owner>/<repo>` (GitHub) ou `<root>/<slug>`
|
|
74
|
+
* (sinon). Renvoie aussi la source normalisée à cloner. Rejette explicitement les
|
|
75
|
+
* segments `.`/`..` : seul relative() ne suffit pas, join() les ferait s'annuler
|
|
76
|
+
* et ramènerait la destination dans la racine (S4).
|
|
77
|
+
*/
|
|
78
|
+
export function localDirFor(url, root) {
|
|
79
|
+
// L3 : refus dédié (et sans echo de l'URL, qui porterait le secret en clair).
|
|
80
|
+
if (hasGitCredentials(url))
|
|
81
|
+
return { error: "identifiants embarqués dans l'URL git refusés — utilise les identifiants git configurés sur ce poste" };
|
|
82
|
+
const source = normalizeGitUrl(url);
|
|
83
|
+
if (!source)
|
|
84
|
+
return { error: `URL git invalide: ${redactCredentials(url.trim())}` };
|
|
85
|
+
const repo = parseGitHubSource(source);
|
|
86
|
+
const slug = repo ? repo.repo : slugFor(source);
|
|
87
|
+
if (!slug)
|
|
88
|
+
return { error: `URL git invalide: ${redactCredentials(source)}` };
|
|
89
|
+
// Pas de garde relative() ici : owner/repo viennent de parseGitHubRepo (un segment
|
|
90
|
+
// `[A-Za-z0-9_.-]+`, jamais `.`/`..` — hasDotSegments a filtré en amont) et slug est un
|
|
91
|
+
// segment unique : join(root, …) ne peut pas en sortir (J1).
|
|
92
|
+
const dest = repo ? join(root, repo.owner, slug) : join(root, slug);
|
|
93
|
+
return { dest, source };
|
|
94
|
+
}
|
|
95
|
+
/** `dir` est-il sous `root` (formes lexicales canoniques) ? Garde B1 avant toute écriture. */
|
|
96
|
+
export function isInsideDir(path, root) {
|
|
97
|
+
return isInside(resolve(path), resolve(root));
|
|
98
|
+
}
|
|
99
|
+
function isGitWorkTree(dir) {
|
|
100
|
+
return new Promise((resolvePromise) => {
|
|
101
|
+
execFile("git", ["-C", dir, "rev-parse", "--is-inside-work-tree"], { timeout: 10_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }, (err, stdout) => {
|
|
102
|
+
resolvePromise(!err && stdout.trim() === "true");
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Forme canonique pour la comparaison littérale hors GitHub : barres obliques finales et
|
|
108
|
+
* `.git` retirés des deux côtés, schéma et hôte en minuscules — sinon `https://gitlab.com/a/b/`
|
|
109
|
+
* est refusée comme « dépôt différent » à destination identique (S4).
|
|
110
|
+
*/
|
|
111
|
+
function canonicalGitLiteral(source) {
|
|
112
|
+
const s = source.trim().replace(/\/+$/, "").replace(/\.git$/, "");
|
|
113
|
+
const parts = s.match(/^([a-z][a-z0-9+.-]*:\/\/[^/]*)(\/.*)?$/i);
|
|
114
|
+
return parts ? parts[1].toLowerCase() + (parts[2] ?? "") : s;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Même source à formes d'URL équivalentes près : `https://github.com/o/r`,
|
|
118
|
+
* `git@github.com:o/r.git` et `…/o/r.git` désignent le même dépôt (comparaison
|
|
119
|
+
* `owner/repo` insensible à la casse quand le parsing réussit des deux côtés) ; sinon
|
|
120
|
+
* comparaison littérale canonique (M2, S4).
|
|
121
|
+
*/
|
|
122
|
+
function sameGitSource(origin, source) {
|
|
123
|
+
const a = parseGitHubSource(origin);
|
|
124
|
+
const b = parseGitHubSource(source);
|
|
125
|
+
if (a && b)
|
|
126
|
+
return a.owner.toLowerCase() === b.owner.toLowerCase() && a.repo.toLowerCase() === b.repo.toLowerCase();
|
|
127
|
+
return canonicalGitLiteral(origin) === canonicalGitLiteral(source);
|
|
128
|
+
}
|
|
129
|
+
/** URL d'origine d'un dépôt existant, null si absente ou illisible. */
|
|
130
|
+
function originOf(dir) {
|
|
131
|
+
return new Promise((resolvePromise) => {
|
|
132
|
+
execFile("git", ["-C", dir, "remote", "get-url", "origin"], { timeout: 10_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }, (err, stdout) => {
|
|
133
|
+
resolvePromise(err ? null : stdout.trim());
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Clone `url` vers `dest` avec les identifiants git ambiants (D1 : dépôt privé si le
|
|
139
|
+
* poste est déjà authentifié ; aucun token stocké, lu ni affiché). GIT_TERMINAL_PROMPT=0 :
|
|
140
|
+
* échec explicite, jamais de prompt bloquant. Un dossier existant et valide est repris
|
|
141
|
+
* (clone orphelin, D4). `created` distingue « dossier créé par ce clone » de « dossier
|
|
142
|
+
* préexistant » pour que l'appelant ne supprime que le premier (S3) ; `cloned` distingue
|
|
143
|
+
* la reprise d'un clone frais.
|
|
144
|
+
*/
|
|
145
|
+
export async function cloneRepo(url, dest, connectionEnv) {
|
|
146
|
+
const github = connectionEnv ? parseGitHubSource(url.trim()) : null;
|
|
147
|
+
const source = github ? `https://github.com/${github.owner}/${github.repo}.git` : url.trim();
|
|
148
|
+
if (!isValidGitSource(url.trim()))
|
|
149
|
+
return { error: `URL git invalide: ${redactCredentials(source)}` };
|
|
150
|
+
const preExisting = existsSync(dest);
|
|
151
|
+
if (preExisting) {
|
|
152
|
+
if (await isGitWorkTree(dest)) {
|
|
153
|
+
// Un dossier existant n'est repris que s'il vient de la même source : sinon deux
|
|
154
|
+
// dépôts de même dernier segment se partageraient la destination (mauvais contenu).
|
|
155
|
+
const origin = await originOf(dest);
|
|
156
|
+
if (origin !== null && sameGitSource(origin, source))
|
|
157
|
+
return { dir: dest, cloned: false, created: false };
|
|
158
|
+
return { error: `dépôt différent déjà cloné à cet emplacement: ${dest}` };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
await new Promise((resolvePromise, reject) => {
|
|
166
|
+
execFile("git", [...(github ? ["-c", "credential.https://github.com.helper=", "-c", "credential.https://github.com.helper=!gh auth git-credential"] : []), "clone", "--quiet", ...(github ? ["--config", "credential.https://github.com.helper=", "--config", "credential.https://github.com.helper=!gh auth git-credential"] : []), "--", source, dest], { timeout: CLONE_TIMEOUT_MS, env: { ...(connectionEnv ?? process.env), GIT_TERMINAL_PROMPT: "0" } }, (err, _stdout, stderr) => (err ? reject(new Error(gitErrorDetail(stderr) || gitErrorDetail(err.message))) : resolvePromise()));
|
|
167
|
+
});
|
|
168
|
+
return { dir: dest, cloned: true, created: !preExisting };
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
// Ne supprime que ce qu'on a créé, et pas si un import concurrent a gagné la course
|
|
172
|
+
// en laissant un dépôt valide à cette destination. Nettoyage best-effort : un rmSync
|
|
173
|
+
// qui lève ne doit pas masquer l'erreur de clone d'origine (S2).
|
|
174
|
+
// shortcut: un crash serveur pendant le clone laisse un dossier partiel (preExisting
|
|
175
|
+
// au réimport → échec répété « clone échoué », aucun recours UI) ; à revoir si un
|
|
176
|
+
// nettoyage de clones orphelins non enrôlés est un jour ajouté (L4).
|
|
177
|
+
if (!preExisting && !(await isGitWorkTree(dest))) {
|
|
178
|
+
try {
|
|
179
|
+
rmSync(dest, { recursive: true, force: true });
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
/* dossier résiduel possible, signalé par l'erreur d'origine */
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { error: `clone échoué: ${err instanceof Error ? err.message : String(err)}` };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
export function githubEnv(paths) {
|
|
5
|
+
const env = { ...process.env, GH_CONFIG_DIR: join(paths.home, "github"), GH_PROMPT_DISABLED: "1", GH_BROWSER: "true", BROWSER: "true", NO_COLOR: "1", TERM: "dumb", LC_ALL: "C" };
|
|
6
|
+
// This connection belongs to this installation, never an ambient token.
|
|
7
|
+
for (const key of ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"])
|
|
8
|
+
delete env[key];
|
|
9
|
+
return env;
|
|
10
|
+
}
|
|
11
|
+
export function githubConfigured(paths) { return existsSync(join(paths.home, "github", "hosts.yml")); }
|
|
12
|
+
export function deviceCode(output) {
|
|
13
|
+
return output.match(/(?:one-time code|code):\s*([A-Z0-9]{4}-[A-Z0-9]{4})\b/i)?.[1];
|
|
14
|
+
}
|
|
15
|
+
export class GitHubLogin {
|
|
16
|
+
paths;
|
|
17
|
+
onConnected;
|
|
18
|
+
child;
|
|
19
|
+
timer;
|
|
20
|
+
view = { available: true, connected: false, status: "idle" };
|
|
21
|
+
checkedAt = 0;
|
|
22
|
+
checking;
|
|
23
|
+
constructor(paths, onConnected = async () => { }) {
|
|
24
|
+
this.paths = paths;
|
|
25
|
+
this.onConnected = onConnected;
|
|
26
|
+
}
|
|
27
|
+
async state() {
|
|
28
|
+
if (this.child || Date.now() - this.checkedAt < 10_000)
|
|
29
|
+
return { ...this.view };
|
|
30
|
+
if (this.checking)
|
|
31
|
+
return this.checking;
|
|
32
|
+
this.checking = new Promise(resolve => {
|
|
33
|
+
execFile("gh", ["api", "--hostname", "github.com", "user", "--jq", ".login"], { env: githubEnv(this.paths), timeout: 10_000, maxBuffer: 16_384 }, (error, stdout) => {
|
|
34
|
+
const login = stdout.trim();
|
|
35
|
+
this.view.available = error?.code !== "ENOENT";
|
|
36
|
+
this.view.connected = !error && /^[a-z0-9-]{1,39}$/i.test(login);
|
|
37
|
+
this.view.login = this.view.connected ? login : undefined;
|
|
38
|
+
this.checkedAt = Date.now();
|
|
39
|
+
this.checking = undefined;
|
|
40
|
+
resolve({ ...this.view });
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
return this.checking;
|
|
44
|
+
}
|
|
45
|
+
start() {
|
|
46
|
+
if (this.child)
|
|
47
|
+
return { ...this.view };
|
|
48
|
+
const dir = githubEnv(this.paths).GH_CONFIG_DIR;
|
|
49
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
50
|
+
chmodSync(dir, 0o700);
|
|
51
|
+
this.view = { available: true, connected: false, status: "starting" };
|
|
52
|
+
const child = spawn("gh", ["auth", "login", "--hostname", "github.com", "--git-protocol", "https", "--web"], { env: githubEnv(this.paths), cwd: this.paths.home, stdio: ["pipe", "pipe", "pipe"] });
|
|
53
|
+
this.child = child;
|
|
54
|
+
let output = "";
|
|
55
|
+
const receive = (chunk) => {
|
|
56
|
+
if (this.child !== child || this.view.code)
|
|
57
|
+
return;
|
|
58
|
+
output = (output + chunk.toString()).slice(-4096);
|
|
59
|
+
const code = deviceCode(output);
|
|
60
|
+
if (code) {
|
|
61
|
+
this.view = { ...this.view, status: "waiting", code, url: "https://github.com/login/device" };
|
|
62
|
+
output = "";
|
|
63
|
+
child.stdin?.write("\n");
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
child.stdout?.on("data", receive);
|
|
67
|
+
child.stderr?.on("data", receive);
|
|
68
|
+
const finish = (ok) => {
|
|
69
|
+
if (this.child !== child)
|
|
70
|
+
return;
|
|
71
|
+
clearTimeout(this.timer);
|
|
72
|
+
this.child = undefined;
|
|
73
|
+
this.checkedAt = 0;
|
|
74
|
+
for (const file of ["hosts.yml", "config.yml"]) {
|
|
75
|
+
const path = join(dir, file);
|
|
76
|
+
if (existsSync(path))
|
|
77
|
+
chmodSync(path, 0o600);
|
|
78
|
+
}
|
|
79
|
+
this.view = { available: true, connected: false, status: ok ? "done" : "error", ...(ok ? {} : { error: "github.loginFailed" }) };
|
|
80
|
+
if (ok)
|
|
81
|
+
void this.state().then(state => state.connected ? this.onConnected() : undefined).catch(() => { });
|
|
82
|
+
};
|
|
83
|
+
child.once("error", () => finish(false));
|
|
84
|
+
child.once("close", code => finish(code === 0));
|
|
85
|
+
this.timer = setTimeout(() => { this.cancel(); this.view.status = "error"; this.view.error = "github.expired"; }, 15 * 60_000);
|
|
86
|
+
return { ...this.view };
|
|
87
|
+
}
|
|
88
|
+
cancel() {
|
|
89
|
+
const child = this.child;
|
|
90
|
+
this.child = undefined;
|
|
91
|
+
clearTimeout(this.timer);
|
|
92
|
+
child?.kill("SIGTERM");
|
|
93
|
+
if (child) {
|
|
94
|
+
const timer = setTimeout(() => { if (child.exitCode === null)
|
|
95
|
+
child.kill("SIGKILL"); }, 1000);
|
|
96
|
+
timer.unref();
|
|
97
|
+
}
|
|
98
|
+
this.view = { available: true, connected: false, status: "idle" };
|
|
99
|
+
this.checkedAt = 0;
|
|
100
|
+
}
|
|
101
|
+
}
|
package/dist/src/history.js
CHANGED
|
@@ -26,13 +26,18 @@ function blockIsError(content) {
|
|
|
26
26
|
}
|
|
27
27
|
/** Parse le .jsonl pi en entrées ordonnées : user / assistant / thinking / tool (avec résultat). */
|
|
28
28
|
export function readEntries(sessionFile, limit = 300) {
|
|
29
|
+
return entriesFromLines(readSessionLines(sessionFile, HISTORY_LINES_SCAN), limit);
|
|
30
|
+
}
|
|
31
|
+
export function entriesFromLines(lines, limit = 300) {
|
|
29
32
|
const out = [];
|
|
30
33
|
const pendingTools = new Map(); // toolCallId → index dans out
|
|
31
|
-
for (const line of
|
|
34
|
+
for (const line of lines) {
|
|
32
35
|
const entry = parseJsonLine(line);
|
|
33
36
|
if (!entry || entry.type !== "message")
|
|
34
37
|
continue;
|
|
35
38
|
const msg = entry.message;
|
|
39
|
+
if (!msg || typeof msg !== "object")
|
|
40
|
+
continue;
|
|
36
41
|
const content = msg.content;
|
|
37
42
|
if (msg.role === "user") {
|
|
38
43
|
const text = extractText(content).trim();
|
package/dist/src/host-pi.js
CHANGED
|
@@ -21,7 +21,7 @@ function findPackageUp(name, from) {
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
/** Dossier du package `name` selon la résolution node depuis `from`. */
|
|
24
|
-
function
|
|
24
|
+
export function findPackageFrom(name, from) {
|
|
25
25
|
for (let dir = from;; dir = dirname(dir)) {
|
|
26
26
|
const candidate = join(dir, "node_modules", name);
|
|
27
27
|
if (existsSync(join(candidate, "package.json")))
|
|
@@ -34,26 +34,29 @@ function hostBase() {
|
|
|
34
34
|
try {
|
|
35
35
|
const bins = execFileSync(process.platform === "win32" ? "where" : "which", process.platform === "win32" ? ["pi"] : ["-a", "pi"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim().split("\n").map((line) => line.trim());
|
|
36
36
|
// Un pi sous node_modules/.bin est le devDependency d'un projet, pas l'installation de l'utilisateur.
|
|
37
|
-
const bin = bins.find((path) => !/node_modules[\\/]\.bin[\\/]/.test(path))
|
|
37
|
+
const bin = bins.find((path) => path && !/node_modules[\\/]\.bin[\\/]/.test(path));
|
|
38
38
|
return bin ? findPackageUp("@earendil-works/pi-coding-agent", dirname(realpathSync(bin))) : null;
|
|
39
39
|
}
|
|
40
40
|
catch {
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
|
|
44
|
+
/** Racine `@earendil-works/pi-coding-agent` du `pi` hôte, ou null si aucun binaire résolvable. */
|
|
45
|
+
export const hostPiPackage = hostBase();
|
|
46
|
+
const bases = [hostPiPackage, findPackageUp("@ignitionai/cogitator", dirname(fileURLToPath(import.meta.url)))].filter((base) => base !== null);
|
|
45
47
|
function root(pkg) {
|
|
46
48
|
for (const base of bases) {
|
|
47
|
-
const found =
|
|
49
|
+
const found = findPackageFrom(pkg, base);
|
|
48
50
|
if (found)
|
|
49
51
|
return found;
|
|
50
52
|
}
|
|
51
53
|
throw new Error(`package pi introuvable: ${pkg}`);
|
|
52
54
|
}
|
|
53
|
-
export const codingAgentRoot = root("@earendil-works/pi-coding-agent");
|
|
55
|
+
export const codingAgentRoot = hostPiPackage ?? root("@earendil-works/pi-coding-agent");
|
|
54
56
|
// Ces packages n'exposent qu'une condition "import" : chargement ESM dynamique.
|
|
55
57
|
const load = (...segments) => import(pathToFileURL(join(...segments)).href);
|
|
56
|
-
|
|
58
|
+
/** Catalogue `pi-ai` résolu depuis le même arbre que le binaire (pas un voisin hoisté supposé). */
|
|
59
|
+
export const piAiRoot = findPackageFrom("@earendil-works/pi-ai", codingAgentRoot) ?? root("@earendil-works/pi-ai");
|
|
57
60
|
export const piCodingAgent = await load(codingAgentRoot, "dist/index.js");
|
|
58
61
|
export const piAi = await load(piAiRoot, "dist/index.js");
|
|
59
62
|
export const piAiProviders = await load(piAiRoot, "dist/providers/all.js");
|
package/dist/src/json-files.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { chmodSync, copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
2
|
/** Lit un JSON tolérant (fichier absent → fallback). */
|
|
3
3
|
export function readJson(path, fallback) {
|
|
4
4
|
try {
|
|
@@ -9,10 +9,13 @@ export function readJson(path, fallback) {
|
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
11
|
/** Écriture atomique : tmp + rename, backup `.bak` de l'ancien. */
|
|
12
|
-
export function atomicWriteJson(path, value) {
|
|
12
|
+
export function atomicWriteJson(path, value, mode) {
|
|
13
13
|
const tmp = `${path}.tmp-${process.pid}`;
|
|
14
|
-
writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
15
|
-
if (existsSync(path))
|
|
14
|
+
writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode });
|
|
15
|
+
if (existsSync(path)) {
|
|
16
16
|
copyFileSync(path, `${path}.bak`);
|
|
17
|
+
if (mode !== undefined)
|
|
18
|
+
chmodSync(`${path}.bak`, mode);
|
|
19
|
+
}
|
|
17
20
|
renameSync(tmp, path);
|
|
18
21
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { cpus, freemem, totalmem, uptime } from "node:os";
|
|
2
|
+
import { readFile, statfs } from "node:fs/promises";
|
|
3
|
+
export function cpuPercent(before, after) {
|
|
4
|
+
const total = after.total - before.total;
|
|
5
|
+
const idle = after.idle - before.idle;
|
|
6
|
+
return total > 0 && idle >= 0 ? Math.max(0, Math.min(100, (1 - idle / total) * 100)) : null;
|
|
7
|
+
}
|
|
8
|
+
export function availableMemory(meminfo) {
|
|
9
|
+
const value = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(meminfo);
|
|
10
|
+
return value ? Number(value[1]) * 1024 : null;
|
|
11
|
+
}
|
|
12
|
+
function cpuSnapshot() {
|
|
13
|
+
const cores = cpus();
|
|
14
|
+
return { cores: cores.length, idle: cores.reduce((sum, c) => sum + c.times.idle, 0), total: cores.reduce((sum, c) => sum + Object.values(c.times).reduce((a, b) => a + b, 0), 0) };
|
|
15
|
+
}
|
|
16
|
+
/** Host metrics, not a container/service resource quota. No shell or arbitrary path input. */
|
|
17
|
+
export function machineMetrics(home) {
|
|
18
|
+
let previous = cpuSnapshot();
|
|
19
|
+
let lastAt = performance.now();
|
|
20
|
+
let cached;
|
|
21
|
+
let pending;
|
|
22
|
+
return function sample() {
|
|
23
|
+
if (cached && performance.now() - lastAt < 2000)
|
|
24
|
+
return Promise.resolve(cached);
|
|
25
|
+
if (pending)
|
|
26
|
+
return pending;
|
|
27
|
+
pending = (async () => {
|
|
28
|
+
const cpu = cpuSnapshot();
|
|
29
|
+
const elapsed = performance.now() - lastAt;
|
|
30
|
+
const percent = elapsed >= 500 ? cpuPercent(previous, cpu) : null;
|
|
31
|
+
const total = totalmem();
|
|
32
|
+
let available = freemem();
|
|
33
|
+
if (process.platform === "linux") {
|
|
34
|
+
available = await readFile("/proc/meminfo", "utf8").then(s => availableMemory(s) ?? available).catch(() => available);
|
|
35
|
+
}
|
|
36
|
+
const used = Math.max(0, Math.min(total, total - available));
|
|
37
|
+
const disk = await statfs(home).then(s => {
|
|
38
|
+
const total = s.blocks * s.bsize;
|
|
39
|
+
const used = (s.blocks - s.bfree) * s.bsize;
|
|
40
|
+
return { total, used, available: s.bavail * s.bsize, percent: total > 0 ? used / total * 100 : 0 };
|
|
41
|
+
}).catch(() => null);
|
|
42
|
+
previous = cpu;
|
|
43
|
+
lastAt = performance.now();
|
|
44
|
+
cached = { sampledAt: new Date().toISOString(), cpu: { percent, cores: cpu.cores }, memory: { used, total, percent: total > 0 ? used / total * 100 : 0 }, disk, uptimeSeconds: uptime(), processMemoryBytes: process.memoryUsage().rss };
|
|
45
|
+
return cached;
|
|
46
|
+
})().finally(() => { pending = undefined; });
|
|
47
|
+
return pending;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|