toolroll 0.9.115 → 0.9.116
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 +19 -0
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +12 -12
- package/dist/contracts/console-api.js +1 -1
- package/dist/contracts/engine-api.js +13 -0
- package/dist/flexible-authority-end.js +2 -0
- package/dist/flexible-interactive-schema.js +133 -0
- package/dist/flexible-interactive.js +94 -0
- package/dist/flexible-session.js +26 -2
- package/dist/flexible-sign-in.js +10 -0
- package/dist/flexible-start.js +17 -2
- package/dist/flexible.js +13 -0
- package/dist/lead-tools.js +1 -0
- package/dist/server/console.css +9 -9
- package/dist/server/flows.js +4 -3
- package/dist/spend-report.js +2 -2
- package/dist/spend.js +3 -3
- package/dist/store.js +105 -7
- package/dist/subagent-admin.js +23 -10
- package/dist/subagent-backup-schema.js +36 -0
- package/dist/subagent-backup.js +92 -0
- package/dist/subagent-week.js +2 -2
- package/dist/subagent-work.js +70 -47
- package/dist/subagents-ui.js +6 -2
- package/dist/subagents.js +5 -2
- package/dist/subscription-chat.js +4 -0
- package/dist/terminal-safety.js +114 -0
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/package.json +2 -2
package/dist/store.js
CHANGED
|
@@ -31,6 +31,8 @@ import { V170_ADDED_COLUMNS, V170_STEPS } from "./agent-said-schema.js";
|
|
|
31
31
|
import { V171_SCHEMA, V171_STEPS } from "./flexible-setting-schema.js";
|
|
32
32
|
import { V172_ADDED_COLUMNS, V172_OBJECTS, V172_SCHEMA, V172_STEPS } from "./flexible-sign-in-schema.js";
|
|
33
33
|
import { V173_ADDED_COLUMNS, V173_STEPS } from "./plan-problems-schema.js";
|
|
34
|
+
import { V175_OBJECTS, V175_SCHEMA, V175_STEPS } from "./flexible-interactive-schema.js";
|
|
35
|
+
import { V176_ADDED_COLUMNS, V176_STEPS, V176_SCHEMA, V176_OBJECTS } from "./subagent-backup-schema.js";
|
|
34
36
|
import { V174_OBJECTS, V174_SCHEMA, V174_STEPS } from "./flexible-everyday-schema.js";
|
|
35
37
|
import { endThreadAuthorityFor } from "./flexible-authority-end.js";
|
|
36
38
|
import { relayCancel } from "./flexible-relay-cancel.js";
|
|
@@ -838,7 +840,7 @@ export function checkSuitesOf(value) {
|
|
|
838
840
|
}
|
|
839
841
|
}
|
|
840
842
|
const REGISTERED_AT_FILING = "again, as it was filed";
|
|
841
|
-
export const SCHEMA_VERSION =
|
|
843
|
+
export const SCHEMA_VERSION = 176;
|
|
842
844
|
export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
|
|
843
845
|
const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
|
|
844
846
|
const V118_COORDINATOR_COLUMNS = [["task_ref", "coordinator_cid"], ["coordinator_event", "cid"], ["mcp_idempotency", "cid"], ["coordinator_proposal", "cid"]];
|
|
@@ -903,7 +905,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
|
|
|
903
905
|
"fallback_config", "fallback_cycle", "fallback_transition",
|
|
904
906
|
]);
|
|
905
907
|
const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
|
|
906
|
-
export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174]);
|
|
908
|
+
export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176]);
|
|
907
909
|
export const V119_ADDED_COLUMNS = Object.freeze({
|
|
908
910
|
task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
|
|
909
911
|
run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
|
|
@@ -1446,7 +1448,7 @@ export { V156_STEPS };
|
|
|
1446
1448
|
export { V157_STEPS };
|
|
1447
1449
|
export { V158_STEPS };
|
|
1448
1450
|
export { V159_STEPS };
|
|
1449
|
-
export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS };
|
|
1451
|
+
export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS };
|
|
1450
1452
|
export const RELEASE_ONCE_SCHEMA = `
|
|
1451
1453
|
CREATE TABLE IF NOT EXISTS release_authority (
|
|
1452
1454
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -1799,7 +1801,7 @@ function readSubagentGrant(row) {
|
|
|
1799
1801
|
}
|
|
1800
1802
|
function readSubagentRow(row) {
|
|
1801
1803
|
return { id: Number(row["id"]), repo: String(row["repo"]), handle: String(row["handle"]), state: String(row["state"]), version: Number(row["version"]), soul: String(row["soul"]),
|
|
1802
|
-
model: row["model"] === null ? null : String(row["model"]), dailyTurns: Number(row["daily_turns"]), manager: String(row["manager"]), createdBy: String(row["created_by"]), createdAt: String(row["created_at"]),
|
|
1804
|
+
model: row["model"] === null ? null : String(row["model"]), codexBackupModel: typeof row["codex_backup_model"] === "string" ? row["codex_backup_model"] : null, authorityGeneration: Number(row["authority_generation"] ?? 0), dailyTurns: Number(row["daily_turns"]), manager: String(row["manager"]), createdBy: String(row["created_by"]), createdAt: String(row["created_at"]),
|
|
1803
1805
|
updatedBy: String(row["updated_by"]), updatedAt: String(row["updated_at"]), summaryAt: row["summary_at"] === null ? null : String(row["summary_at"]),
|
|
1804
1806
|
deskFlow: row["desk_flow"] === null || row["desk_flow"] === undefined ? null : Number(row["desk_flow"]),
|
|
1805
1807
|
weeklyAt: row["weekly_at"] === null || row["weekly_at"] === undefined ? null : String(row["weekly_at"]) };
|
|
@@ -4224,7 +4226,7 @@ function initializeStore(db, file, options = {}) {
|
|
|
4224
4226
|
throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
|
|
4225
4227
|
}
|
|
4226
4228
|
if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
|
|
4227
|
-
const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db);
|
|
4229
|
+
const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db);
|
|
4228
4230
|
if (missing !== null)
|
|
4229
4231
|
throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
|
|
4230
4232
|
db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
|
|
@@ -4642,6 +4644,20 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
|
|
|
4642
4644
|
if (everydayDamaged !== null)
|
|
4643
4645
|
throw new Error(`${file}: refusing to open — ${everydayDamaged}`);
|
|
4644
4646
|
step("flexible-everyday");
|
|
4647
|
+
db.exec(V175_SCHEMA);
|
|
4648
|
+
db.prepare("INSERT INTO flexible_thread_runtime (thread, runtime, chosen) SELECT id, 'stream-json', 1 FROM flexible_thread WHERE id NOT IN (SELECT thread FROM flexible_thread_runtime)").run();
|
|
4649
|
+
const interactiveDamaged = flexibleInteractiveShapeProblem(db);
|
|
4650
|
+
if (interactiveDamaged !== null)
|
|
4651
|
+
throw new Error(`${file}: refusing to open — ${interactiveDamaged}`);
|
|
4652
|
+
step("flexible-interactive");
|
|
4653
|
+
for (const [table, columns] of Object.entries(V176_ADDED_COLUMNS))
|
|
4654
|
+
for (const [column, { definition }] of Object.entries(columns))
|
|
4655
|
+
addColumn(db, table, column, definition);
|
|
4656
|
+
db.exec(V176_SCHEMA);
|
|
4657
|
+
const backupDamaged = subagentBackupShapeProblem(db);
|
|
4658
|
+
if (backupDamaged !== null)
|
|
4659
|
+
throw new Error(`${file}: refusing to open — ${backupDamaged}`);
|
|
4660
|
+
step("subagent-backup-columns");
|
|
4645
4661
|
if (!fresh)
|
|
4646
4662
|
reclaimDatabase(db, "migration");
|
|
4647
4663
|
const expectedMarker = preflight < 0 ? preflight : -preflight;
|
|
@@ -13599,8 +13615,12 @@ export class Store {
|
|
|
13599
13615
|
}));
|
|
13600
13616
|
}
|
|
13601
13617
|
subagentTurnsSince(subagent, since) {
|
|
13602
|
-
|
|
13618
|
+
const legacy = Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_event WHERE subagent = ? AND at >= ? AND kind IN ('decided','handled','handed','asked','failed')").get(subagent, since)?.["n"] ?? 0)
|
|
13603
13619
|
+ Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_call WHERE subagent = ? AND created_at >= ?").get(subagent, since)?.["n"] ?? 0);
|
|
13620
|
+
const hasAttempts = this.db.prepare("SELECT 1 FROM subagent_turn WHERE subagent = ? AND at >= ? AND counted_attempt = 1 LIMIT 1").get(subagent, since) !== undefined;
|
|
13621
|
+
if (this.getSubagent(subagent)?.codexBackupModel === null && !hasAttempts)
|
|
13622
|
+
return legacy;
|
|
13623
|
+
return Math.max(legacy, Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_turn WHERE subagent = ? AND at >= ?").get(subagent, since)?.["n"] ?? 0));
|
|
13604
13624
|
}
|
|
13605
13625
|
openSubagentQuestion(question, now) {
|
|
13606
13626
|
const { changes, lastInsertRowid } = this.db.prepare("INSERT OR IGNORE INTO subagent_question (subagent, card, entry, question, options_json, asked_of, state, created_at, tool_call, suggestion) VALUES (?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)")
|
|
@@ -13748,7 +13768,7 @@ export class Store {
|
|
|
13748
13768
|
}
|
|
13749
13769
|
subagentTurns(subagent, since) {
|
|
13750
13770
|
return this.db.prepare("SELECT * FROM subagent_turn WHERE subagent = ? AND at >= ? ORDER BY id").all(subagent, since).map(row => ({
|
|
13751
|
-
id: Number(row["id"]), subagent: Number(row["subagent"]), card: row["card"] === null ? null : Number(row["card"]), model: String(row["model"]), ok: Number(row["ok"]) === 1, ms: Number(row["ms"]),
|
|
13771
|
+
id: Number(row["id"]), subagent: Number(row["subagent"]), card: row["card"] === null ? null : Number(row["card"]), model: String(row["model"]), provider: row["provider"] === "codex" ? "codex" : "claude", pending: Number(row["pending"]) === 1, modelReported: typeof row["model_reported"] === "string" ? row["model_reported"] : null, ok: Number(row["ok"]) === 1, ms: Number(row["ms"]),
|
|
13752
13772
|
costUsd: row["cost_usd"] === null ? null : Number(row["cost_usd"]), tokensIn: row["tokens_in"] === null ? null : Number(row["tokens_in"]), tokensOut: row["tokens_out"] === null ? null : Number(row["tokens_out"]), at: String(row["at"])
|
|
13753
13773
|
}));
|
|
13754
13774
|
}
|
|
@@ -16561,6 +16581,53 @@ export class Store {
|
|
|
16561
16581
|
flowFencePolicy(flow) {
|
|
16562
16582
|
return this.db.prepare("SELECT fence_policy FROM flow WHERE id = ?").get(flow)?.["fence_policy"] === 2 ? 2 : 1;
|
|
16563
16583
|
}
|
|
16584
|
+
setSubagentCodexBackup(id, model, by, now) {
|
|
16585
|
+
this.db.prepare("UPDATE subagent SET codex_backup_model = ?, updated_by = ?, updated_at = ? WHERE id = ?").run(model, by, now.toISOString(), id);
|
|
16586
|
+
this.addSubagentEvent({ subagent: id, kind: "note", said: model === null ? "Codex backup turned off." : `Codex backup enabled (${model}); every provider attempt counts toward the daily limit.`, by }, now);
|
|
16587
|
+
}
|
|
16588
|
+
reserveSubagentAttempt(input, now) {
|
|
16589
|
+
return this.transact(() => {
|
|
16590
|
+
const mate = this.getSubagent(input.subagent);
|
|
16591
|
+
if (mate === null || mate.state !== "active" || mate.codexBackupModel === null || mate.authorityGeneration !== input.authorityGeneration)
|
|
16592
|
+
return { ok: false, why: "The subagent or its backup is no longer enabled." };
|
|
16593
|
+
const card = this.getFlowCard(input.card);
|
|
16594
|
+
if (card === null || card.state !== "active" || card.entry !== input.cardEntry || card.stage !== input.stage || this.getFlow(card.flow)?.repo !== mate.repo || this.getFlow(card.flow)?.revision !== input.flowRevision || this.getFlow(card.flow)?.state !== "active")
|
|
16595
|
+
return { ok: false, why: "The card no longer belongs to this project." };
|
|
16596
|
+
if (this.db.prepare("SELECT 1 FROM subagent_turn WHERE subagent = ? AND card = ? AND card_entry = ? AND pending = 1").get(mate.id, input.card, input.cardEntry) !== undefined)
|
|
16597
|
+
return { ok: false, why: "An earlier attempt on this card is unfinished; inspect it before trying again." };
|
|
16598
|
+
if (input.provider === "claude") {
|
|
16599
|
+
const model = mate.model ?? (this.getChatConfig()?.provider === "claude-subscription" ? this.getChatConfig().model : "default");
|
|
16600
|
+
if (input.model !== model)
|
|
16601
|
+
return { ok: false, why: "The primary model changed." };
|
|
16602
|
+
}
|
|
16603
|
+
if (input.provider === "codex") {
|
|
16604
|
+
const parent = this.db.prepare("SELECT * FROM subagent_turn WHERE id = ? AND subagent = ? AND card = ? AND provider = 'claude' AND ok = 0 AND pending = 0 AND failure_kind IN ('usage-limit','unavailable') AND authority_generation = ? AND card_entry = ?").get(input.backupOf ?? -1, mate.id, input.card, mate.authorityGeneration, input.cardEntry);
|
|
16605
|
+
if (parent === undefined || mate.codexBackupModel !== input.model || input.billing !== "subscription")
|
|
16606
|
+
return { ok: false, why: "The approved backup or its primary attempt changed." };
|
|
16607
|
+
if (this.db.prepare("SELECT 1 FROM subagent_turn WHERE backup_of = ?").get(input.backupOf) !== undefined)
|
|
16608
|
+
return { ok: false, why: "This primary attempt already used its backup." };
|
|
16609
|
+
}
|
|
16610
|
+
const policy = this.agentPolicyRefusal(input.provider, input.model);
|
|
16611
|
+
if (policy !== null)
|
|
16612
|
+
return { ok: false, why: policy };
|
|
16613
|
+
const day = new Date(now);
|
|
16614
|
+
day.setHours(0, 0, 0, 0);
|
|
16615
|
+
if (this.subagentTurnsSince(mate.id, day.toISOString()) >= mate.dailyTurns)
|
|
16616
|
+
return { ok: false, why: "The daily turn limit is reached." };
|
|
16617
|
+
const budget = this.budgetGate(now)({ project: mate.repo, person: null, subagent: mate.id, agents: [{ provider: input.provider, billing: input.billing }] });
|
|
16618
|
+
if (budget.over !== null)
|
|
16619
|
+
return { ok: false, why: "A budget holds this provider attempt." };
|
|
16620
|
+
const row = this.db.prepare("INSERT INTO subagent_turn (subagent, card, card_entry, model, provider, billing, backup_of, pending, counted_attempt, authority_generation, ok, ms, at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 0, 0, ?)")
|
|
16621
|
+
.run(mate.id, input.card, input.cardEntry, input.model, input.provider, input.billing, input.backupOf ?? null, mate.authorityGeneration, now.toISOString());
|
|
16622
|
+
this.spendCache = null;
|
|
16623
|
+
return { ok: true, id: Number(row.lastInsertRowid) };
|
|
16624
|
+
});
|
|
16625
|
+
}
|
|
16626
|
+
settleSubagentAttempt(id, result) {
|
|
16627
|
+
this.db.prepare("UPDATE subagent_turn SET pending = 0, ok = ?, ms = ?, model_reported = ?, failure_kind = ?, cost_usd = ?, tokens_in = ?, tokens_out = ? WHERE id = ? AND pending = 1")
|
|
16628
|
+
.run(result.ok ? 1 : 0, Math.round(result.ms), result.modelReported ?? null, result.failureKind ?? null, result.costUsd ?? null, result.tokensIn ?? null, result.tokensOut ?? null, id);
|
|
16629
|
+
this.spendCache = null;
|
|
16630
|
+
}
|
|
16564
16631
|
}
|
|
16565
16632
|
function wholeNumber(value) {
|
|
16566
16633
|
if (value === null || value === undefined)
|
|
@@ -19124,3 +19191,34 @@ function flexibleEverydayShapeProblem(db) {
|
|
|
19124
19191
|
}
|
|
19125
19192
|
return null;
|
|
19126
19193
|
}
|
|
19194
|
+
function flexibleInteractiveShapeProblem(db) {
|
|
19195
|
+
const statements = V175_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
|
|
19196
|
+
for (const [type, name] of V175_OBJECTS) {
|
|
19197
|
+
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
|
|
19198
|
+
if (row === undefined)
|
|
19199
|
+
return `the interactive agent threads ${type} ${name} is missing`;
|
|
19200
|
+
const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
|
|
19201
|
+
if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want.replace(/;$/, "")).trim())
|
|
19202
|
+
return `the interactive agent threads ${type} ${name} has an unknown shape`;
|
|
19203
|
+
}
|
|
19204
|
+
return null;
|
|
19205
|
+
}
|
|
19206
|
+
function subagentBackupShapeProblem(db) {
|
|
19207
|
+
for (const [table, columns] of Object.entries(V176_ADDED_COLUMNS)) {
|
|
19208
|
+
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
|
|
19209
|
+
for (const [column, { definition }] of Object.entries(columns)) {
|
|
19210
|
+
if (!hasColumn(db, table, column))
|
|
19211
|
+
return `the subagent backup column ${table}.${column} is missing`;
|
|
19212
|
+
if (row === undefined || !canonicalDdl(String(row["sql"])).includes(canonicalDdl(`, ${column} ${definition}`).trim()))
|
|
19213
|
+
return `the subagent backup column ${table}.${column} has an unknown shape`;
|
|
19214
|
+
}
|
|
19215
|
+
}
|
|
19216
|
+
const statements = V176_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(Boolean);
|
|
19217
|
+
for (const [type, name] of V176_OBJECTS) {
|
|
19218
|
+
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
|
|
19219
|
+
const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
|
|
19220
|
+
if (row === undefined || want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")) !== canonicalDdl(want))
|
|
19221
|
+
return `the subagent backup ${type} ${name} has an unknown shape`;
|
|
19222
|
+
}
|
|
19223
|
+
return null;
|
|
19224
|
+
}
|
package/dist/subagent-admin.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validModelId } from "./provider.js";
|
|
1
2
|
import { flowDefinitionOf } from "./flow-engine.js";
|
|
2
3
|
import { handleOf, parseSoul, SUBAGENT_TEMPLATES, subagentLabel } from "./subagents.js";
|
|
3
4
|
export const SUBAGENT_MODELS = ["default", "sonnet", "opus", "haiku"];
|
|
@@ -46,16 +47,28 @@ export function setSubagentState(store, mate, state, by, now) {
|
|
|
46
47
|
store.addSubagentEvent({ subagent: mate.id, kind: state === "paused" ? "paused" : "resumed", said: state === "paused" ? `${by} paused ${name}.` : `${by} set ${name} working again.`, by }, now);
|
|
47
48
|
return { ok: true, said: state === "paused" ? `${name} is paused. Its decisions go to people until you resume it.` : `${name} is working again.` };
|
|
48
49
|
}
|
|
49
|
-
export function subagentSettings(store, mate, change, by, now) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
50
|
+
export function subagentSettings(store, mate, change, by, now, options = {}) {
|
|
51
|
+
return store.transact(() => {
|
|
52
|
+
const current = store.getSubagent(mate.id);
|
|
53
|
+
if (current === null || current.state === "removed")
|
|
54
|
+
return { ok: false, said: "This teammate is no longer on the team." };
|
|
55
|
+
const model = change.model === undefined ? undefined : change.model === "default" ? null : SUBAGENT_MODELS.includes(change.model) ? change.model : undefined;
|
|
56
|
+
if (change.model !== undefined && model === undefined)
|
|
57
|
+
return { ok: false, said: "Choose one of the models listed." };
|
|
58
|
+
if (change.dailyTurns !== undefined && (!Number.isInteger(change.dailyTurns) || change.dailyTurns < 1 || change.dailyTurns > 2000))
|
|
59
|
+
return { ok: false, said: "A daily limit is 1 to 2,000 turns." };
|
|
60
|
+
if (change.manager !== undefined && !store.accountCanAccess(change.manager, current.repo))
|
|
61
|
+
return { ok: false, said: "Its manager must be someone on this project." };
|
|
62
|
+
const backup = change.codexBackupModel;
|
|
63
|
+
if (backup !== undefined && backup !== null && (!validModelId(backup) || ["default", "inherit", ""].includes(backup)))
|
|
64
|
+
return { ok: false, said: "Enter an exact Codex backup model ID, or leave it blank to turn the backup off." };
|
|
65
|
+
if (backup != null && backup !== current.codexBackupModel && (!store.accountCanAccess(by, current.repo) || options.proveBackup?.() !== true))
|
|
66
|
+
return { ok: false, said: "Enter your Toolroll password to enable or change the Codex backup. Nothing changed." };
|
|
67
|
+
store.updateSubagent(current.id, { ...(model === undefined ? {} : { model }), ...(change.dailyTurns === undefined ? {} : { dailyTurns: change.dailyTurns }), ...(change.manager === undefined ? {} : { manager: change.manager }) }, by, now);
|
|
68
|
+
if (backup !== undefined && backup !== current.codexBackupModel)
|
|
69
|
+
store.setSubagentCodexBackup(current.id, backup, by, now);
|
|
70
|
+
return { ok: true, said: "Saved." };
|
|
71
|
+
});
|
|
59
72
|
}
|
|
60
73
|
export const nameOf = (mate) => { const read = parseSoul(mate.soul); return read.ok ? read.soul.name : mate.handle; };
|
|
61
74
|
export const labelOf = (mate) => { const read = parseSoul(mate.soul); return read.ok ? subagentLabel(read.soul) : mate.handle; };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export const V176_ADDED_COLUMNS = Object.freeze({
|
|
2
|
+
subagent: { authority_generation: { definition: "INTEGER NOT NULL DEFAULT 0 CHECK (authority_generation >= 0)", saved: "0" }, codex_backup_model: { definition: "TEXT", saved: "NULL" } },
|
|
3
|
+
subagent_turn: {
|
|
4
|
+
provider: { definition: "TEXT NOT NULL DEFAULT 'claude' CHECK (provider IN ('claude','codex'))", saved: "'claude'" },
|
|
5
|
+
card_entry: { definition: "INTEGER", saved: "NULL" },
|
|
6
|
+
model_reported: { definition: "TEXT", saved: "NULL" },
|
|
7
|
+
backup_of: { definition: "INTEGER REFERENCES subagent_turn(id)", saved: "NULL" },
|
|
8
|
+
authority_generation: { definition: "INTEGER NOT NULL DEFAULT 0 CHECK (authority_generation >= 0)", saved: "0" },
|
|
9
|
+
counted_attempt: { definition: "INTEGER NOT NULL DEFAULT 0 CHECK (counted_attempt IN (0,1))", saved: "0" },
|
|
10
|
+
failure_kind: { definition: "TEXT CHECK (failure_kind IN ('usage-limit','unavailable'))", saved: "NULL" },
|
|
11
|
+
pending: { definition: "INTEGER NOT NULL DEFAULT 0 CHECK (pending IN (0,1))", saved: "0" },
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
export const V176_STEPS = Object.freeze(["subagent-backup-columns"]);
|
|
15
|
+
export const V176_SCHEMA = `
|
|
16
|
+
CREATE UNIQUE INDEX IF NOT EXISTS subagent_backup_once ON subagent_turn(backup_of) WHERE backup_of IS NOT NULL;
|
|
17
|
+
CREATE TRIGGER IF NOT EXISTS subagent_authority_changed AFTER UPDATE OF state, soul, model, codex_backup_model, daily_turns, manager ON subagent
|
|
18
|
+
WHEN NEW.state IS NOT OLD.state OR NEW.soul IS NOT OLD.soul OR NEW.model IS NOT OLD.model
|
|
19
|
+
OR NEW.codex_backup_model IS NOT OLD.codex_backup_model OR NEW.daily_turns IS NOT OLD.daily_turns OR NEW.manager IS NOT OLD.manager
|
|
20
|
+
BEGIN
|
|
21
|
+
UPDATE subagent SET authority_generation = OLD.authority_generation + 1 WHERE id = NEW.id;
|
|
22
|
+
END;
|
|
23
|
+
CREATE TRIGGER IF NOT EXISTS subagent_policy_changed AFTER UPDATE ON org_policy
|
|
24
|
+
BEGIN
|
|
25
|
+
UPDATE subagent SET authority_generation = authority_generation + 1;
|
|
26
|
+
END;
|
|
27
|
+
CREATE TRIGGER IF NOT EXISTS subagent_policy_inserted AFTER INSERT ON org_policy
|
|
28
|
+
BEGIN
|
|
29
|
+
UPDATE subagent SET authority_generation = authority_generation + 1;
|
|
30
|
+
END;
|
|
31
|
+
CREATE TRIGGER IF NOT EXISTS subagent_policy_removed AFTER DELETE ON org_policy
|
|
32
|
+
BEGIN
|
|
33
|
+
UPDATE subagent SET authority_generation = authority_generation + 1;
|
|
34
|
+
END;
|
|
35
|
+
`;
|
|
36
|
+
export const V176_OBJECTS = Object.freeze([...V176_SCHEMA.matchAll(/CREATE (UNIQUE INDEX|TRIGGER) IF NOT EXISTS (\w+)/g)].map(one => [one[1] === "UNIQUE INDEX" ? "index" : "trigger", one[2]]));
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { claudeTurnRunner } from "./subagents.js";
|
|
3
|
+
import { TURN_MODEL_SCHEMA } from "./contracts/subagent-turn.js";
|
|
4
|
+
import { strictJsonParse } from "./converse.js";
|
|
5
|
+
import { performSubscriptionLeadRequest } from "./subscription-chat.js";
|
|
6
|
+
import { run } from "./exec.js";
|
|
7
|
+
import { ALL_CREDENTIAL_ENV } from "./provider.js";
|
|
8
|
+
import { claudeMachineBilling } from "./spend.js";
|
|
9
|
+
import { inEvalWorld } from "./eval-gate.js";
|
|
10
|
+
export async function subagentAttemptWithBackup(store, mate, card, request, runner = run, clock = () => new Date(), elapsedNow = () => performance.now()) {
|
|
11
|
+
const started = elapsedNow();
|
|
12
|
+
const remaining = () => Math.max(0, Math.min(request.timeoutMs, request.timeoutMs - (elapsedNow() - started)));
|
|
13
|
+
const failure = (said, provider = "claude", model = request.model) => ({ reply: { ok: false, said }, provider, model, backup: provider === "codex", authorize: () => said });
|
|
14
|
+
if (inEvalWorld())
|
|
15
|
+
return failure("Subagents don't run in an eval world.");
|
|
16
|
+
if (remaining() <= 0)
|
|
17
|
+
return failure("The original turn deadline elapsed.");
|
|
18
|
+
const originalFlow = store.getFlow(card.flow);
|
|
19
|
+
const flowRevision = request.flowRevision ?? originalFlow?.revision;
|
|
20
|
+
if (flowRevision === undefined)
|
|
21
|
+
return failure("The flow is no longer available.");
|
|
22
|
+
const freshnessProblem = (provider, model) => {
|
|
23
|
+
if (remaining() <= 0)
|
|
24
|
+
return "The original turn deadline elapsed before the answer could be used.";
|
|
25
|
+
const liveMate = store.getSubagent(mate.id), liveCard = store.getFlowCard(card.id), liveFlow = store.getFlow(card.flow);
|
|
26
|
+
if (liveMate?.state !== "active" || liveMate.authorityGeneration !== mate.authorityGeneration || liveCard?.state !== "active" || liveCard.entry !== card.entry || liveCard.stage !== card.stage || liveFlow?.revision !== flowRevision || liveFlow?.state !== "active")
|
|
27
|
+
return "The attempt's permission or card changed before its answer could be used.";
|
|
28
|
+
if (provider === "codex" && liveMate.codexBackupModel !== model)
|
|
29
|
+
return "The Codex backup's permission changed before its answer could be used.";
|
|
30
|
+
return store.agentPolicyRefusal(provider, model);
|
|
31
|
+
};
|
|
32
|
+
const primary = store.reserveSubagentAttempt({ subagent: mate.id, card: card.id, cardEntry: card.entry, stage: card.stage, authorityGeneration: mate.authorityGeneration, flowRevision, provider: "claude", model: request.model, billing: claudeMachineBilling(store.handle) }, clock());
|
|
33
|
+
if (!primary.ok)
|
|
34
|
+
return failure(primary.why);
|
|
35
|
+
let first;
|
|
36
|
+
try {
|
|
37
|
+
first = await claudeTurnRunner(runner)({ ...request, timeoutMs: remaining() });
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
first = { ok: false, said: "Claude's attempt stopped without a decision." };
|
|
41
|
+
}
|
|
42
|
+
const primaryProblem = freshnessProblem("claude", request.model);
|
|
43
|
+
if (first.ok && primaryProblem !== null)
|
|
44
|
+
first = { ...first, ok: false, said: primaryProblem };
|
|
45
|
+
store.settleSubagentAttempt(primary.id, { ...first, ms: elapsedNow() - started, ...(!first.ok && first.backupReason !== undefined ? { failureKind: first.backupReason } : {}) });
|
|
46
|
+
if (!first.ok && primaryProblem !== null)
|
|
47
|
+
return failure(primaryProblem);
|
|
48
|
+
if (first.ok || first.backupReason === undefined || remaining() <= 0)
|
|
49
|
+
return { reply: first, provider: "claude", model: request.model, backup: false, authorize: () => freshnessProblem("claude", request.model) };
|
|
50
|
+
let signedIn = false;
|
|
51
|
+
try {
|
|
52
|
+
const status = await runner("codex", ["login", "status"], { timeoutMs: Math.min(15_000, remaining()), maxBuffer: 65_536, omitEnv: ALL_CREDENTIAL_ENV, processGroup: true });
|
|
53
|
+
const said = `${status.stdout}\n${status.stderr}`;
|
|
54
|
+
signedIn = status.code === 0 && !status.timedOut && !status.notFound && /^Logged in using ChatGPT\s*$/m.test(said) && !/api key|bedrock/i.test(said);
|
|
55
|
+
}
|
|
56
|
+
catch { }
|
|
57
|
+
if (!signedIn || remaining() <= 0)
|
|
58
|
+
return failure(`${first.said} Codex backup needs a current ChatGPT sign-in.`);
|
|
59
|
+
const current = store.getSubagent(mate.id);
|
|
60
|
+
const model = current?.codexBackupModel;
|
|
61
|
+
if (model === null || model === undefined)
|
|
62
|
+
return failure(`${first.said} Codex backup is no longer enabled.`);
|
|
63
|
+
const backup = store.reserveSubagentAttempt({ subagent: mate.id, card: card.id, cardEntry: card.entry, stage: card.stage, authorityGeneration: mate.authorityGeneration, flowRevision, provider: "codex", model, billing: "subscription", backupOf: primary.id }, clock());
|
|
64
|
+
if (!backup.ok)
|
|
65
|
+
return failure(`${first.said} ${backup.why}`);
|
|
66
|
+
const began = elapsedNow();
|
|
67
|
+
let reply;
|
|
68
|
+
let modelReported = null;
|
|
69
|
+
try {
|
|
70
|
+
if (remaining() <= 0)
|
|
71
|
+
throw new Error("The original turn deadline elapsed.");
|
|
72
|
+
const answered = await performSubscriptionLeadRequest({ provider: "codex-subscription", model, system: "You decide one flow-card turn. Return exactly the supplied subagent decision schema. You have no native tools, repository or MCP access. The host validates any requested project-tool action separately.", dataDocument: request.prompt, history: [], tools: [], outputSchema: TURN_MODEL_SCHEMA, timeoutMs: remaining() }, runner);
|
|
73
|
+
if (!answered.ok)
|
|
74
|
+
reply = { ok: false, said: `Codex backup couldn't decide (${answered.problem}).` };
|
|
75
|
+
else {
|
|
76
|
+
modelReported = answered.answer.modelReported ?? null;
|
|
77
|
+
const parsed = strictJsonParse(Buffer.from(answered.answer.text, "utf8"), 65_536, 12);
|
|
78
|
+
const usage = { tokensIn: answered.answer.tokensIn, tokensOut: answered.answer.tokensOut,
|
|
79
|
+
...(answered.answer.reportedCostUsd == null ? {} : { costUsd: answered.answer.reportedCostUsd }) };
|
|
80
|
+
reply = parsed.ok ? { ok: true, value: parsed.value, ms: elapsedNow() - began, ...usage }
|
|
81
|
+
: { ok: false, said: "Codex backup's answer wasn't a decision.", ...usage };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
reply = { ok: false, said: "Codex backup stopped without a decision." };
|
|
86
|
+
}
|
|
87
|
+
const backupProblem = freshnessProblem("codex", model);
|
|
88
|
+
if (backupProblem !== null)
|
|
89
|
+
reply = { ...reply, ok: false, said: backupProblem };
|
|
90
|
+
store.settleSubagentAttempt(backup.id, { ...reply, ms: elapsedNow() - began, modelReported });
|
|
91
|
+
return { reply, provider: "codex", model: modelReported ?? model, backup: true, authorize: () => freshnessProblem("codex", model) };
|
|
92
|
+
}
|
package/dist/subagent-week.js
CHANGED
|
@@ -24,7 +24,7 @@ export function weekOf(store, mate, now, since = new Date(now.getTime() - WEEK_M
|
|
|
24
24
|
});
|
|
25
25
|
const moved = store.flowMovesOverridden(`${name} (AI)`, since).map(one => ({ said: `${one.by} moved “${one.title.slice(0, 80)}” after ${name} did`, at: one.at, href: flowCardHref(one.flow, one.card) }));
|
|
26
26
|
return {
|
|
27
|
-
since, turns: turns.length, failedTurns: turns.filter(one => !one.ok).length, costUsd: costs.length === 0 ? null : Math.round(costs.reduce((sum, one) => sum + one, 0) * 1e6) / 1e6,
|
|
27
|
+
since, turns: turns.length, pendingTurns: turns.filter(one => one.pending).length, failedTurns: turns.filter(one => !one.ok && !one.pending).length, costUsd: costs.length !== turns.length || costs.length === 0 ? null : Math.round(costs.reduce((sum, one) => sum + one, 0) * 1e6) / 1e6,
|
|
28
28
|
minutes: Math.round(turns.reduce((sum, one) => sum + one.ms, 0) / 60_000),
|
|
29
29
|
decided: count("decided"), handled: count("handled"), handed: count("handed"), asked: count("asked"),
|
|
30
30
|
calls: { made: calls.filter(one => one.state === "done" || one.state === "failed").length, approved: calls.filter(one => one.decidedBy !== null && one.state !== "denied" && one.state !== "refused").length,
|
|
@@ -41,7 +41,7 @@ export function weekWords(mate, week) {
|
|
|
41
41
|
const lines = [
|
|
42
42
|
`${name} decided ${week.decided}, handled ${week.handled}, handed ${week.handed} to people and asked ${week.asked} question${week.asked === 1 ? "" : "s"}.`,
|
|
43
43
|
`Tool calls: ${week.calls.made} made${week.calls.approved > 0 ? ` (${week.calls.approved} after a person approved)` : ""}${week.calls.denied > 0 ? `, ${week.calls.denied} turned down` : ""}${week.calls.refused > 0 ? `, ${week.calls.refused} outside its rules` : ""}${week.calls.undone > 0 ? `, ${week.calls.undone} undone` : ""}.`,
|
|
44
|
-
`${week.turns} turn${week.turns === 1 ? "" : "s"}${week.failedTurns > 0 ? ` (${week.failedTurns} failed)` : ""}, about ${week.minutes} minute${week.minutes === 1 ? "" : "s"} of thinking${week.costUsd === null ? "" : `, ${money(week.costUsd)} at API prices`}.`,
|
|
44
|
+
`${week.turns} turn${week.turns === 1 ? "" : "s"}${week.pendingTurns > 0 ? ` (${week.pendingTurns} unfinished)` : ""}${week.failedTurns > 0 ? ` (${week.failedTurns} failed)` : ""}, about ${week.minutes} minute${week.minutes === 1 ? "" : "s"} of thinking${week.costUsd === null ? "" : `, ${money(week.costUsd)} at API prices`}.`,
|
|
45
45
|
...(week.overrides.length === 0 ? ["Nobody overrode it."] : [`You overrode it ${week.overrides.length} time${week.overrides.length === 1 ? "" : "s"}:`, ...week.overrides.slice(0, 5).map(one => `• ${one.said}`)]),
|
|
46
46
|
];
|
|
47
47
|
return lines.join("\n");
|
package/dist/subagent-work.js
CHANGED
|
@@ -7,6 +7,7 @@ import { LIMITS } from "./decision.js";
|
|
|
7
7
|
import { callName, callOutcome, callWords, inputProblem, makeCall, offeredTools, refreshGrants, ruleFor } from "./subagent-tools.js";
|
|
8
8
|
import { ACCEPT, answerSuggestion, considerSuggestion, memoriesFor, remember } from "./subagent-memory.js";
|
|
9
9
|
import { replyToAsker } from "./subagent-desk.js";
|
|
10
|
+
import { subagentAttemptWithBackup } from "./subagent-backup.js";
|
|
10
11
|
import { claudeMachineBilling } from "./spend.js";
|
|
11
12
|
export const ASKED = "9999-12-31T00:00:00.000Z";
|
|
12
13
|
const CARRY_ON = "Carry on";
|
|
@@ -87,15 +88,18 @@ export async function subagentTurn(store, flow, definition, stage, card, mate, n
|
|
|
87
88
|
const tools = spent ? [] : offeredTools(store, mate);
|
|
88
89
|
const context = { ...contextOf(store, flow, definition, stage, card, mate, tools, spent && made > 0), ...(shorten === undefined ? {} : { shorten }) };
|
|
89
90
|
const asked = Date.now();
|
|
90
|
-
const
|
|
91
|
-
|
|
91
|
+
const attempt = io.turn === undefined && store.getSubagent(mate.id)?.codexBackupModel != null
|
|
92
|
+
? await subagentAttemptWithBackup(store, mate, card, { model, prompt: turnPrompt(context), timeoutMs: TURN_TIMEOUT_MS, flowRevision: flow.revision }) : null;
|
|
93
|
+
const reply = attempt?.reply ?? await (io.turn ?? claudeTurnRunner())({ model, prompt: turnPrompt(context), timeoutMs: TURN_TIMEOUT_MS });
|
|
94
|
+
if (attempt === null)
|
|
95
|
+
store.addSubagentTurn({ subagent: mate.id, card: card.id, model, ok: reply.ok, ms: reply.ok ? reply.ms : Date.now() - asked, costUsd: reply.costUsd ?? null, tokensIn: reply.tokensIn ?? null, tokensOut: reply.tokensOut ?? null }, now);
|
|
92
96
|
if (!reply.ok)
|
|
93
97
|
return { state: "retry", said: reply.said, ...(log.length === 0 ? {} : { log: log.join("\n\n") }) };
|
|
94
98
|
const read = readTurn(reply.value, context);
|
|
95
99
|
if (!read.ok)
|
|
96
100
|
return { state: "retry", said: `${context.name}'s answer wasn't one this zone allows.`, log: [...log, read.issues.map(issue => issue.line).join("\n"), JSON.stringify(reply.value).slice(0, 4000)].join("\n\n") };
|
|
97
101
|
const answer = read.value;
|
|
98
|
-
const header = `${context.name} (${model}) · ${(reply.ms / 1000).toFixed(1)} s`;
|
|
102
|
+
const header = `${context.name} (${attempt?.backup ? `Codex backup · ${attempt.model}` : model}) · ${(reply.ms / 1000).toFixed(1)} s`;
|
|
99
103
|
const over = turnOverruns(answer);
|
|
100
104
|
if (over.length > 0 && !shortened) {
|
|
101
105
|
shortened = true;
|
|
@@ -105,60 +109,79 @@ export async function subagentTurn(store, flow, definition, stage, card, mate, n
|
|
|
105
109
|
continue;
|
|
106
110
|
}
|
|
107
111
|
shorten = undefined;
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
+
const accepted = store.transact(() => {
|
|
113
|
+
const problem = attempt?.authorize();
|
|
114
|
+
if (problem != null)
|
|
115
|
+
return { refused: { state: "retry", said: problem } };
|
|
116
|
+
if (answer.remember !== "")
|
|
117
|
+
remember(store, mate, answer.remember, { source: "subagent", card: card.id, by: subagentActor({ name: context.name }) }, now);
|
|
118
|
+
return answer.action === "use_tool" ? {} : { outcome: carryOut(store, flow, definition, stage, card, mate, context, answer, now, io, header) };
|
|
119
|
+
});
|
|
120
|
+
if (accepted.refused !== undefined)
|
|
121
|
+
return accepted.refused;
|
|
122
|
+
if (accepted.outcome !== undefined) {
|
|
123
|
+
const outcome = accepted.outcome;
|
|
112
124
|
return log.length === 0 ? outcome : { ...outcome, log: `${log.join("\n\n")}\n\n${outcome.log ?? ""}`.trim() };
|
|
113
125
|
}
|
|
114
126
|
log.push(`${header}\n\n${JSON.stringify(answer)}`);
|
|
115
|
-
const waiting = await useTool(store, flow, stage, card, mate, context, answer, io, now);
|
|
127
|
+
const waiting = await useTool(store, flow, stage, card, mate, context, answer, io, now, attempt?.authorize);
|
|
116
128
|
if (waiting !== null)
|
|
117
129
|
return { ...waiting, log: log.join("\n\n") };
|
|
118
130
|
}
|
|
119
131
|
}
|
|
120
|
-
async function useTool(store, flow, stage, card, mate, context, answer, io, now) {
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
132
|
+
async function useTool(store, flow, stage, card, mate, context, answer, io, now, authorize) {
|
|
133
|
+
const prepared = store.transact(() => {
|
|
134
|
+
const authorityProblem = authorize?.();
|
|
135
|
+
if (authorityProblem != null)
|
|
136
|
+
return { outcome: { state: "retry", said: authorityProblem } };
|
|
137
|
+
const split = answer.tool.indexOf(".");
|
|
138
|
+
const tool = split < 0 ? answer.tool : answer.tool.slice(0, split), action = split < 0 ? "" : answer.tool.slice(split + 1);
|
|
139
|
+
const receipt = { subagent: mate.id, card: card.id, entry: card.entry, tool: tool.slice(0, 40), action: action.slice(0, 64) || "(none)", why: answer.reason };
|
|
140
|
+
const refuse = (input, said) => { store.addSubagentCall({ ...receipt, input, rule: "never", state: "refused", result: said }, now); return { outcome: null }; };
|
|
141
|
+
if (!(context.tools ?? []).some(one => one.name === answer.tool))
|
|
142
|
+
return refuse({}, `There's no ${answer.tool} among the tools you may use.`);
|
|
143
|
+
let input;
|
|
144
|
+
try {
|
|
145
|
+
const parsed = JSON.parse(answer.input === "" ? "{}" : answer.input);
|
|
146
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
147
|
+
return refuse({}, "Its input wasn't a JSON object.");
|
|
148
|
+
input = parsed;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
131
151
|
return refuse({}, "Its input wasn't a JSON object.");
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
152
|
+
}
|
|
153
|
+
const grant = store.subagentGrant(mate.id, tool);
|
|
154
|
+
const info = grant?.actions.find(one => one.name === action);
|
|
155
|
+
if (grant === null || info === undefined)
|
|
156
|
+
return refuse(input, "This tool action is no longer available.");
|
|
157
|
+
const problem = inputProblem(info, input);
|
|
158
|
+
if (problem !== null)
|
|
159
|
+
return refuse(input, problem);
|
|
160
|
+
const rule = ruleFor(grant, action, input);
|
|
161
|
+
if (rule.use === "never")
|
|
162
|
+
return refuse(input, rule.why);
|
|
163
|
+
if (rule.use === "free") {
|
|
164
|
+
const id = store.addSubagentCall({ ...receipt, input, rule: "free", state: "running" }, now);
|
|
165
|
+
return { call: id };
|
|
166
|
+
}
|
|
167
|
+
const soul = { name: context.name, role: context.role };
|
|
168
|
+
const id = store.addSubagentCall({ ...receipt, input, rule: "ask", state: "asked", result: rule.why }, now);
|
|
169
|
+
const words = callWords(tool, action, input, 480);
|
|
170
|
+
const question = store.openSubagentQuestion({ subagent: mate.id, card: card.id, entry: card.entry, question: `Use ${words}?`, options: [{ id: APPROVE, label: "Approve" }, { id: DENY, label: "Deny" }], askedOf: context.person, toolCall: id }, now);
|
|
171
|
+
if (question === null)
|
|
172
|
+
return { outcome: { state: "failed", said: "It asked to make the same call twice." } };
|
|
173
|
+
notifyPeople(store, card, [context.person], null, { key: `teammate-q:${question}`, attention: true, subject: `${subagentLabel(soul)} asks to use ${action} on “${card.title}”`,
|
|
174
|
+
body: `${words}\n\n${answer.reason === "" ? "" : `Why: ${answer.reason}\n`}(${rule.why})\n\nApprove makes exactly this call. Deny stops it. Or answer in words to tell ${context.name} what to do instead.`,
|
|
175
|
+
}, now);
|
|
176
|
+
if (stage.kind !== "approval")
|
|
177
|
+
store.updateFlowCard(card.id, { waiting: `${context.name} asked ${context.person} to approve: ${words}`.slice(0, 300) }, now);
|
|
178
|
+
return { outcome: { state: "waiting", said: `Asked ${context.person} to approve ${action}`, nextAt: ASKED } };
|
|
179
|
+
});
|
|
180
|
+
if ("call" in prepared) {
|
|
181
|
+
await makeCall(store, store.subagentCall(prepared.call), flow.repo, io, now);
|
|
148
182
|
return null;
|
|
149
183
|
}
|
|
150
|
-
|
|
151
|
-
const id = store.addSubagentCall({ ...receipt, input, rule: "ask", state: "asked", result: rule.why }, now);
|
|
152
|
-
const words = callWords(tool, action, input, 480);
|
|
153
|
-
const question = store.openSubagentQuestion({ subagent: mate.id, card: card.id, entry: card.entry, question: `Use ${words}?`, options: [{ id: APPROVE, label: "Approve" }, { id: DENY, label: "Deny" }], askedOf: context.person, toolCall: id }, now);
|
|
154
|
-
if (question === null)
|
|
155
|
-
return { state: "failed", said: "It asked to make the same call twice." };
|
|
156
|
-
notifyPeople(store, card, [context.person], null, { key: `teammate-q:${question}`, attention: true, subject: `${subagentLabel(soul)} asks to use ${action} on “${card.title}”`,
|
|
157
|
-
body: `${words}\n\n${answer.reason === "" ? "" : `Why: ${answer.reason}\n`}(${rule.why})\n\nApprove makes exactly this call. Deny stops it. Or answer in words to tell ${context.name} what to do instead.`,
|
|
158
|
-
}, now);
|
|
159
|
-
if (stage.kind !== "approval")
|
|
160
|
-
store.updateFlowCard(card.id, { waiting: `${context.name} asked ${context.person} to approve: ${words}`.slice(0, 300) }, now);
|
|
161
|
-
return { state: "waiting", said: `Asked ${context.person} to approve ${action}`, nextAt: ASKED };
|
|
184
|
+
return prepared.outcome;
|
|
162
185
|
}
|
|
163
186
|
function keptWhole(store, flow, card, author, text, limit, holds, what, now) {
|
|
164
187
|
const kept = passOn(text, limit, { label: "the card's discussion", href: flowCardHref(flow.id, card.id) }, holds);
|
package/dist/subagents-ui.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { field, input, btn } from "./server/kit.js";
|
|
1
2
|
import { labelOf, nameOf, summaryOf, SUBAGENT_MODELS, zonesOf } from "./subagent-admin.js";
|
|
2
3
|
import { SUBAGENT_TEMPLATES } from "./subagents.js";
|
|
3
4
|
import { projectToolsOf } from "./project-tools.js";
|
|
@@ -122,6 +123,9 @@ export function subagentPageHtml(store, mate, viewer, projectName, canManage, ap
|
|
|
122
123
|
const soul = html `<details class="card"${canManage && html ` open`}><summary>Soul file</summary><p class="meta">Who ${name} is and its rules, read every turn. Version ${mate.version}${latest !== undefined && ` · saved by ${latest.savedBy}, ${when(latest.savedAt)}`} · <a href="/settings/lead/subagents/${mate.id}/soul.md" download>Download</a></p>${canManage
|
|
123
124
|
? postForm(`/settings/lead/subagents/${mate.id}/soul`, html `<label class="sr-only" for="subagent-soul">Soul file</label><textarea id="subagent-soul" name="soul" rows="24" class="mono" maxlength="12000" spellcheck="false">${notice.soulDraft ?? mate.soul}</textarea><button>Save</button>`, { attrs: { "data-soul-form": true } })
|
|
124
125
|
: html `<pre class="mono">${mate.soul}</pre>`}</details>`;
|
|
125
|
-
const
|
|
126
|
-
|
|
126
|
+
const backupProblem = notice.problem?.includes("Codex backup") === true;
|
|
127
|
+
const backupPasswordProblem = backupProblem && notice.problem?.startsWith("Enter your Toolroll password") === true;
|
|
128
|
+
const backup = html `<input type="hidden" name="backupPresent" value="1"><details class="k-disclose" id="backup"${(backupProblem || mate.codexBackupModel !== null) && html ` open`}><summary>Codex backup · ${mate.codexBackupModel === null ? "Off" : "On"}</summary><p class="meta">When Claude hits its limit or isn't installed, send this teammate's card, memory and tool results to Codex through your ChatGPT sign-in. Tool approvals stay the same.</p>${field({ id: "subagent-backup-model", label: "Codex model", hint: "Leave blank to turn off. Each Claude or Codex attempt counts toward the daily limit.", error: backupProblem && !backupPasswordProblem ? notice.problem ?? null : null, control: input({ id: "subagent-backup-model", name: "codexBackupModel", value: notice.backupDraft ?? mate.codexBackupModel ?? "", hint: true, error: backupProblem && !backupPasswordProblem, attrs: { autocomplete: "off", spellcheck: "false" } }) })}${reauth(field({ id: "subagent-backup-password", label: "Password to enable or change backup", error: backupPasswordProblem ? notice.problem ?? null : null, control: input({ id: "subagent-backup-password", name: "password", type: "password", error: backupPasswordProblem, attrs: { autocomplete: "current-password" } }) }))}</details>`;
|
|
129
|
+
const settings = canManage && html `<details class="card"${backupProblem && html ` open`}><summary>Settings</summary>${postForm(`/settings/lead/subagents/${mate.id}/settings`, html `<label>Model<select name="model">${SUBAGENT_MODELS.map(one => html `<option value="${one}"${(mate.model ?? "default") === one && html ` selected`}>${one === "default" ? "The lead chat's model" : one[0].toUpperCase() + one.slice(1)}</option>`)}</select></label><label>Turns a day, at most<input type="number" name="dailyTurns" min="1" max="2000" value="${mate.dailyTurns}"></label><label>Reports to<select name="manager">${[...new Set([mate.manager, ...approvers])].map(one => html `<option value="${one}"${one === mate.manager && html ` selected`}>${one}</option>`)}</select></label>${backup}${btn("Save settings", { type: "submit" })}`)}${postForm(`/settings/lead/subagents/${mate.id}/state`, html `<button class="danger">Remove ${name} from the team</button>`, { attrs: { class: "danger-zone mt-3" }, hidden: { state: "removed" } })}</details>`;
|
|
130
|
+
return html `${notice.problem && !backupProblem && html `<p class="problem" role="alert">${notice.problem}</p>`}${notice.said && html `<p class="said" role="status">${notice.said}</p>`}<p class="meta">${projectName(mate.repo)} · ${mate.state === "active" ? "Working" : "Paused: its decisions go to people"} · reports to ${mate.manager}</p>${manage}${questions.length > 0 && html `<section><h2>Questions</h2>${asked}</section>`}<section class="card"><h2>Today</h2><p class="subagent-summary">${lines(summaryOf(store, mate, startOfDay()).said)}</p></section>${weekSection(store, mate, canManage)}<section class="card"><h2>Works on</h2>${where}</section>${toolsSection(store, mate, canManage)}${deskSection(store, mate, canManage)}${memorySection(store, mate, canManage, notice.query ?? null)}${soul}<details class="card"><summary>What ${name} did</summary>${activity}</details>${settings}`;
|
|
127
131
|
}
|
package/dist/subagents.js
CHANGED
|
@@ -189,13 +189,16 @@ export function claudeTurnRunner(runner = run) {
|
|
|
189
189
|
"-p", "--output-format", "json", "--json-schema", JSON.stringify(TURN_MODEL_SCHEMA), ...CLAUDE_NO_TOOLS_ARGS, ...claudeModelArgs(request.model),
|
|
190
190
|
], { cwd: dir, stdin: request.prompt, timeoutMs: request.timeoutMs, maxBuffer: 512 * 1024, omitEnv: ALL_CREDENTIAL_ENV, processGroup: true });
|
|
191
191
|
if (result.notFound)
|
|
192
|
-
return { ok: false, said: "Claude isn't installed on this computer." };
|
|
192
|
+
return { ok: false, said: "Claude isn't installed on this computer.", backupReason: "unavailable" };
|
|
193
193
|
if (result.timedOut)
|
|
194
194
|
return { ok: false, said: "Claude took too long to decide." };
|
|
195
195
|
const body = claudeJsonBody(result.stdout, 512 * 1024);
|
|
196
196
|
if (result.code !== 0 || body === null || body["is_error"] === true || body["subtype"] !== "success") {
|
|
197
197
|
const why = typeof body?.["subtype"] === "string" && body["subtype"] !== "success" ? ` (${String(body["subtype"]).replace(/_/g, " ").slice(0, 60)})` : result.code !== 0 ? ` (exit ${result.code})` : "";
|
|
198
|
-
|
|
198
|
+
const backupReason = result.code !== 0 && body?.["type"] === "result" && body["is_error"] === true
|
|
199
|
+
&& body["api_error_status"] === 429 && ["usage_limit_reached", "rate_limit_error"].includes(String(body["api_error"])) ? "usage-limit" : undefined;
|
|
200
|
+
return { ok: false, said: backupReason === "usage-limit" ? "Claude reached its usage limit." : CLAUDE_SIGNED_OUT.test(`${result.stdout}${result.stderr}`) ? "Claude isn't signed in on this computer." : `Claude couldn't decide${why}.`,
|
|
201
|
+
...costOf(body ?? {}), ...(backupReason === undefined ? {} : { backupReason }) };
|
|
199
202
|
}
|
|
200
203
|
const cost = costOf(body);
|
|
201
204
|
if (body["structured_output"] !== undefined && body["structured_output"] !== null)
|