@ignitionai/cogitator 0.5.0 → 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.
Files changed (63) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -44
  4. package/dist/extensions/index.js +66 -29
  5. package/dist/src/app-updates.js +15 -0
  6. package/dist/src/auth-cli.js +18 -8
  7. package/dist/src/auth-http.js +13 -3
  8. package/dist/src/auth-state.js +41 -6
  9. package/dist/src/board.js +3 -1
  10. package/dist/src/browser-http.js +143 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +30 -4
  13. package/dist/src/config.js +10 -0
  14. package/dist/src/cron.js +91 -15
  15. package/dist/src/db.js +55 -3
  16. package/dist/src/durable/approvals.js +17 -2
  17. package/dist/src/durable/effect-gateway.js +23 -16
  18. package/dist/src/durable/manager.js +15 -6
  19. package/dist/src/durable/mission-runtime.js +204 -46
  20. package/dist/src/durable/recovery.js +37 -0
  21. package/dist/src/durable/workers.js +22 -14
  22. package/dist/src/execution/confinement.js +2 -1
  23. package/dist/src/execution/worker-supervisor.js +222 -0
  24. package/dist/src/git-import.js +187 -0
  25. package/dist/src/github-login.js +101 -0
  26. package/dist/src/history.js +6 -1
  27. package/dist/src/host-pi.js +64 -0
  28. package/dist/src/json-files.js +7 -4
  29. package/dist/src/machine-metrics.js +49 -0
  30. package/dist/src/machine-types.js +1 -0
  31. package/dist/src/mcp-cli.js +63 -0
  32. package/dist/src/mcp-http.js +164 -0
  33. package/dist/src/mcp-oauth.js +502 -0
  34. package/dist/src/mcp-server.js +6 -136
  35. package/dist/src/mcp-tokens.js +104 -0
  36. package/dist/src/mcp-tools.js +264 -0
  37. package/dist/src/native-auth.js +9 -2
  38. package/dist/src/packages.js +190 -0
  39. package/dist/src/paths.js +1 -0
  40. package/dist/src/pi-child.js +180 -0
  41. package/dist/src/pi-rpc-wrap.js +84 -0
  42. package/dist/src/pool.js +58 -7
  43. package/dist/src/project-setup.js +63 -0
  44. package/dist/src/provider-login.js +73 -14
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +68 -45
  47. package/dist/src/schemas.js +19 -4
  48. package/dist/src/server-compat.js +173 -0
  49. package/dist/src/server-identity.js +69 -0
  50. package/dist/src/server.js +534 -41
  51. package/dist/src/shared-browser.js +357 -0
  52. package/dist/src/skills-import.js +13 -4
  53. package/dist/src/skills-upload.js +68 -0
  54. package/dist/src/spawner.js +20 -4
  55. package/dist/src/subagents.js +242 -0
  56. package/dist/src/team-queue.js +262 -0
  57. package/package.json +13 -4
  58. package/web/dist/assets/BrandLogo3D-CHGXwTbZ.js +4035 -0
  59. package/web/dist/assets/index-DGLkhrE7.css +1 -0
  60. package/web/dist/assets/index-P0WoXBgX.js +84 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/index-C3tRuOTh.js +0 -83
  63. package/web/dist/assets/index-DMQqB0r1.css +0 -1
@@ -1,7 +1,9 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
1
3
  import { randomUUID } from "node:crypto";
2
- import { builtinModels } from "@earendil-works/pi-ai/providers/all";
4
+ import { piAiProviders } from "./host-pi.js";
3
5
  import { atomicWriteJson, readJson } from "./json-files.js";
4
- function fileCredentialStore(path) {
6
+ export function fileCredentialStore(path) {
5
7
  let queue = Promise.resolve();
6
8
  const locked = (fn) => {
7
9
  const run = queue.then(fn, fn);
@@ -22,7 +24,8 @@ function fileCredentialStore(path) {
22
24
  const next = await fn(file[providerId]);
23
25
  if (next !== undefined) {
24
26
  file[providerId] = next;
25
- atomicWriteJson(path, file);
27
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
28
+ atomicWriteJson(path, file, 0o600);
26
29
  }
27
30
  return next ?? file[providerId];
28
31
  });
@@ -31,7 +34,7 @@ function fileCredentialStore(path) {
31
34
  return locked(async () => {
32
35
  const file = all();
33
36
  delete file[providerId];
34
- atomicWriteJson(path, file);
37
+ atomicWriteJson(path, file, 0o600);
35
38
  });
36
39
  },
37
40
  };
@@ -45,23 +48,51 @@ function publicPrompt(prompt) {
45
48
  };
46
49
  }
47
50
  export class ProviderLogins {
48
- paths;
49
51
  sessions = new Map();
50
- constructor(paths) {
51
- this.paths = paths;
52
+ models;
53
+ deviceId;
54
+ deviceFile;
55
+ constructor(paths, models) {
56
+ this.deviceFile = join(paths.home, "provider-device.json");
57
+ this.models = models ?? piAiProviders.builtinModels({ credentials: fileCredentialStore(paths.piAuthJson) });
58
+ }
59
+ getDeviceId() {
60
+ if (this.deviceId)
61
+ return this.deviceId;
62
+ const saved = readJson(this.deviceFile, {});
63
+ if (typeof saved.id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(saved.id))
64
+ return this.deviceId = saved.id;
65
+ const id = randomUUID();
66
+ mkdirSync(dirname(this.deviceFile), { recursive: true, mode: 0o700 });
67
+ atomicWriteJson(this.deviceFile, { id }, 0o600);
68
+ return this.deviceId = id;
52
69
  }
53
70
  start(providerId, type) {
71
+ if (this.sessions.size >= 64)
72
+ throw new Error("Too many pending provider logins");
54
73
  const id = randomUUID();
55
74
  const abort = new AbortController();
56
- const session = { events: [], listeners: new Set(), abort };
75
+ const expiry = setTimeout(() => {
76
+ emit({ type: "error", message: "Provider login expired. Start again." });
77
+ this.cancel(id);
78
+ }, 15 * 60_000);
79
+ expiry.unref();
80
+ const session = { events: [], listeners: new Set(), abort, expiry };
57
81
  this.sessions.set(id, session);
58
82
  const emit = (event) => {
83
+ if (session.terminal)
84
+ return;
59
85
  session.events.push(event);
86
+ if (event.type === "done" || event.type === "error") {
87
+ session.terminal = true;
88
+ clearTimeout(session.expiry);
89
+ session.expiry = setTimeout(() => this.cancel(id), 60_000);
90
+ session.expiry.unref();
91
+ }
60
92
  for (const listener of session.listeners)
61
93
  listener(event);
62
94
  };
63
- const models = builtinModels({ credentials: fileCredentialStore(this.paths.piAuthJson) });
64
- void models.login(providerId, type, {
95
+ void this.models.login(providerId, type, {
65
96
  signal: abort.signal,
66
97
  notify: (event) => emit(event),
67
98
  prompt: (prompt) => new Promise((resolve, reject) => {
@@ -69,11 +100,30 @@ export class ProviderLogins {
69
100
  reject(abort.signal.reason instanceof Error ? abort.signal.reason : new Error("cancelled"));
70
101
  return;
71
102
  }
72
- session.resolvePrompt = resolve;
73
- session.rejectPrompt = reject;
103
+ const signals = [abort.signal, prompt.signal].filter((signal) => Boolean(signal));
104
+ const finish = (value, error) => {
105
+ for (const signal of signals)
106
+ signal.removeEventListener("abort", onAbort);
107
+ session.resolvePrompt = undefined;
108
+ session.rejectPrompt = undefined;
109
+ session.prompt = undefined;
110
+ emit({ type: "prompt_clear" });
111
+ if (error)
112
+ reject(error);
113
+ else
114
+ resolve(value);
115
+ };
116
+ const onAbort = () => finish(undefined, new Error("cancelled"));
117
+ session.prompt = publicPrompt(prompt);
118
+ session.resolvePrompt = (value) => finish(value);
119
+ session.rejectPrompt = (error) => finish(undefined, error);
120
+ for (const signal of signals)
121
+ signal.addEventListener("abort", onAbort, { once: true });
74
122
  emit({ type: "prompt", prompt: publicPrompt(prompt) });
123
+ if (signals.some((signal) => signal.aborted))
124
+ onAbort();
75
125
  }),
76
- }, { agentName: "Cogitator" }).then(() => emit({ type: "done" }), (error) => {
126
+ }, { agentName: "Cogitator", getDeviceId: () => this.getDeviceId() }).then(() => emit({ type: "done" }), (error) => {
77
127
  if (abort.signal.aborted)
78
128
  return;
79
129
  emit({ type: "error", message: error instanceof Error ? error.message : "login failed" });
@@ -95,7 +145,11 @@ export class ProviderLogins {
95
145
  }
96
146
  reply(id, value) {
97
147
  const session = this.sessions.get(id);
98
- if (!session?.resolvePrompt)
148
+ if (!session?.resolvePrompt || session.terminal)
149
+ return false;
150
+ if (session.prompt?.type !== "text" && !value.trim())
151
+ return false;
152
+ if (session.prompt?.type === "select" && !session.prompt.options?.some(option => option.id === value))
99
153
  return false;
100
154
  const resolve = session.resolvePrompt;
101
155
  session.resolvePrompt = undefined;
@@ -103,10 +157,15 @@ export class ProviderLogins {
103
157
  resolve(value);
104
158
  return true;
105
159
  }
160
+ dispose() {
161
+ for (const id of this.sessions.keys())
162
+ this.cancel(id);
163
+ }
106
164
  cancel(id) {
107
165
  const session = this.sessions.get(id);
108
166
  if (!session)
109
167
  return false;
168
+ clearTimeout(session.expiry);
110
169
  session.rejectPrompt?.(new Error("cancelled"));
111
170
  session.abort.abort();
112
171
  this.sessions.delete(id);
@@ -0,0 +1,138 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { reapIntervalMs } from "./config.js";
4
+ /** Marqueur posé sur les process pi spawnés par Cogitator (hors pool.ts) : `pid:starttime`. */
5
+ export const OWNED_PI_ENV = "COGITATOR_OWNED_PI";
6
+ /** `/proc/<pid>/stat` : comm entre parenthèses, puis champs 3… ; le 22 est starttime. */
7
+ export function parseProcStat(stat) {
8
+ const close = stat.lastIndexOf(")");
9
+ if (close < 0)
10
+ return undefined;
11
+ const rest = stat.slice(close + 1).trim().split(/\s+/);
12
+ const state = rest[0];
13
+ const ppid = Number(rest[1]);
14
+ const starttime = rest[19];
15
+ if (!state || !Number.isInteger(ppid) || starttime === undefined || starttime === "")
16
+ return undefined;
17
+ return { ppid, starttime, state };
18
+ }
19
+ export function readProcStat(pid) {
20
+ try {
21
+ return parseProcStat(readFileSync(join("/proc", String(pid), "stat"), "utf8"));
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ export function parseOwnedPiMarker(value) {
28
+ const sep = value.indexOf(":");
29
+ if (sep <= 0)
30
+ return undefined;
31
+ const pid = Number(value.slice(0, sep));
32
+ const starttime = value.slice(sep + 1);
33
+ if (!Number.isInteger(pid) || pid <= 0 || starttime === "")
34
+ return undefined;
35
+ return { pid, starttime };
36
+ }
37
+ /** Marqueur de l'hôte courant (pid + starttime) pour battre la réutilisation de pid. */
38
+ export function ownedPiMarker(pid = process.pid) {
39
+ const stat = readProcStat(pid);
40
+ return stat ? `${pid}:${stat.starttime}` : undefined;
41
+ }
42
+ export function ownerStillAlive(marker) {
43
+ const stat = readProcStat(marker.pid);
44
+ return Boolean(stat && stat.state !== "Z" && stat.starttime === marker.starttime);
45
+ }
46
+ /** Mort, zombie, ou pid réutilisé : `kill(pid, 0)` réussit encore sur un zombie. */
47
+ export function processIsGone(pid) {
48
+ const stat = readProcStat(pid);
49
+ if (!stat || stat.state === "Z")
50
+ return true;
51
+ try {
52
+ process.kill(pid, 0);
53
+ return false;
54
+ }
55
+ catch {
56
+ return true;
57
+ }
58
+ }
59
+ function environEntry(environ, key) {
60
+ const prefix = `${key}=`;
61
+ for (const entry of environ.split("\0")) {
62
+ if (entry.startsWith(prefix))
63
+ return entry.slice(prefix.length);
64
+ }
65
+ return undefined;
66
+ }
67
+ /** Uniquement le process rpc (`node … --mode rpc`), pas les descendants détachés (xdg-open, nohup). */
68
+ export function isPiRpcCmdline(cmdline) {
69
+ const parts = cmdline.split("\0");
70
+ return parts.some((part, i) => part === "--mode" && parts[i + 1] === "rpc");
71
+ }
72
+ function readCmdline(pid) {
73
+ try {
74
+ return readFileSync(join("/proc", String(pid), "cmdline"), "utf8");
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ /**
81
+ * Tue les process pi orphelins d'un hôte Cogitator mort (SIGKILL, subreaper, pid réutilisé).
82
+ * Orphelin = marqueur `pid:starttime` + même `COGITATOR_HOME` + cmdline `--mode rpc`,
83
+ * et l'hôte n'est plus ce process (pid mort, starttime différent). Jamais un process
84
+ * sans marqueur, sans cmdline rpc, ni un process dont l'hôte est encore vivant.
85
+ */
86
+ export function reapOrphanOwnedPi(home, signal = "SIGKILL") {
87
+ if (process.platform === "win32")
88
+ return { pids: [] };
89
+ let names;
90
+ try {
91
+ names = readdirSync("/proc");
92
+ }
93
+ catch {
94
+ return { pids: [] };
95
+ }
96
+ const pids = [];
97
+ for (const name of names) {
98
+ if (!/^\d+$/.test(name))
99
+ continue;
100
+ const pid = Number(name);
101
+ if (pid === process.pid)
102
+ continue;
103
+ let environ;
104
+ try {
105
+ environ = readFileSync(join("/proc", name, "environ"), "utf8");
106
+ }
107
+ catch {
108
+ continue;
109
+ }
110
+ if (environEntry(environ, "COGITATOR_HOME") !== home)
111
+ continue;
112
+ const marker = parseOwnedPiMarker(environEntry(environ, OWNED_PI_ENV) ?? "");
113
+ if (!marker)
114
+ continue;
115
+ const cmdline = readCmdline(pid);
116
+ if (!cmdline || !isPiRpcCmdline(cmdline))
117
+ continue;
118
+ if (ownerStillAlive(marker))
119
+ continue;
120
+ pids.push(pid);
121
+ }
122
+ for (const pid of pids) {
123
+ try {
124
+ process.kill(pid, signal);
125
+ }
126
+ catch {
127
+ /* déjà mort */
128
+ }
129
+ }
130
+ return { pids };
131
+ }
132
+ export function startPeriodicReap(home, intervalMs = reapIntervalMs()) {
133
+ if (intervalMs <= 0)
134
+ return { stop() { } };
135
+ const timer = setInterval(() => { reapOrphanOwnedPi(home); }, intervalMs);
136
+ timer.unref?.();
137
+ return { stop() { clearInterval(timer); } };
138
+ }
@@ -1,9 +1,9 @@
1
- import { execFile } from "node:child_process";
2
- import { existsSync, readdirSync, readFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { builtinProviders, getBuiltinModels, getBuiltinProviders } from "@earendil-works/pi-ai/providers/all";
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
5
3
  import { readJson, atomicWriteJson } from "./json-files.js";
6
- import { MCP_NAME, PROVIDER_ID } from "./schemas.js";
4
+ import { piAiProviders, piCodingAgent } from "./host-pi.js";
5
+ import { fileCredentialStore } from "./provider-login.js";
6
+ import { MCP_NAME, PROVIDER_ID, THINKING_LEVELS } from "./schemas.js";
7
7
  export const API_PROTOCOLS = [
8
8
  "openai-completions",
9
9
  "openai-responses",
@@ -18,17 +18,39 @@ export const API_PROTOCOLS = [
18
18
  /** Limite imposée par pi sur la description d'un skill (frontmatter SKILL.md). */
19
19
  export const SKILL_DESCRIPTION_MAX = 1024;
20
20
  const AUTH_CHECK_TIMEOUT_MS = 15_000;
21
+ /** Niveaux supportés par un modèle du catalogue — miroir exact de `getSupportedThinkingLevels` de pi
22
+ * (agent-session) pour que le sélecteur web offre exactement ce que la validation d'application accepte. */
23
+ function supportedThinkingLevels(model) {
24
+ if (!model.reasoning)
25
+ return ["off"];
26
+ return THINKING_LEVELS.filter((level) => {
27
+ const mapped = model.thinkingLevelMap?.[level];
28
+ return mapped === null ? false : level === "xhigh" || level === "max" ? mapped !== undefined : true;
29
+ });
30
+ }
21
31
  function mapStoreModels(models) {
22
- return (models ?? []).map((m) => ({
23
- id: String(m.id),
24
- name: typeof m.name === "string" ? m.name : undefined,
25
- reasoning: typeof m.reasoning === "boolean" ? m.reasoning : undefined,
26
- }));
32
+ return (models ?? []).map((m) => {
33
+ const reasoning = typeof m.reasoning === "boolean" ? m.reasoning : undefined;
34
+ const thinkingLevelMap = m.thinkingLevelMap && typeof m.thinkingLevelMap === "object"
35
+ ? m.thinkingLevelMap
36
+ : undefined;
37
+ return {
38
+ id: String(m.id),
39
+ name: typeof m.name === "string" ? m.name : undefined,
40
+ reasoning,
41
+ levels: reasoning === undefined && !thinkingLevelMap ? undefined : supportedThinkingLevels({ reasoning, thinkingLevelMap }),
42
+ };
43
+ });
27
44
  }
28
45
  function overlayModels(base, extra) {
29
46
  const byId = new Map(base.map((model) => [model.id, model]));
30
- for (const model of extra)
31
- byId.set(model.id, model);
47
+ // Fusion : l'overlay gagne sur ses champs définis, mais hérite des champs du
48
+ // catalogue (ex. levels) qu'il ne mentionne pas — sinon un overlay nu effacerait
49
+ // les niveaux supportés connus du modèle.
50
+ for (const model of extra) {
51
+ const defined = Object.fromEntries(Object.entries(model).filter(([, value]) => value !== undefined));
52
+ byId.set(model.id, { ...byId.get(model.id), ...defined, id: model.id });
53
+ }
32
54
  const seen = new Set();
33
55
  const out = [];
34
56
  for (const model of extra) {
@@ -49,8 +71,8 @@ export function readCatalog(paths) {
49
71
  const store = readJson(join(paths.piAgentDir, "models-store.json"), {});
50
72
  const customs = readJson(paths.piModelsJson, {}).providers ?? {};
51
73
  const out = new Map();
52
- for (const id of getBuiltinProviders()) {
53
- out.set(id, getBuiltinModels(id).map((m) => ({ id: m.id, name: m.name, reasoning: m.reasoning })));
74
+ for (const id of piAiProviders.getBuiltinProviders()) {
75
+ out.set(id, piAiProviders.getBuiltinModels(id).map((m) => ({ id: m.id, name: m.name, reasoning: m.reasoning, levels: supportedThinkingLevels(m) })));
54
76
  }
55
77
  for (const [id, entry] of Object.entries(store)) {
56
78
  if (!entry.models?.length)
@@ -72,11 +94,11 @@ let authMethodsCache;
72
94
  export function authMethodsFor(id) {
73
95
  if (!authMethodsCache) {
74
96
  authMethodsCache = new Map();
75
- for (const provider of builtinProviders()) {
97
+ for (const provider of piAiProviders.builtinProviders()) {
76
98
  const methods = [];
77
99
  if (provider.auth.oauth)
78
100
  methods.push({ type: "oauth", name: provider.auth.oauth.loginLabel ?? provider.auth.oauth.name });
79
- if (provider.auth.apiKey)
101
+ if (provider.auth.apiKey?.login)
80
102
  methods.push({ type: "api_key", name: provider.auth.apiKey.name });
81
103
  authMethodsCache.set(provider.id, methods);
82
104
  }
@@ -86,44 +108,39 @@ export function authMethodsFor(id) {
86
108
  function readAuth(paths) {
87
109
  return readJson(paths.piAuthJson, {});
88
110
  }
89
- const authCache = new Map();
90
- const AUTH_TTL_MS = 60_000;
91
- function checkAuthReady(provider) {
92
- const cached = authCache.get(provider);
93
- if (cached && Date.now() - cached.at < AUTH_TTL_MS)
94
- return Promise.resolve(cached.ready);
95
- return new Promise((resolve) => {
96
- execFile("pi", ["auth", "check", "--provider", provider, "--json"], { timeout: AUTH_CHECK_TIMEOUT_MS }, (err, stdout) => {
97
- let ready = null;
98
- try {
99
- ready = JSON.parse(stdout).status === "ready";
100
- }
101
- catch {
102
- ready = null;
103
- }
104
- if (err && ready === null)
105
- ready = false;
106
- authCache.set(provider, { at: Date.now(), ready });
107
- resolve(ready);
108
- });
109
- });
110
- }
111
111
  /** providers enrichis : catalogue + source + statut auth. Prêt pour GET /api/providers. */
112
112
  export async function listProviders(paths) {
113
113
  const catalog = readCatalog(paths);
114
114
  const auth = readAuth(paths);
115
115
  const customs = readJson(paths.piModelsJson, {}).providers ?? {};
116
116
  const ids = new Set([...catalog.keys(), ...Object.keys(auth), ...Object.keys(customs)]);
117
+ // Same explicit files as login and RPC; never inspect another pi installation's home.
118
+ // checkAuth reports local availability only: no model request or OAuth refresh.
119
+ const runtime = await piCodingAgent.ModelRuntime.create({
120
+ credentials: fileCredentialStore(paths.piAuthJson),
121
+ modelsPath: paths.piModelsJson,
122
+ allowModelNetwork: false,
123
+ refreshOnCreate: false,
124
+ });
117
125
  const views = await Promise.all([...ids].map(async (id) => {
118
- const configured = Boolean(auth[id]);
126
+ let check;
127
+ let ready = null;
128
+ try {
129
+ if (!runtime.getError()) {
130
+ check = await runtime.checkAuth(id, { signal: AbortSignal.timeout(AUTH_CHECK_TIMEOUT_MS) });
131
+ ready = Boolean(check);
132
+ }
133
+ }
134
+ catch { /* Unavailable local check is distinct from missing credentials. */ }
135
+ const configured = Boolean(auth[id]) || Boolean(check);
119
136
  return {
120
137
  id,
121
138
  source: customs[id] ? "custom" : "builtin",
122
139
  models: catalog.get(id) ?? [],
123
140
  auth: {
124
141
  configured,
125
- type: auth[id]?.type ?? null,
126
- ready: configured ? await checkAuthReady(id) : false,
142
+ type: auth[id]?.type ?? check?.type ?? null,
143
+ ready,
127
144
  },
128
145
  authMethods: authMethodsFor(id),
129
146
  };
@@ -144,6 +161,7 @@ export function upsertProvider(paths, id, input) {
144
161
  const protocolError = validateProtocol(input.api);
145
162
  if (protocolError)
146
163
  return { error: protocolError };
164
+ mkdirSync(paths.piAgentDir, { recursive: true, mode: 0o700 });
147
165
  const file = readJson(paths.piModelsJson, {});
148
166
  file.providers ??= {};
149
167
  const existing = file.providers[id] ?? {};
@@ -159,7 +177,7 @@ export function upsertProvider(paths, id, input) {
159
177
  if (input.apiKey !== undefined) {
160
178
  const auth = readAuth(paths);
161
179
  auth[id] = { type: "api_key", key: input.apiKey };
162
- atomicWriteJson(paths.piAuthJson, auth);
180
+ atomicWriteJson(paths.piAuthJson, auth, 0o600);
163
181
  }
164
182
  return {};
165
183
  }
@@ -172,11 +190,11 @@ export function deleteProvider(paths, id) {
172
190
  const auth = readAuth(paths);
173
191
  if (auth[id]) {
174
192
  delete auth[id];
175
- atomicWriteJson(paths.piAuthJson, auth);
193
+ atomicWriteJson(paths.piAuthJson, auth, 0o600);
176
194
  }
177
195
  }
178
196
  // ---------- Skills (scan) ----------
179
- export function listSkills(paths) {
197
+ export function listSkills(paths, cwd = paths.home) {
180
198
  const out = [];
181
199
  for (const dir of paths.skillsDirs) {
182
200
  if (!existsSync(dir))
@@ -199,7 +217,12 @@ export function listSkills(paths) {
199
217
  });
200
218
  }
201
219
  }
202
- return out.sort((a, b) => a.name.localeCompare(b.name));
220
+ const merged = new Map(out.map(s => [s.path, s]));
221
+ for (const skill of piCodingAgent.loadSkills({ cwd, agentDir: paths.piAgentDir, skillPaths: [...paths.skillsDirs, join(cwd, ".agents/skills"), join(cwd, ".pi/skills")], includeDefaults: false }).skills) {
222
+ const path = dirname(skill.filePath);
223
+ merged.set(path, { name: skill.name, description: skill.description, path, descriptionTooLong: skill.description.length > SKILL_DESCRIPTION_MAX });
224
+ }
225
+ return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
203
226
  }
204
227
  // ---------- MCP user-level ----------
205
228
  export function readMcp(paths) {
@@ -30,7 +30,7 @@ export const providerLoginSchema = z.object({
30
30
  type: z.enum(["api_key", "oauth"]),
31
31
  });
32
32
  export const providerLoginReplySchema = z.object({
33
- value: z.string().min(1),
33
+ value: z.string().max(32_768),
34
34
  });
35
35
  // ---------- Agents ----------
36
36
  export const subagentInputSchema = z.object({
@@ -58,11 +58,16 @@ export const agentInputSchema = z.object({
58
58
  default_workspace_id: z.string().nullable().optional(),
59
59
  });
60
60
  // ---------- Workspaces ----------
61
- export const workspaceCreateSchema = z.object({
62
- dir: z.string().min(1, "dir requis"),
61
+ /** `dir` (dossier local) ou `git_url` (clone GitHub), jamais les deux. */
62
+ export const workspaceCreateSchema = z
63
+ .object({
64
+ dir: z.string().min(1, "dir requis").optional(),
65
+ git_url: z.string().min(1, "URL git requise").optional(),
63
66
  name: z.string().optional(),
64
67
  default_agent_id: z.string().nullable().optional(),
65
- });
68
+ })
69
+ .refine((v) => !(v.dir && v.git_url), { message: "fournir dir ou git_url (pas les deux)" })
70
+ .refine((v) => Boolean(v.dir) || Boolean(v.git_url), { message: "dir ou git_url requis" });
66
71
  export const workspaceUpdateSchema = z.object({
67
72
  name: z.string().optional(),
68
73
  default_agent_id: z.string().nullable().optional(),
@@ -178,3 +183,13 @@ export const skillImportSchema = z.object({
178
183
  source: z.string().min(1, "source requise (URL GitHub ou chemin local)"),
179
184
  overwrite: z.boolean().optional(),
180
185
  });
186
+ /** Relais d'un agent vers une conversation (file durable lot 2). */
187
+ export const teamSendSchema = z.object({
188
+ conversation_id: z.string().min(1),
189
+ body: z.string().min(1),
190
+ from_conversation_id: z.string().min(1).optional(),
191
+ from_agent_id: z.string().min(1).optional(),
192
+ chain_id: z.string().min(1).optional(),
193
+ hop: z.number().int().nonnegative().optional(),
194
+ idempotency_key: z.string().min(1).optional(),
195
+ });