@ignitionai/cogitator 0.4.1 → 0.5.0
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 +30 -8
- package/dist/extensions/index.js +1 -1
- package/dist/src/classic-configuration.js +153 -0
- package/dist/src/conversations.js +9 -7
- package/dist/src/db.js +52 -3
- package/dist/src/default-agent.js +1 -1
- package/dist/src/durable/admission.js +131 -0
- package/dist/src/durable/approvals.js +171 -0
- package/dist/src/durable/compatibility.js +59 -0
- package/dist/src/durable/effect-gateway.js +68 -0
- package/dist/src/durable/lease.js +48 -0
- package/dist/src/durable/manager.js +167 -0
- package/dist/src/durable/mission-runtime.js +460 -0
- package/dist/src/durable/profile.js +79 -0
- package/dist/src/durable/workers.js +42 -0
- package/dist/src/execution/admission.js +45 -0
- package/dist/src/execution/confinement.js +108 -0
- package/dist/src/execution/container.js +102 -0
- package/dist/src/execution/egress.js +69 -0
- package/dist/src/groups.js +71 -0
- package/dist/src/pool.js +193 -72
- package/dist/src/provider-login.js +115 -0
- package/dist/src/registry.js +72 -14
- package/dist/src/runtime.js +92 -0
- package/dist/src/schemas.js +45 -0
- package/dist/src/server.js +423 -23
- package/dist/src/spawner.js +34 -12
- package/dist/src/workspace-files.js +6 -5
- package/dist/src/workspaces.js +19 -6
- package/package.json +4 -1
- package/web/dist/assets/index-C3tRuOTh.js +83 -0
- package/web/dist/assets/index-DMQqB0r1.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-D3Q54zLM.js +0 -83
- package/web/dist/assets/index-Kj5NVQYi.css +0 -1
package/README.md
CHANGED
|
@@ -19,27 +19,48 @@ The entire application interface is available in **English and French**. Use the
|
|
|
19
19
|
|
|
20
20
|
User content, agent responses, editable agent presets, code, files, and technical identifiers are preserved as authored. Cogitator’s controls and diagnostic explanations are translated; external diagnostic details remain available in their original form. The documentation is in English.
|
|
21
21
|
|
|
22
|
-
##
|
|
22
|
+
## Install the pi extension
|
|
23
|
+
|
|
24
|
+
Cogitator ships as a [pi package](https://pi.dev/packages). `pi install` **does not start the app**. It only registers an extension: a `/cogitator` slash command, loaded the next time you open pi. The extension itself stays idle until you run that command (it must not spawn a server just because pi started).
|
|
25
|
+
|
|
26
|
+
You need [pi](https://pi.dev) and **Node.js ≥ 22.19.0**.
|
|
23
27
|
|
|
24
28
|
```sh
|
|
25
29
|
pi install npm:@ignitionai/cogitator
|
|
26
30
|
```
|
|
27
31
|
|
|
28
|
-
Then,
|
|
32
|
+
Confirm with `pi list`. Then, **inside a pi session**, type:
|
|
29
33
|
|
|
30
34
|
```text
|
|
31
|
-
/cogitator
|
|
35
|
+
/cogitator
|
|
32
36
|
```
|
|
33
37
|
|
|
34
|
-
|
|
38
|
+
What that does:
|
|
39
|
+
|
|
40
|
+
1. Looks for a Cogitator server already answering on `http://127.0.0.1:5320`.
|
|
41
|
+
2. If none is up, starts `cogitator` in the **background** (detached). Closing pi does not stop it — scheduled tasks keep running.
|
|
42
|
+
3. Opens the control panel in your default browser.
|
|
43
|
+
4. Prints the URL in pi. Default: `http://127.0.0.1:5320`.
|
|
44
|
+
|
|
45
|
+
State lives in `~/.cogitator` (SQLite catalog). Conversation transcripts stay in pi’s own JSONL files. Later: `pi update --extensions` to refresh, `pi remove npm:@ignitionai/cogitator` to uninstall the package (this does not delete `~/.cogitator`).
|
|
46
|
+
|
|
47
|
+
If pi reports **Cogitator unavailable**: something else is bound to port 5320, or an older/incompatible Cogitator is still running. Stop that process and run `/cogitator` again. Auth-required instances also refuse a plain loopback probe until owner login is in place.
|
|
48
|
+
|
|
49
|
+
### Run the server yourself
|
|
50
|
+
|
|
51
|
+
Same process, foreground, no pi session:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
npx @ignitionai/cogitator
|
|
55
|
+
```
|
|
35
56
|
|
|
36
|
-
|
|
57
|
+
Logs the URL, then waits. Ctrl+C stops it. After a global npm install you can also run `cogitator`. Optional flags: `cogitator --auth-required`, and `cogitator auth init|recover|setup-key` for single-owner login. Override bind with `COGITATOR_PORT` / `COGITATOR_URL` if 5320 is taken.
|
|
37
58
|
|
|
38
|
-
|
|
59
|
+
### Local loopback only
|
|
39
60
|
|
|
40
|
-
The
|
|
61
|
+
The default app is a **trusted service on 127.0.0.1**, not a secured remote product. Do not put it behind a public proxy.
|
|
41
62
|
|
|
42
|
-
|
|
63
|
+
[Native single-owner login and MFA](https://github.com/IgnitionAI/cogitator/blob/dev/docs/native-auth.md) has passed independent code re-reviews and bounded local verification (Node 22/26, real local HTTPS/browser journeys). Login is **not** isolation of agent execution. Public remote operation, autonomous recovery, and the remaining Durable work are not approved. See the [evidence and remaining gates](https://github.com/IgnitionAI/cogitator/blob/dev/docs/native-auth-verification.md).
|
|
43
64
|
|
|
44
65
|
## Features
|
|
45
66
|
|
|
@@ -49,6 +70,7 @@ The earlier [identity-service inventory](https://github.com/IgnitionAI/cogitator
|
|
|
49
70
|
- **GitHub-native kanban** — each card is a GitHub issue, with `status:`/`priority:` labels, native blocking relationships, and writes through `gh`. No synchronization layer: GitHub remains the single source of truth.
|
|
50
71
|
- **Agent dispatch** — use “Lancer l’agent” (launch agent) on a ticket to start a conversation in its workspace, link the card to its activity, and move it to in progress.
|
|
51
72
|
- **Conversations** — SSE streaming with reconnection recovery, copyable code, structured tool output and diffs, pasted images, history, and skills invoked with `/skill:name`.
|
|
73
|
+
- **Live model settings** — change provider, model and reasoning in a classic chat or for an individual group member, without losing history. Changes wait for the current response to finish. Apply to the conversation only, or explicitly also save the bot's defaults for future conversations; existing sibling chats stay unchanged. Durable missions keep their frozen configuration. A pending change interrupted by a controller restart requires an explicit retry.
|
|
52
74
|
- **Automatic interactive UI** — agents choose between text, forms, choices, checklists, and tables as needed, in both standalone and workspace conversations. Responses are submitted explicitly and saved in pi JSONL transcripts. Generated HTML and JavaScript are never executed. See the [contract and limitations](https://github.com/IgnitionAI/cogitator/blob/dev/docs/chat-generative-ui.md).
|
|
53
75
|
- **Scheduled tasks** — cron scheduling with concurrent-run protection, catch-up behavior, run history, and notifications.
|
|
54
76
|
- **Providers and skills** — inspect pi configuration, check authentication with `pi auth check`, use atomic writes with backups, and import skills from GitHub, local directories, or npm commands.
|
package/dist/extensions/index.js
CHANGED
|
@@ -46,7 +46,7 @@ export default function (pi) {
|
|
|
46
46
|
}
|
|
47
47
|
});
|
|
48
48
|
pi.registerCommand("cogitator", {
|
|
49
|
-
description: "
|
|
49
|
+
description: "Start the local Cogitator web panel if needed, then open it in the browser",
|
|
50
50
|
handler: async (_args, ctx) => {
|
|
51
51
|
if (!(await isUp())) {
|
|
52
52
|
const here = dirname(fileURLToPath(import.meta.url)); // dist/extensions
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { applyAgent, getAgent } from "./agents.js";
|
|
3
|
+
import { getConversation } from "./conversations.js";
|
|
4
|
+
import { checkRequestAuthorization } from "./request-authorization.js";
|
|
5
|
+
import { THINKING_LEVELS } from "./schemas.js";
|
|
6
|
+
export class ConfigurationError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
constructor(message, status = 502) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.status = status;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function conversation(db, id) {
|
|
14
|
+
const conv = getConversation(db, id);
|
|
15
|
+
if (!conv)
|
|
16
|
+
throw new ConfigurationError("conversation not found", 404);
|
|
17
|
+
if (conv.runtime_kind === "durable")
|
|
18
|
+
throw new ConfigurationError("Durable configuration is immutable", 409);
|
|
19
|
+
return conv;
|
|
20
|
+
}
|
|
21
|
+
async function readTuple(client) {
|
|
22
|
+
const state = await client.getState();
|
|
23
|
+
if (!state.model || !state.thinkingLevel)
|
|
24
|
+
throw new ConfigurationError("RPC configuration readback unavailable");
|
|
25
|
+
return { provider: state.model.provider, model: state.model.id, thinking: state.thinkingLevel };
|
|
26
|
+
}
|
|
27
|
+
async function select(client, target) {
|
|
28
|
+
const before = await readTuple(client);
|
|
29
|
+
const thinking = target.thinking ?? before.thinking;
|
|
30
|
+
if (!(await client.getAvailableModels()).some(m => m.provider === target.provider && m.id === target.model)) {
|
|
31
|
+
throw new ConfigurationError("unsupported model", 422);
|
|
32
|
+
}
|
|
33
|
+
if (before.provider !== target.provider || before.model !== target.model)
|
|
34
|
+
await client.setModel(target.provider, target.model);
|
|
35
|
+
const levels = await client.getAvailableThinkingLevels();
|
|
36
|
+
if (!thinking || !THINKING_LEVELS.includes(thinking) || !levels.includes(thinking)) {
|
|
37
|
+
throw new ConfigurationError("unsupported thinking level for target model", 422);
|
|
38
|
+
}
|
|
39
|
+
await client.setThinkingLevel(thinking);
|
|
40
|
+
const actual = await readTuple(client);
|
|
41
|
+
if (actual.provider !== target.provider || actual.model !== target.model || actual.thinking !== thinking) {
|
|
42
|
+
throw new ConfigurationError("RPC configuration readback mismatch");
|
|
43
|
+
}
|
|
44
|
+
return actual;
|
|
45
|
+
}
|
|
46
|
+
function writeTuple(db, conv, tuple) {
|
|
47
|
+
const spawn = { ...JSON.parse(conv.spawn_args), ...tuple };
|
|
48
|
+
db.prepare("UPDATE conversation SET provider = ?, model = ?, thinking = ?, spawn_args = ?, updated_at = datetime('now') WHERE id = ?")
|
|
49
|
+
.run(tuple.provider, tuple.model, tuple.thinking, JSON.stringify(spawn), conv.id);
|
|
50
|
+
}
|
|
51
|
+
function publish(db, pool, id) {
|
|
52
|
+
pool.emit(id, { type: "configuration_changed", conversation: getConversation(db, id) });
|
|
53
|
+
}
|
|
54
|
+
function pending(db, pool, id, value) {
|
|
55
|
+
db.prepare("UPDATE conversation SET pending_configuration = ? WHERE id = ?").run(value ? JSON.stringify(value) : null, id);
|
|
56
|
+
publish(db, pool, id);
|
|
57
|
+
}
|
|
58
|
+
/** Called inside pool startup lock, before the handle becomes usable. */
|
|
59
|
+
export async function reconcileConfiguration(db, pool, id, client) {
|
|
60
|
+
const conv = conversation(db, id);
|
|
61
|
+
const actual = await select(client, conv);
|
|
62
|
+
checkRequestAuthorization();
|
|
63
|
+
writeTuple(db, conv, actual);
|
|
64
|
+
publish(db, pool, id);
|
|
65
|
+
}
|
|
66
|
+
/** Restart cannot recreate the original authorization check: retain visible, retryable failure. */
|
|
67
|
+
export function recoverConfigurations(db) {
|
|
68
|
+
const rows = db.prepare("SELECT id FROM conversation WHERE pending_configuration IS NOT NULL AND runtime_kind = 'classic'").all();
|
|
69
|
+
for (const { id } of rows) {
|
|
70
|
+
const p = getConversation(db, id)?.pending_configuration;
|
|
71
|
+
if (p?.status === "pending")
|
|
72
|
+
db.prepare("UPDATE conversation SET pending_configuration = ? WHERE id = ?")
|
|
73
|
+
.run(JSON.stringify({ ...p, status: "failed", error: "Controller restarted; renew authorization by retrying this change" }), id);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function changeConfiguration(deps, id, input) {
|
|
77
|
+
const { db, pool, paths } = deps;
|
|
78
|
+
// Reserve synchronously, so competing HTTP calls cannot wait out an applying request.
|
|
79
|
+
const conv = conversation(db, id);
|
|
80
|
+
const scope = input.scope ?? "conversation";
|
|
81
|
+
if (scope !== "conversation" && scope !== "preset")
|
|
82
|
+
throw new ConfigurationError("invalid scope", 409);
|
|
83
|
+
if (conv.pending_configuration?.status === "pending")
|
|
84
|
+
throw new ConfigurationError("configuration outstanding", 409);
|
|
85
|
+
if (scope === "preset" && !conv.agent_id)
|
|
86
|
+
throw new ConfigurationError("preset scope requires a linked preset", 409);
|
|
87
|
+
if (scope === "preset" && !getAgent(db, conv.agent_id))
|
|
88
|
+
throw new ConfigurationError("preset not found", 404);
|
|
89
|
+
checkRequestAuthorization();
|
|
90
|
+
const request = { request_id: randomUUID(), provider: input.provider, model: input.id, thinking: input.thinking ?? conv.thinking, scope, status: "pending" };
|
|
91
|
+
pending(db, pool, id, request);
|
|
92
|
+
let applied = false;
|
|
93
|
+
try {
|
|
94
|
+
await pool.serial(id, async () => {
|
|
95
|
+
await deps.ensure(conversation(db, id));
|
|
96
|
+
applied = await pool.configure(id, async () => {
|
|
97
|
+
const client = pool.client(id);
|
|
98
|
+
let old;
|
|
99
|
+
let previousPreset = null;
|
|
100
|
+
try {
|
|
101
|
+
checkRequestAuthorization();
|
|
102
|
+
old = await readTuple(client);
|
|
103
|
+
const actual = await select(client, request);
|
|
104
|
+
checkRequestAuthorization();
|
|
105
|
+
db.transaction(() => {
|
|
106
|
+
const current = conversation(db, id);
|
|
107
|
+
writeTuple(db, current, actual);
|
|
108
|
+
if (scope === "preset") {
|
|
109
|
+
previousPreset = getAgent(db, conv.agent_id);
|
|
110
|
+
if (!previousPreset)
|
|
111
|
+
throw new ConfigurationError("preset not found", 404);
|
|
112
|
+
db.prepare("UPDATE agent_preset SET provider = ?, model = ?, thinking = ?, updated_at = datetime('now') WHERE id = ?")
|
|
113
|
+
.run(actual.provider, actual.model, actual.thinking, conv.agent_id);
|
|
114
|
+
applyAgent(paths, getAgent(db, conv.agent_id));
|
|
115
|
+
}
|
|
116
|
+
db.prepare("UPDATE conversation SET pending_configuration = NULL WHERE id = ?").run(id);
|
|
117
|
+
})();
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
try {
|
|
121
|
+
if (!old)
|
|
122
|
+
throw error;
|
|
123
|
+
await select(client, old);
|
|
124
|
+
if (previousPreset)
|
|
125
|
+
applyAgent(paths, previousPreset);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
await pool.evict(id);
|
|
129
|
+
}
|
|
130
|
+
pending(db, pool, id, { ...request, status: "failed", error: error instanceof Error ? error.message : String(error) });
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
publish(db, pool, id);
|
|
134
|
+
if (scope === "preset")
|
|
135
|
+
deps.onPresetChanged?.();
|
|
136
|
+
}, () => pending(db, pool, id, { ...request, status: "failed", error: "Session stopped before configuration applied; retry required" }));
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (getConversation(db, id)?.pending_configuration?.status === "pending")
|
|
141
|
+
pending(db, pool, id, { ...request, status: "failed", error: String(error) });
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
return { status: applied ? 200 : 202, conversation: conversation(db, id) };
|
|
145
|
+
}
|
|
146
|
+
export function dismissConfiguration(db, pool, id) {
|
|
147
|
+
const conv = conversation(db, id);
|
|
148
|
+
if (conv.pending_configuration?.status !== "failed")
|
|
149
|
+
throw new ConfigurationError("only failed configuration can be dismissed", 409);
|
|
150
|
+
checkRequestAuthorization();
|
|
151
|
+
pending(db, pool, id, null);
|
|
152
|
+
return conversation(db, id);
|
|
153
|
+
}
|
|
@@ -6,6 +6,7 @@ export function listConversations(db, workspaceId, agentId) {
|
|
|
6
6
|
const where = [
|
|
7
7
|
workspaceId ? "c.workspace_id = ?" : "",
|
|
8
8
|
agentId ? "c.agent_id = ?" : "",
|
|
9
|
+
"c.group_id IS NULL", // les sessions membres ne sont pas des fils 1–1 (resume-last, ADR-011)
|
|
9
10
|
].filter(Boolean).join(" AND ");
|
|
10
11
|
const sql = `
|
|
11
12
|
SELECT c.*, w.dir AS workspace_dir FROM conversation c
|
|
@@ -13,19 +14,19 @@ export function listConversations(db, workspaceId, agentId) {
|
|
|
13
14
|
${where ? `WHERE ${where}` : ""}
|
|
14
15
|
ORDER BY c.updated_at DESC`;
|
|
15
16
|
const params = [workspaceId, agentId].filter((v) => Boolean(v));
|
|
16
|
-
return (params.length ? db.prepare(sql).all(...params) : db.prepare(sql).all());
|
|
17
|
+
return (params.length ? db.prepare(sql).all(...params) : db.prepare(sql).all()).map(parseConversation);
|
|
17
18
|
}
|
|
18
19
|
export function getConversation(db, id) {
|
|
19
20
|
const row = db
|
|
20
21
|
.prepare(`SELECT c.*, w.dir AS workspace_dir FROM conversation c
|
|
21
22
|
LEFT JOIN workspace w ON w.id = c.workspace_id WHERE c.id = ?`)
|
|
22
23
|
.get(id);
|
|
23
|
-
return row
|
|
24
|
+
return row ? parseConversation(row) : null;
|
|
24
25
|
}
|
|
25
26
|
export function createConversation(db, input) {
|
|
26
27
|
const id = randomUUID();
|
|
27
|
-
db.prepare(`INSERT INTO conversation (id, workspace_id, agent_id, provider, model, thinking, spawn_args, status)
|
|
28
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, 'idle')`).run(id, input.workspaceId ?? null, input.agentId ?? null, input.spawn.provider, input.spawn.model, input.spawn.thinking ?? null, JSON.stringify({ ...input.spawn, uiInstructions: UI_INSTRUCTIONS }));
|
|
28
|
+
db.prepare(`INSERT INTO conversation (id, workspace_id, agent_id, group_id, provider, model, thinking, spawn_args, status, runtime_kind)
|
|
29
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'idle', ?)`).run(id, input.workspaceId ?? null, input.agentId ?? null, input.groupId ?? null, input.spawn.provider, input.spawn.model, input.spawn.thinking ?? null, JSON.stringify({ ...input.spawn, uiInstructions: UI_INSTRUCTIONS }), input.runtimeKind ?? "classic");
|
|
29
30
|
return getConversation(db, id);
|
|
30
31
|
}
|
|
31
32
|
export function setConversationStatus(db, id, status) {
|
|
@@ -37,9 +38,10 @@ export function setConversationSession(db, id, sessionFile) {
|
|
|
37
38
|
export function setConversationTitle(db, id, title) {
|
|
38
39
|
db.prepare("UPDATE conversation SET title = CASE WHEN title = '' THEN ? ELSE title END, updated_at = datetime('now') WHERE id = ?").run(title.slice(0, TITLE_MAX), id);
|
|
39
40
|
}
|
|
40
|
-
export function setConversationModel(db, id, provider, model, spawn) {
|
|
41
|
-
db.prepare("UPDATE conversation SET provider = ?, model = ?, spawn_args = ?, updated_at = datetime('now') WHERE id = ?").run(provider, model, JSON.stringify(spawn), id);
|
|
42
|
-
}
|
|
43
41
|
export function deleteConversation(db, id) {
|
|
44
42
|
return db.prepare("DELETE FROM conversation WHERE id = ?").run(id).changes > 0;
|
|
45
43
|
}
|
|
44
|
+
function parseConversation(row) {
|
|
45
|
+
const raw = row.pending_configuration;
|
|
46
|
+
return { ...row, pending_configuration: typeof raw === "string" ? JSON.parse(raw) : raw ?? null };
|
|
47
|
+
}
|
package/dist/src/db.js
CHANGED
|
@@ -103,6 +103,35 @@ ALTER TABLE conversation_v2 RENAME TO conversation;
|
|
|
103
103
|
// v2 → v3 : agent par défaut global (le "Majordome")
|
|
104
104
|
const MIGRATE_V2_TO_V3 = `ALTER TABLE agent_preset ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0;`;
|
|
105
105
|
const MIGRATE_V3_TO_V4 = `ALTER TABLE agent_preset ADD COLUMN default_workspace_id TEXT REFERENCES workspace(id) ON DELETE SET NULL;`;
|
|
106
|
+
// v4 → v5 : groupes de bots (ADR-011) — agrégat Cogitator, membres = conversations privées
|
|
107
|
+
const MIGRATE_V4_TO_V5 = `
|
|
108
|
+
CREATE TABLE IF NOT EXISTS agent_group (
|
|
109
|
+
id TEXT PRIMARY KEY,
|
|
110
|
+
name TEXT NOT NULL,
|
|
111
|
+
host_agent_id TEXT NOT NULL REFERENCES agent_preset(id) ON DELETE CASCADE,
|
|
112
|
+
default_workspace_id TEXT REFERENCES workspace(id) ON DELETE SET NULL,
|
|
113
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
114
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
115
|
+
);
|
|
116
|
+
ALTER TABLE conversation ADD COLUMN group_id TEXT REFERENCES agent_group(id) ON DELETE CASCADE;
|
|
117
|
+
`;
|
|
118
|
+
// v5 → v6 : bus de fil de groupe (ADR-011) — log Cogitator, pas un jsonl pi partagé
|
|
119
|
+
const MIGRATE_V5_TO_V6 = `
|
|
120
|
+
CREATE TABLE IF NOT EXISTS group_message (
|
|
121
|
+
id TEXT PRIMARY KEY,
|
|
122
|
+
group_id TEXT NOT NULL REFERENCES agent_group(id) ON DELETE CASCADE,
|
|
123
|
+
conversation_id TEXT REFERENCES conversation(id) ON DELETE SET NULL,
|
|
124
|
+
agent_id TEXT REFERENCES agent_preset(id) ON DELETE SET NULL,
|
|
125
|
+
role TEXT NOT NULL,
|
|
126
|
+
text TEXT NOT NULL DEFAULT '',
|
|
127
|
+
detail TEXT,
|
|
128
|
+
is_error INTEGER NOT NULL DEFAULT 0,
|
|
129
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
130
|
+
);
|
|
131
|
+
CREATE INDEX IF NOT EXISTS idx_group_message_group ON group_message(group_id, created_at);
|
|
132
|
+
`;
|
|
133
|
+
// v6 → v7 : runtime_kind figé à la création (classic | durable, Plan 0002 §6 ; D2/D3)
|
|
134
|
+
const MIGRATE_V6_TO_V7 = `ALTER TABLE conversation ADD COLUMN runtime_kind TEXT NOT NULL DEFAULT 'classic';`;
|
|
106
135
|
export function openDb(dbPath) {
|
|
107
136
|
const db = new Database(dbPath);
|
|
108
137
|
db.pragma("journal_mode = WAL");
|
|
@@ -112,8 +141,12 @@ export function openDb(dbPath) {
|
|
|
112
141
|
db.exec(SCHEMA_V2);
|
|
113
142
|
db.exec(MIGRATE_V2_TO_V3);
|
|
114
143
|
db.exec(MIGRATE_V3_TO_V4);
|
|
115
|
-
db.
|
|
116
|
-
|
|
144
|
+
db.exec(MIGRATE_V4_TO_V5);
|
|
145
|
+
db.exec(MIGRATE_V5_TO_V6);
|
|
146
|
+
db.exec(MIGRATE_V6_TO_V7);
|
|
147
|
+
db.exec("ALTER TABLE conversation ADD COLUMN pending_configuration TEXT");
|
|
148
|
+
db.pragma("user_version = 8");
|
|
149
|
+
return { db, version: 8 };
|
|
117
150
|
}
|
|
118
151
|
if (version < 2) {
|
|
119
152
|
// FK OFF pendant la migration (pratique SQLite standard ; les parents peuvent être créés plus tard)
|
|
@@ -130,5 +163,21 @@ export function openDb(dbPath) {
|
|
|
130
163
|
db.exec(MIGRATE_V3_TO_V4);
|
|
131
164
|
db.pragma("user_version = 4");
|
|
132
165
|
}
|
|
133
|
-
|
|
166
|
+
if (version < 5) {
|
|
167
|
+
db.exec(MIGRATE_V4_TO_V5);
|
|
168
|
+
db.pragma("user_version = 5");
|
|
169
|
+
}
|
|
170
|
+
if (version < 6) {
|
|
171
|
+
db.exec(MIGRATE_V5_TO_V6);
|
|
172
|
+
db.pragma("user_version = 6");
|
|
173
|
+
}
|
|
174
|
+
if (version < 7) {
|
|
175
|
+
db.exec(MIGRATE_V6_TO_V7);
|
|
176
|
+
db.pragma("user_version = 7");
|
|
177
|
+
}
|
|
178
|
+
if (version < 8) {
|
|
179
|
+
db.exec("ALTER TABLE conversation ADD COLUMN pending_configuration TEXT");
|
|
180
|
+
db.pragma("user_version = 8");
|
|
181
|
+
}
|
|
182
|
+
return { db, version: 8 };
|
|
134
183
|
}
|
|
@@ -51,7 +51,7 @@ C. EXÉCUTER après validation, et terminer par un bilan : ce qui a été créé
|
|
|
51
51
|
|
|
52
52
|
Règles de conduite :
|
|
53
53
|
1. Avant toute action destructive (suppression), confirme explicitement avec l'utilisateur.
|
|
54
|
-
2. Quand tu crées un agent, propose de le valider (cogitator_validate_agent) après création.
|
|
54
|
+
2. Quand tu crées un agent, propose de le valider (cogitator_validate_agent) après création. Si l'utilisateur ne précise pas provider/modèle, réutilise les tiens (cogitator_get_agent sur ta propre fiche si besoin).
|
|
55
55
|
3. Pour les expressions cron, propose du clair ("tous les jours à 9h" → "0 9 * * *").
|
|
56
56
|
4. Réponds en français, court et structuré.
|
|
57
57
|
5. Si un outil renvoie une erreur, explique-la et propose une correction.`;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admission des missions (Plan 0002 §5/§7, ADR-008 D7, UA3) :
|
|
3
|
+
* - au plus DEUX missions s'exécutent en concurrence ; une troisième file
|
|
4
|
+
* visiblement (état `queued`, jamais de travail caché) ;
|
|
5
|
+
* - une mission détient un claim EXCLUSIF sur son workspace : deux jobs ne
|
|
6
|
+
* courent jamais sur le même checkout ; le claim n'est relâché qu'après
|
|
7
|
+
* l'arrêt des écritures (waitForIdle confirmé côté runtime) ;
|
|
8
|
+
* - les budgets : seul le gate QUOTIDIEN se réinitialise, à minuit UTC ;
|
|
9
|
+
* les limites par mission ne se réinitialisent JAMAIS implicitement ; l'UI
|
|
10
|
+
* nomme la limite liante et la prochaine action (UA3) ;
|
|
11
|
+
* - l'attente (queued, budget_paused) ne consomme pas de slot d'exécution.
|
|
12
|
+
*/
|
|
13
|
+
export class MissionSlotPool {
|
|
14
|
+
capacity;
|
|
15
|
+
holders = new Set();
|
|
16
|
+
queue = [];
|
|
17
|
+
constructor(capacity = 2) {
|
|
18
|
+
this.capacity = capacity;
|
|
19
|
+
}
|
|
20
|
+
get running() {
|
|
21
|
+
return [...this.holders];
|
|
22
|
+
}
|
|
23
|
+
get queued() {
|
|
24
|
+
return [...this.queue];
|
|
25
|
+
}
|
|
26
|
+
/** Tente d'admettre une mission ; sinon la met en file (visible), FIFO. */
|
|
27
|
+
tryAcquire(missionId) {
|
|
28
|
+
if (this.holders.has(missionId))
|
|
29
|
+
return { admitted: true };
|
|
30
|
+
if (this.holders.size < this.capacity) {
|
|
31
|
+
this.holders.add(missionId);
|
|
32
|
+
return { admitted: true };
|
|
33
|
+
}
|
|
34
|
+
if (!this.queue.includes(missionId))
|
|
35
|
+
this.queue.push(missionId);
|
|
36
|
+
return { admitted: false, reason: "slots_missions_pleins" };
|
|
37
|
+
}
|
|
38
|
+
/** Relâche le slot et promeut la mission en tête de file s'il y a place. */
|
|
39
|
+
release(missionId) {
|
|
40
|
+
this.holders.delete(missionId);
|
|
41
|
+
const i = this.queue.indexOf(missionId);
|
|
42
|
+
if (i >= 0)
|
|
43
|
+
this.queue.splice(i, 1);
|
|
44
|
+
const next = this.queue[0];
|
|
45
|
+
if (next !== undefined && this.holders.size < this.capacity) {
|
|
46
|
+
this.queue.shift();
|
|
47
|
+
this.holders.add(next);
|
|
48
|
+
return next;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export class WorkspaceClaims {
|
|
54
|
+
byDir = new Map();
|
|
55
|
+
/** Claim exclusif : un second job sur le même dossier attend (ne race pas). */
|
|
56
|
+
acquire(dir, missionId) {
|
|
57
|
+
const holder = this.byDir.get(dir);
|
|
58
|
+
if (holder && holder !== missionId)
|
|
59
|
+
return { claimed: false, heldBy: holder };
|
|
60
|
+
this.byDir.set(dir, missionId);
|
|
61
|
+
return { claimed: true };
|
|
62
|
+
}
|
|
63
|
+
/** Relâche uniquement si la mission en est le détenteur (jamais le claim d'autrui). */
|
|
64
|
+
release(dir, missionId) {
|
|
65
|
+
if (this.byDir.get(dir) === missionId)
|
|
66
|
+
this.byDir.delete(dir);
|
|
67
|
+
}
|
|
68
|
+
holder(dir) {
|
|
69
|
+
return this.byDir.get(dir);
|
|
70
|
+
}
|
|
71
|
+
/** Vue pour l'observabilité et les tests. */
|
|
72
|
+
entries() {
|
|
73
|
+
return Object.fromEntries(this.byDir);
|
|
74
|
+
}
|
|
75
|
+
/** Relâche tous les claims détenus par une mission (fermeture de runtime). */
|
|
76
|
+
releaseByMission(missionId) {
|
|
77
|
+
for (const [dir, holder] of this.byDir) {
|
|
78
|
+
if (holder === missionId)
|
|
79
|
+
this.byDir.delete(dir);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Jour civil UTC `YYYY-MM-DD` — la SEULE frontière de reset automatique. */
|
|
84
|
+
export function utcDay(now) {
|
|
85
|
+
return new Date(now).toISOString().slice(0, 10);
|
|
86
|
+
}
|
|
87
|
+
function bindingFor(kind, limit, used, daily) {
|
|
88
|
+
const nextAction = daily
|
|
89
|
+
? "attendre le reset du gate quotidien à minuit UTC, ou relever la limite explicitement"
|
|
90
|
+
: "relever la limite de mission explicitement, ou annuler la mission (aucun reset implicite)";
|
|
91
|
+
return { kind, limit, used, nextAction };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Évalue l'état budget. `dailyUsed` = consommation du jour civil UTC courant ;
|
|
95
|
+
* `missionUsed` = cumul depuis le début de la mission. Un gate quotidien liant
|
|
96
|
+
* se délie seul au passage à minuit UTC (frontière calculée par `utcDay`) ;
|
|
97
|
+
* une limite de mission ne se délie JAMAIS sans action owner explicite.
|
|
98
|
+
*/
|
|
99
|
+
export function evaluateBudget(policy, missionUsed, dailyUsed, _now) {
|
|
100
|
+
// Le reset UTC n'a rien à écrire : à minuit, le jour courant change et la
|
|
101
|
+
// consommation « du jour » (calculée par dailyUsage) repart de zéro.
|
|
102
|
+
const checks = [
|
|
103
|
+
{ kind: "missionCalls", limit: policy.missionCalls, used: missionUsed.calls, daily: false },
|
|
104
|
+
{ kind: "missionTokens", limit: policy.missionTokens, used: missionUsed.tokens, daily: false },
|
|
105
|
+
{ kind: "dailyCalls", limit: policy.dailyCalls, used: dailyUsed.calls, daily: true },
|
|
106
|
+
{ kind: "dailyTokens", limit: policy.dailyTokens, used: dailyUsed.tokens, daily: true },
|
|
107
|
+
];
|
|
108
|
+
for (const check of checks) {
|
|
109
|
+
if (check.limit !== undefined && check.used >= check.limit) {
|
|
110
|
+
return { status: "budget_paused", binding: bindingFor(check.kind, check.limit, check.used, check.daily) };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { status: "within" };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Résolution paresseuse de la consommation journalière : la mission persiste
|
|
117
|
+
* son cumul (`missionUsed`) et le point de base du jour (`dayBaseline` =
|
|
118
|
+
* cumul constaté au début du jour civil UTC courant). Consommation du jour =
|
|
119
|
+
* cumul − base ; au passage à minuit UTC, l'appelant roule la base : reset
|
|
120
|
+
* automatique, sans jamais toucher au cumul de mission.
|
|
121
|
+
*/
|
|
122
|
+
export function rollDailyBaseline(baseline, totals, now) {
|
|
123
|
+
const day = utcDay(now);
|
|
124
|
+
if (baseline.day === day)
|
|
125
|
+
return baseline;
|
|
126
|
+
return { day, calls: totals.calls, tokens: totals.tokens };
|
|
127
|
+
}
|
|
128
|
+
export function dailyUsage(baseline, totals, now) {
|
|
129
|
+
const rolled = rollDailyBaseline(baseline, totals, now);
|
|
130
|
+
return { calls: Math.max(0, totals.calls - rolled.calls), tokens: Math.max(0, totals.tokens - rolled.tokens) };
|
|
131
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Approbations persistées, grants révocables et receipts d'effets (Plan 0002 §5,
|
|
3
|
+
* ADR-008 D6, Skeptic S3, UA1) — vérité Durable (D4) : pending actions, grants
|
|
4
|
+
* et intents/receipts vivent dans le stockage Durable de la conversation.
|
|
5
|
+
*
|
|
6
|
+
* Contrats :
|
|
7
|
+
* - UNE action privilégiée ne peut être approuvée que si le SERVEUR a créé un
|
|
8
|
+
* pending action immuable (operation, target, artifact/argument digests,
|
|
9
|
+
* expiry, allowed uses) ; le client n'invente jamais l'action à approuver ;
|
|
10
|
+
* - le pending action est immuable : seul son état de décision change ;
|
|
11
|
+
* - le grant est vérifiable à la dispatch : digests exacts (artefact/arguments/
|
|
12
|
+
* opération/cible, S3 — pas de ref mutable), expiration, révocation, uses
|
|
13
|
+
* restants, recheck immédiat avant CHAQUE effet protégé ;
|
|
14
|
+
* - consommation du grant et association de l'intent (idempotency key) ATOMIQUES
|
|
15
|
+
* dans un même commit ;
|
|
16
|
+
* - denial/expiry/cancellation sont des événements distincts (UA1) ; une demande
|
|
17
|
+
* identique n'est jamais re-demandée en boucle ;
|
|
18
|
+
* - le receipt enregistre l'intent (clé d'idempotence) + l'issue OBSERVÉE côté
|
|
19
|
+
* distant : on ne déduit jamais le succès du texte du modèle.
|
|
20
|
+
*/
|
|
21
|
+
import { randomUUID } from "node:crypto";
|
|
22
|
+
import { defineDoc } from "@earendil-works/pi-durable";
|
|
23
|
+
import { digest } from "./profile.js";
|
|
24
|
+
export { digest };
|
|
25
|
+
const emptyApprovals = () => ({ pendingActions: [], grants: [], receipts: [] });
|
|
26
|
+
/** Document conversationnel unique : approbations et effets de la mission. */
|
|
27
|
+
export const MissionApprovals = defineDoc({
|
|
28
|
+
kind: "cogitator.mission-approvals",
|
|
29
|
+
version: 1,
|
|
30
|
+
scope: "conversation",
|
|
31
|
+
history: "latest",
|
|
32
|
+
fork: "initial",
|
|
33
|
+
initial: emptyApprovals,
|
|
34
|
+
});
|
|
35
|
+
// ---------- Erreurs de dispatch (motifs vérifiables, jamais génériques) ----------
|
|
36
|
+
export class GrantRejectedError extends Error {
|
|
37
|
+
reason;
|
|
38
|
+
constructor(reason) {
|
|
39
|
+
super(`effet protégé refusé : ${reason}`);
|
|
40
|
+
this.reason = reason;
|
|
41
|
+
this.name = "GrantRejectedError";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Recherche un grant valide pour l'effet EXACT, immédiatement avant la dispatch. */
|
|
45
|
+
export function findValidGrant(grants, effect, now) {
|
|
46
|
+
const candidates = grants.filter((g) => g.operation === effect.operation &&
|
|
47
|
+
g.target === effect.target &&
|
|
48
|
+
g.artifactDigest === effect.artifactDigest &&
|
|
49
|
+
g.argumentDigest === effect.argumentDigest);
|
|
50
|
+
if (candidates.length === 0)
|
|
51
|
+
return { reason: "aucun grant pour cette action exacte (artefact/arguments/cible figés, S3)" };
|
|
52
|
+
const revoked = candidates.find((g) => g.revoked);
|
|
53
|
+
if (revoked && candidates.every((g) => g.revoked))
|
|
54
|
+
return { reason: "grant révoqué : plus aucune dispatch future autorisée" };
|
|
55
|
+
const expired = candidates.find((g) => g.expiresAt <= now);
|
|
56
|
+
if (expired && candidates.every((g) => g.expiresAt <= now || g.revoked)) {
|
|
57
|
+
return { reason: "grant expiré : renouvellement owner requis (l'expiration reste visible, UA1)" };
|
|
58
|
+
}
|
|
59
|
+
const usable = candidates.find((g) => !g.revoked && g.expiresAt > now && g.remainingUses > 0);
|
|
60
|
+
if (!usable)
|
|
61
|
+
return { reason: "grant épuisé (uses restants = 0)" };
|
|
62
|
+
return { grant: usable };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Consommation atomique : décrémente le grant ET associe l'intent (receipt
|
|
66
|
+
* "intent_committed" avec la clé d'idempotence et la tâche) dans la MÊME
|
|
67
|
+
* mutation de document. Une tentative déjà associée à cette clé n'est jamais
|
|
68
|
+
* re-consommée : on renvoie le receipt existant (déduplication/reprise).
|
|
69
|
+
*/
|
|
70
|
+
export function consumeGrantForEffect(doc, effect, now) {
|
|
71
|
+
const prior = doc.receipts.find((r) => r.intentKey === effect.intentKey);
|
|
72
|
+
if (prior)
|
|
73
|
+
return { kind: "duplicate", receipt: prior };
|
|
74
|
+
const found = findValidGrant(doc.grants, effect, now);
|
|
75
|
+
if ("reason" in found)
|
|
76
|
+
return { kind: "rejected", reason: found.reason };
|
|
77
|
+
found.grant.remainingUses -= 1;
|
|
78
|
+
doc.receipts.push({
|
|
79
|
+
...effect,
|
|
80
|
+
grantId: found.grant.id,
|
|
81
|
+
taskId: effect.taskId,
|
|
82
|
+
status: "intent_committed",
|
|
83
|
+
updatedAt: now,
|
|
84
|
+
});
|
|
85
|
+
return { kind: "consumed" };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Crée un pending action côté serveur. Une demande IDENTIQUE (mêmes digests +
|
|
89
|
+
* opération + cible) déjà pending ou déjà déniée n'est pas dupliquée (UA1) :
|
|
90
|
+
* on renvoie l'existant. Champs de scope immuables après création.
|
|
91
|
+
*/
|
|
92
|
+
export function createPendingAction(doc, input, now) {
|
|
93
|
+
const identical = doc.pendingActions.find((p) => p.decision !== "approved" &&
|
|
94
|
+
p.operation === input.operation &&
|
|
95
|
+
p.target === input.target &&
|
|
96
|
+
p.artifactDigest === input.artifactDigest &&
|
|
97
|
+
p.argumentDigest === input.argumentDigest);
|
|
98
|
+
if (identical)
|
|
99
|
+
return identical;
|
|
100
|
+
const action = {
|
|
101
|
+
...input,
|
|
102
|
+
id: randomUUID(),
|
|
103
|
+
createdAt: now,
|
|
104
|
+
decision: "pending",
|
|
105
|
+
decidedAt: 0,
|
|
106
|
+
};
|
|
107
|
+
doc.pendingActions.push(action);
|
|
108
|
+
return action;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Décision owner sur un pending action immuable. Approuver crée le grant
|
|
112
|
+
* (copie des digests figés, expiry, allowed uses) ; dénier est durable et ne
|
|
113
|
+
* re-demandera jamais l'action identique. Les décisions ne se réécrivent pas.
|
|
114
|
+
*/
|
|
115
|
+
export function decidePendingAction(doc, pendingActionId, decision, now, denialReason) {
|
|
116
|
+
const action = doc.pendingActions.find((p) => p.id === pendingActionId);
|
|
117
|
+
if (!action)
|
|
118
|
+
return { kind: "error", reason: "pending action introuvable (le client ne peut pas en inventer un)" };
|
|
119
|
+
if (action.decision !== "pending")
|
|
120
|
+
return { kind: "error", reason: `décision déjà enregistrée (${action.decision}) — les décisions sont durables` };
|
|
121
|
+
if (action.expiresAt <= now)
|
|
122
|
+
return { kind: "error", reason: "pending action expiré : renouveler ou annuler (l'expiration reste visible, UA1)" };
|
|
123
|
+
action.decision = decision;
|
|
124
|
+
action.decidedAt = now;
|
|
125
|
+
if (decision === "denied")
|
|
126
|
+
action.denialReason = denialReason ?? "refus owner";
|
|
127
|
+
if (decision === "approved") {
|
|
128
|
+
const grant = {
|
|
129
|
+
operation: action.operation,
|
|
130
|
+
target: action.target,
|
|
131
|
+
artifactDigest: action.artifactDigest,
|
|
132
|
+
argumentDigest: action.argumentDigest,
|
|
133
|
+
id: randomUUID(),
|
|
134
|
+
pendingActionId: action.id,
|
|
135
|
+
expiresAt: action.expiresAt,
|
|
136
|
+
remainingUses: action.allowedUses,
|
|
137
|
+
revoked: false,
|
|
138
|
+
decidedAt: now,
|
|
139
|
+
};
|
|
140
|
+
doc.grants.push(grant);
|
|
141
|
+
return { kind: "decided", pendingAction: action, grant };
|
|
142
|
+
}
|
|
143
|
+
return { kind: "decided", pendingAction: action };
|
|
144
|
+
}
|
|
145
|
+
/** Révocation : bloque les FUTURES dispatches ; n'annule pas un effet déjà accepté. */
|
|
146
|
+
export function revokeGrant(doc, grantId) {
|
|
147
|
+
const grant = doc.grants.find((g) => g.id === grantId);
|
|
148
|
+
if (!grant)
|
|
149
|
+
return { ok: false, reason: "grant introuvable" };
|
|
150
|
+
grant.revoked = true;
|
|
151
|
+
return { ok: true };
|
|
152
|
+
}
|
|
153
|
+
/** Enregistre l'issue OBSERVÉE d'une tentative déjà associée (jamais inférée). */
|
|
154
|
+
export function recordObservedReceipt(doc, intentKey, observed, now) {
|
|
155
|
+
const receipt = doc.receipts.find((r) => r.intentKey === intentKey);
|
|
156
|
+
if (!receipt)
|
|
157
|
+
return { ok: false, reason: "intent inconnu : la tentative n'a pas été associée à un grant" };
|
|
158
|
+
receipt.status = "observed";
|
|
159
|
+
receipt.observed = { at: now, ...observed };
|
|
160
|
+
receipt.updatedAt = now;
|
|
161
|
+
return { ok: true, receipt };
|
|
162
|
+
}
|
|
163
|
+
/** Marque une tentative dont l'issue externe ne peut être établie (réconciliation requise). */
|
|
164
|
+
export function markReceiptUnknown(doc, intentKey, reason, now) {
|
|
165
|
+
const receipt = doc.receipts.find((r) => r.intentKey === intentKey);
|
|
166
|
+
if (!receipt)
|
|
167
|
+
return;
|
|
168
|
+
receipt.status = "unknown";
|
|
169
|
+
receipt.unknownReason = reason;
|
|
170
|
+
receipt.updatedAt = now;
|
|
171
|
+
}
|