@bendyline/gezel-cli 1.1.1 → 1.2.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 +124 -3
- package/dist/app-author-command.js +1 -0
- package/dist/app-command.js +16 -24
- package/dist/bin/gezel-main.js +901 -106
- package/dist/handboek-export.js +1 -0
- package/dist/knowledge-command.js +1 -0
- package/dist/tui/index.js +26 -14
- package/package.json +10 -10
package/dist/bin/gezel-main.js
CHANGED
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
// src/bin/gezel.ts
|
|
4
4
|
import { basename as basename4, isAbsolute as isAbsolutePath, join as joinPath } from "path";
|
|
5
|
-
import { GEZEL_VERSION, getLogOutput, setLogOutput } from "@bendyline/gezel";
|
|
6
5
|
import {
|
|
7
|
-
|
|
6
|
+
GEZEL_VERSION,
|
|
7
|
+
getLogLevel,
|
|
8
|
+
getLogOutput,
|
|
9
|
+
setLogLevel,
|
|
10
|
+
setLogOutput
|
|
11
|
+
} from "@bendyline/gezel";
|
|
12
|
+
import {
|
|
13
|
+
GezelApiError as GezelApiError3,
|
|
8
14
|
streamChatEvents
|
|
9
15
|
} from "@bendyline/gezel-client";
|
|
10
16
|
import {
|
|
@@ -17,8 +23,40 @@ import {
|
|
|
17
23
|
stopOwnedDaemon as stopOwnedDaemon2,
|
|
18
24
|
stopProcessByPid
|
|
19
25
|
} from "@bendyline/gezel-client/node";
|
|
26
|
+
import { resolveOnDeviceProvider } from "@bendyline/gezel/native";
|
|
20
27
|
import { Command } from "commander";
|
|
21
28
|
|
|
29
|
+
// src/cli-errors.ts
|
|
30
|
+
function formatCliFailure(err, env2 = process.env) {
|
|
31
|
+
if (!(err instanceof Error)) return null;
|
|
32
|
+
if (err.name === "CliError") return err.message;
|
|
33
|
+
if (err.name !== "GezelApiError" || env2.GEZEL_DEBUG === "1") return null;
|
|
34
|
+
const { status, details } = err;
|
|
35
|
+
const request = /\bon ([A-Z]+ \S+)/.exec(err.message)?.[1];
|
|
36
|
+
const serviceText = detailText(details);
|
|
37
|
+
if (status === 404) {
|
|
38
|
+
const what = serviceText && serviceText.toLowerCase() !== "not found" ? serviceText : void 0;
|
|
39
|
+
return `error: not found${what ? `: ${what}` : request ? ` (${request})` : ""}`;
|
|
40
|
+
}
|
|
41
|
+
const lines = [`error: ${serviceText ?? err.message}`];
|
|
42
|
+
if (serviceText && request) lines.push(`(Gezel service answered ${status ?? "?"} to ${request})`);
|
|
43
|
+
lines.push("Set GEZEL_DEBUG=1 to see the full error.");
|
|
44
|
+
return lines.join("\n");
|
|
45
|
+
}
|
|
46
|
+
function isNotFound(err) {
|
|
47
|
+
return err instanceof Error && err.name === "GezelApiError" && err.status === 404;
|
|
48
|
+
}
|
|
49
|
+
function detailText(details) {
|
|
50
|
+
if (typeof details === "string" && details.trim()) return details.trim();
|
|
51
|
+
if (details && typeof details === "object") {
|
|
52
|
+
for (const key of ["message", "error"]) {
|
|
53
|
+
const value = details[key];
|
|
54
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return void 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
22
60
|
// src/connection.ts
|
|
23
61
|
import { createHash, randomUUID } from "crypto";
|
|
24
62
|
import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
@@ -37,6 +75,7 @@ import {
|
|
|
37
75
|
createTrustingFetch,
|
|
38
76
|
discoverOrSpawn,
|
|
39
77
|
electronNativeBinCandidates,
|
|
78
|
+
ensureProjectForFolder as ensureClientProjectForFolder,
|
|
40
79
|
isProcessAlive,
|
|
41
80
|
readRuntime,
|
|
42
81
|
readSystemServiceEndpoint,
|
|
@@ -502,25 +541,15 @@ function fileTokenStorage(storageKey) {
|
|
|
502
541
|
}
|
|
503
542
|
async function ensureProjectForFolder(client, folderPath) {
|
|
504
543
|
const wd = resolve(folderPath);
|
|
505
|
-
const eq = (a, b) => !!a && (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
506
|
-
const { projects } = await client.listProjects();
|
|
507
|
-
const exact = projects.find((p) => eq(p.workingDir, wd));
|
|
508
|
-
if (exact) return exact.id;
|
|
509
544
|
const name = basename(wd) || "workspace";
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
return orphan.id;
|
|
514
|
-
}
|
|
515
|
-
const created = await client.createProject({
|
|
516
|
-
name,
|
|
545
|
+
const result = await ensureClientProjectForFolder(client, wd, {
|
|
546
|
+
mode: "solo",
|
|
547
|
+
source: "cli",
|
|
517
548
|
description: `CLI workspace at ${wd}`,
|
|
518
549
|
about: `${name} \u2014 working directory ${wd}. Fill in who this project is for, what's in scope, and what's explicitly out of scope.`,
|
|
519
|
-
missionObjectives: `${name} \u2014 fill in concrete success criteria for this project
|
|
520
|
-
mode: "solo",
|
|
521
|
-
workingDir: wd
|
|
550
|
+
missionObjectives: `${name} \u2014 fill in concrete success criteria for this project.`
|
|
522
551
|
});
|
|
523
|
-
return
|
|
552
|
+
return result.projectId;
|
|
524
553
|
}
|
|
525
554
|
async function ensureCliProjectLead(client, projectId) {
|
|
526
555
|
const project = await client.getProject(projectId);
|
|
@@ -568,6 +597,190 @@ async function resolveTuiProject(client, globals) {
|
|
|
568
597
|
return ensureProjectForFolder(client, folder);
|
|
569
598
|
}
|
|
570
599
|
|
|
600
|
+
// src/craftbook-command.ts
|
|
601
|
+
import { setTimeout as delay } from "timers/promises";
|
|
602
|
+
import { createAwakeTimeout } from "@bendyline/gezel";
|
|
603
|
+
|
|
604
|
+
// src/tui/craftbook-start.ts
|
|
605
|
+
import {
|
|
606
|
+
CRAFTBOOK_CATEGORY_FAMILY_META,
|
|
607
|
+
CRAFTBOOK_CATEGORY_META,
|
|
608
|
+
CRAFTBOOK_ROLE_META,
|
|
609
|
+
resolveCraftbookCategory,
|
|
610
|
+
visibleCatalogItems
|
|
611
|
+
} from "@bendyline/gezel";
|
|
612
|
+
function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
|
|
613
|
+
const byId = /* @__PURE__ */ new Map();
|
|
614
|
+
for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
|
|
615
|
+
if (item.manifest.kind !== "craftbook-template") continue;
|
|
616
|
+
const manifest = item.manifest;
|
|
617
|
+
if (byId.has(manifest.id)) continue;
|
|
618
|
+
byId.set(manifest.id, {
|
|
619
|
+
id: manifest.id,
|
|
620
|
+
name: manifest.name,
|
|
621
|
+
...manifest.description ? { description: manifest.description } : {},
|
|
622
|
+
version: manifest.version,
|
|
623
|
+
sourceId: item.sourceId,
|
|
624
|
+
source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
|
|
625
|
+
stepCount: manifest.steps.length,
|
|
626
|
+
tags: manifest.tags ?? [],
|
|
627
|
+
role: manifest.role ?? "general",
|
|
628
|
+
category: resolveCraftbookCategory(manifest)
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
632
|
+
}
|
|
633
|
+
function findCraftbook(books, value) {
|
|
634
|
+
const query = value.trim().toLowerCase();
|
|
635
|
+
return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
|
|
636
|
+
}
|
|
637
|
+
function craftbookStartRequest(book) {
|
|
638
|
+
const summary = book.description?.trim();
|
|
639
|
+
const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
|
|
640
|
+
return {
|
|
641
|
+
title: book.name,
|
|
642
|
+
description,
|
|
643
|
+
craftbookId: book.id,
|
|
644
|
+
craftbookSourceId: book.sourceId,
|
|
645
|
+
...book.version ? { craftbookVersion: book.version } : {},
|
|
646
|
+
dispatchEntry: true,
|
|
647
|
+
trustScripts: true
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// src/craftbook-command.ts
|
|
652
|
+
function resolveCraftbookInvocation(books, tokens) {
|
|
653
|
+
for (let length = tokens.length; length > 0; length--) {
|
|
654
|
+
const book = findCraftbook(books, tokens.slice(0, length).join(" "));
|
|
655
|
+
if (book) return { book, args: tokens.slice(length) };
|
|
656
|
+
}
|
|
657
|
+
throw new CliError(`craftbook not found: ${tokens.join(" ")}`);
|
|
658
|
+
}
|
|
659
|
+
function parseCraftbookParams(book, tokens) {
|
|
660
|
+
const schema = book.paramSchema ?? {};
|
|
661
|
+
const properties = schema.properties ?? {};
|
|
662
|
+
const keys = Object.keys(properties);
|
|
663
|
+
const params = {};
|
|
664
|
+
for (const token of tokens) {
|
|
665
|
+
const match = /^([A-Za-z][\w.-]*)=([\s\S]*)$/.exec(token);
|
|
666
|
+
const key = match?.[1] ?? keys.find((name) => !Object.hasOwn(params, name));
|
|
667
|
+
if (!key || !Object.hasOwn(properties, key))
|
|
668
|
+
throw new CliError(`unknown craftbook argument: ${token}`);
|
|
669
|
+
if (Object.hasOwn(params, key)) throw new CliError(`duplicate craftbook parameter: ${key}`);
|
|
670
|
+
const value = match ? match[2] : token;
|
|
671
|
+
const def = properties[key];
|
|
672
|
+
if (Array.isArray(def.enum) && !def.enum.map(String).includes(value)) {
|
|
673
|
+
throw new CliError(`${key} must be one of: ${def.enum.join(", ")}`);
|
|
674
|
+
}
|
|
675
|
+
if (def.type === "boolean" && !["true", "false"].includes(value))
|
|
676
|
+
throw new CliError(`${key} must be true or false`);
|
|
677
|
+
if (def.type === "number" || def.type === "integer") {
|
|
678
|
+
const number = Number(value);
|
|
679
|
+
if (!value.trim() || !Number.isFinite(number) || def.type === "integer" && !Number.isInteger(number))
|
|
680
|
+
throw new CliError(`${key} must be a ${def.type}`);
|
|
681
|
+
if (typeof def.minimum === "number" && number < def.minimum)
|
|
682
|
+
throw new CliError(`${key} must be at least ${def.minimum}`);
|
|
683
|
+
if (typeof def.maximum === "number" && number > def.maximum)
|
|
684
|
+
throw new CliError(`${key} must be at most ${def.maximum}`);
|
|
685
|
+
}
|
|
686
|
+
if (typeof def.pattern === "string" && !new RegExp(def.pattern).test(value))
|
|
687
|
+
throw new CliError(`${key} must match ${def.pattern}`);
|
|
688
|
+
if (typeof def.minLength === "number" && value.trim().length < def.minLength)
|
|
689
|
+
throw new CliError(`${key} is too short`);
|
|
690
|
+
params[key] = value;
|
|
691
|
+
}
|
|
692
|
+
for (const key of Array.isArray(schema.required) ? schema.required : []) {
|
|
693
|
+
if (typeof key === "string" && !Object.hasOwn(params, key) && properties[key]?.default === void 0)
|
|
694
|
+
throw new CliError(`missing required craftbook parameter: ${key}`);
|
|
695
|
+
}
|
|
696
|
+
return params;
|
|
697
|
+
}
|
|
698
|
+
var READ_RETRY_DELAYS = [250, 750, 1500];
|
|
699
|
+
function transientTaskReadError(error) {
|
|
700
|
+
const codes = /ECONNRESET|ECONNREFUSED|ECONNABORTED|EPIPE|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|UND_ERR_(?:SOCKET|CONNECT_TIMEOUT)|NGHTTP2_ENHANCE_YOUR_CALM|Connect Timeout Error|socket hang up|other side closed/;
|
|
701
|
+
if (error instanceof Error && error.name === "GezelApiError") {
|
|
702
|
+
const apiError = error;
|
|
703
|
+
return apiError.status === 0 && apiError.details?.kind === "transport" && apiError.details.readRetryExhausted !== true && typeof apiError.details.cause === "string" && codes.test(apiError.details.cause);
|
|
704
|
+
}
|
|
705
|
+
return error instanceof TypeError && error.cause instanceof Error && codes.test(`${error.cause.code ?? ""} ${error.cause.message}`);
|
|
706
|
+
}
|
|
707
|
+
async function readTaskObservation(read, budget, signal) {
|
|
708
|
+
for (let retries = 0; ; retries++) {
|
|
709
|
+
signal.throwIfAborted();
|
|
710
|
+
if (retries > 0 && budget.expired()) throw new CliError("Task observation timed out.");
|
|
711
|
+
try {
|
|
712
|
+
return await read();
|
|
713
|
+
} catch (error) {
|
|
714
|
+
signal.throwIfAborted();
|
|
715
|
+
if (!transientTaskReadError(error) || retries >= READ_RETRY_DELAYS.length || budget.expired())
|
|
716
|
+
throw error;
|
|
717
|
+
await sleepWithinBudget(READ_RETRY_DELAYS[retries], budget, signal);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
async function sleepWithinBudget(backoffMs, budget, signal) {
|
|
722
|
+
if (budget.remainingMs() > backoffMs) {
|
|
723
|
+
await delay(backoffMs, void 0, { signal });
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
while (!budget.expired()) {
|
|
727
|
+
await delay(Math.max(1, budget.remainingMs()), void 0, { signal });
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
async function waitForTask(client, ref, options) {
|
|
731
|
+
const timeout = createAwakeTimeout(options.timeoutMs, { pollMs: 100 });
|
|
732
|
+
const budget = timeout.budget;
|
|
733
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout.signal]) : timeout.signal;
|
|
734
|
+
let previous = "";
|
|
735
|
+
let lastTask;
|
|
736
|
+
const read = (operation) => readTaskObservation(operation, budget, signal);
|
|
737
|
+
try {
|
|
738
|
+
for (; ; ) {
|
|
739
|
+
const task2 = await read(() => client.getTaskByRef(ref, signal));
|
|
740
|
+
lastTask = task2;
|
|
741
|
+
const progress = `${task2.status}:${task2.activeStepId}`;
|
|
742
|
+
if (progress !== previous) {
|
|
743
|
+
options.onProgress?.(task2);
|
|
744
|
+
previous = progress;
|
|
745
|
+
}
|
|
746
|
+
if (task2.status === "complete") return { task: task2, outcome: "complete", exitCode: 0 };
|
|
747
|
+
if (task2.status === "canceled") return { task: task2, outcome: "canceled", exitCode: 1 };
|
|
748
|
+
if (task2.status === "paused" || task2.status === "draft")
|
|
749
|
+
return { task: task2, outcome: "blocked", exitCode: 2 };
|
|
750
|
+
const refs = /* @__PURE__ */ new Set([task2.ref]);
|
|
751
|
+
if (task2.fanout || task2.craftbook.spawn || task2.craftbook.cliWorkflow) {
|
|
752
|
+
const { tasks } = await read(
|
|
753
|
+
() => client.listTaskChildren(task2.projectId, task2.num, void 0, signal)
|
|
754
|
+
);
|
|
755
|
+
if (!task2.craftbook.cliWorkflow && !tasks.some((child) => child.status === "active") && tasks.some((child) => child.status === "paused" || child.status === "canceled"))
|
|
756
|
+
return { task: task2, outcome: "blocked", exitCode: 2 };
|
|
757
|
+
if (!task2.craftbook.cliWorkflow) for (const child of tasks) refs.add(child.ref);
|
|
758
|
+
}
|
|
759
|
+
if (client.listQuestions) {
|
|
760
|
+
const { questions } = await read(
|
|
761
|
+
() => client.listQuestions(
|
|
762
|
+
{
|
|
763
|
+
projectId: task2.projectId,
|
|
764
|
+
pending: true
|
|
765
|
+
},
|
|
766
|
+
signal
|
|
767
|
+
)
|
|
768
|
+
);
|
|
769
|
+
const questionIds = questions.filter((q) => q.taskRef && refs.has(q.taskRef)).map((q) => q.id);
|
|
770
|
+
if (questionIds.length) return { task: task2, outcome: "blocked", exitCode: 2, questionIds };
|
|
771
|
+
}
|
|
772
|
+
if (budget.expired()) return { task: task2, outcome: "timeout", exitCode: 3 };
|
|
773
|
+
await delay(Math.min(options.pollMs ?? 1e3, budget.remainingMs()), void 0, { signal });
|
|
774
|
+
}
|
|
775
|
+
} catch (error) {
|
|
776
|
+
options.signal?.throwIfAborted();
|
|
777
|
+
if (budget.expired() && lastTask) return { task: lastTask, outcome: "timeout", exitCode: 3 };
|
|
778
|
+
throw error;
|
|
779
|
+
} finally {
|
|
780
|
+
timeout.dispose();
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
571
784
|
// src/engagement-mode.ts
|
|
572
785
|
var CLI_ENGAGEMENT_MODES = [
|
|
573
786
|
{
|
|
@@ -849,6 +1062,11 @@ function formatGb(bytes) {
|
|
|
849
1062
|
return (bytes / 1e9).toFixed(2);
|
|
850
1063
|
}
|
|
851
1064
|
|
|
1065
|
+
// src/native-command.ts
|
|
1066
|
+
import {
|
|
1067
|
+
NativeEngineNameSchema
|
|
1068
|
+
} from "@bendyline/gezel";
|
|
1069
|
+
|
|
852
1070
|
// src/tui/bootstrap.ts
|
|
853
1071
|
import {
|
|
854
1072
|
computeModelFit,
|
|
@@ -872,6 +1090,14 @@ function parseNativeVariant(value) {
|
|
|
872
1090
|
if (NATIVE_VARIANTS.includes(value)) return value;
|
|
873
1091
|
throw new CliError(`--variant must be one of ${NATIVE_VARIANTS.join(", ")} (got "${value}")`);
|
|
874
1092
|
}
|
|
1093
|
+
function parseNativeEngine(value) {
|
|
1094
|
+
if (value === void 0) return void 0;
|
|
1095
|
+
const parsed = NativeEngineNameSchema.safeParse(value);
|
|
1096
|
+
if (parsed.success) return parsed.data;
|
|
1097
|
+
throw new CliError(
|
|
1098
|
+
`--engine must be one of ${NativeEngineNameSchema.options.join(", ")} (got "${value}")`
|
|
1099
|
+
);
|
|
1100
|
+
}
|
|
875
1101
|
function formatNativeStatus(status) {
|
|
876
1102
|
const installed = new Set(
|
|
877
1103
|
status.engines.filter((engine) => engine.installed).map((engine) => engine.name)
|
|
@@ -881,7 +1107,9 @@ function formatNativeStatus(status) {
|
|
|
881
1107
|
`release: native-v${status.release} (${status.pinned ? "verified pin" : "unpinned \u2014 downloads disabled"})`,
|
|
882
1108
|
`platform: ${status.platformKey ?? "unsupported \u2014 downloads unavailable"}`,
|
|
883
1109
|
`llama backend: ${status.llamaBackend ?? "automatic"}`,
|
|
884
|
-
|
|
1110
|
+
// Name the members: `native list` shows every engine the release carries
|
|
1111
|
+
// (ds4, duckdb too), so a bare "0/4" read as a miscount beside it.
|
|
1112
|
+
`toolkit: ${toolkitInstalled}/${NATIVE_TOOLKIT.length} installed (${NATIVE_TOOLKIT.join(", ")}; see \`gezel native list\` for every engine)`
|
|
885
1113
|
].join("\n");
|
|
886
1114
|
}
|
|
887
1115
|
function formatNativeList(status) {
|
|
@@ -908,7 +1136,7 @@ async function installNativeToolkit(client, options) {
|
|
|
908
1136
|
);
|
|
909
1137
|
}
|
|
910
1138
|
const llamaVariant = options.variant ?? status.llamaBackend;
|
|
911
|
-
for (const engine of NATIVE_TOOLKIT) {
|
|
1139
|
+
for (const engine of options.engines ?? NATIVE_TOOLKIT) {
|
|
912
1140
|
await ensureOneEngine(client, engine, llamaVariant, options.output);
|
|
913
1141
|
}
|
|
914
1142
|
return client.getNativeEngineStatus();
|
|
@@ -982,6 +1210,226 @@ function errorMessage(error) {
|
|
|
982
1210
|
return error instanceof Error ? error.message : String(error);
|
|
983
1211
|
}
|
|
984
1212
|
|
|
1213
|
+
// src/run-readiness.ts
|
|
1214
|
+
var READY = { ready: true };
|
|
1215
|
+
async function settledFirstRunConfig(client, options = {}) {
|
|
1216
|
+
const attempts = options.attempts ?? 12;
|
|
1217
|
+
const delayMs = options.delayMs ?? 250;
|
|
1218
|
+
let config = await client.getConfig();
|
|
1219
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
1220
|
+
if (config.firstRunCompleted || config.provider !== "copilot") return config;
|
|
1221
|
+
await new Promise((resolve6) => setTimeout(resolve6, delayMs));
|
|
1222
|
+
config = await client.getConfig();
|
|
1223
|
+
}
|
|
1224
|
+
return config;
|
|
1225
|
+
}
|
|
1226
|
+
async function checkRunReadiness(client, gezelId, env2 = process.env) {
|
|
1227
|
+
if (env2.GEZEL_MOCK_PROVIDER === "1") return READY;
|
|
1228
|
+
const config = await settledFirstRunConfig(client);
|
|
1229
|
+
let provider = config.provider;
|
|
1230
|
+
if (gezelId) {
|
|
1231
|
+
try {
|
|
1232
|
+
const { parsed } = await client.getGezel(gezelId);
|
|
1233
|
+
if (parsed.frontmatter.provider) provider = parsed.frontmatter.provider;
|
|
1234
|
+
} catch {
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
if (provider !== "llama-cpp" && provider !== "mlx") return READY;
|
|
1238
|
+
if (provider === "llama-cpp" && (config.llamaCppBaseUrl || config.llamaCppModelPath)) {
|
|
1239
|
+
return READY;
|
|
1240
|
+
}
|
|
1241
|
+
if (provider === "mlx" && (config.mlxBaseUrl || config.mlxModelPath)) return READY;
|
|
1242
|
+
const native2 = await client.getNativeEngineStatus();
|
|
1243
|
+
if (!native2.platformKey) return READY;
|
|
1244
|
+
const installed = provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
|
|
1245
|
+
const installedIds = installed.models.map((model2) => model2.id);
|
|
1246
|
+
const pinned = config.defaultModel?.[provider];
|
|
1247
|
+
const engineMissing = provider === "llama-cpp" && !native2.engines.some((engine) => engine.name === "llama-server" && engine.installed);
|
|
1248
|
+
const modelReady = pinned ? installedIds.includes(pinned) : installedIds.length > 0;
|
|
1249
|
+
if (!engineMissing && modelReady) return READY;
|
|
1250
|
+
return {
|
|
1251
|
+
ready: false,
|
|
1252
|
+
message: formatRunSetupMessage({
|
|
1253
|
+
provider,
|
|
1254
|
+
engineMissing,
|
|
1255
|
+
pinned,
|
|
1256
|
+
installedIds
|
|
1257
|
+
})
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
function formatRunSetupMessage(input) {
|
|
1261
|
+
const { provider, engineMissing, pinned, installedIds } = input;
|
|
1262
|
+
const steps = [];
|
|
1263
|
+
if (engineMissing) steps.push("gezel native install");
|
|
1264
|
+
if (pinned && !installedIds.includes(pinned)) {
|
|
1265
|
+
steps.push(`gezel model pull ${pinned}${provider === "mlx" ? " --provider mlx" : ""}`);
|
|
1266
|
+
} else if (!pinned && installedIds.length === 0) {
|
|
1267
|
+
steps.push("gezel model list (then: gezel model pull <id>)");
|
|
1268
|
+
}
|
|
1269
|
+
const lines = [];
|
|
1270
|
+
if (pinned && !installedIds.includes(pinned) && installedIds.length > 0) {
|
|
1271
|
+
lines.push(`Your selected on-device model, ${pinned}, isn't downloaded yet.`);
|
|
1272
|
+
} else if (engineMissing && installedIds.length > 0 && (!pinned || installedIds.includes(pinned))) {
|
|
1273
|
+
lines.push("Gezel's on-device engine isn't installed yet.");
|
|
1274
|
+
} else {
|
|
1275
|
+
lines.push("Gezel isn't set up to chat yet: this device doesn't have an on-device model.");
|
|
1276
|
+
}
|
|
1277
|
+
lines.push("", "Run `gezel` to choose a model and download it, step by step.");
|
|
1278
|
+
if (steps.length > 0) {
|
|
1279
|
+
lines.push("", "Or set it up directly:", ...steps.map((step) => ` ${step}`));
|
|
1280
|
+
}
|
|
1281
|
+
lines.push(
|
|
1282
|
+
"",
|
|
1283
|
+
"To use a cloud model instead, save a key (for example",
|
|
1284
|
+
"`gezel secret set openaiApiKey --stdin`), then run `gezel` and pick it with /model.",
|
|
1285
|
+
"",
|
|
1286
|
+
"Nothing was downloaded."
|
|
1287
|
+
);
|
|
1288
|
+
return lines.join("\n");
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// src/secrets-command.ts
|
|
1292
|
+
import { GezelApiError as GezelApiError2 } from "@bendyline/gezel-client";
|
|
1293
|
+
var credentialFlags = {
|
|
1294
|
+
githubToken: "hasGithubToken",
|
|
1295
|
+
openaiApiKey: "hasOpenaiApiKey",
|
|
1296
|
+
openaiOrganization: "hasOpenaiOrganization",
|
|
1297
|
+
anthropicApiKey: "hasAnthropicApiKey",
|
|
1298
|
+
googleAiApiKey: "hasGoogleAiApiKey",
|
|
1299
|
+
webhookBearerToken: "hasWebhookBearerToken",
|
|
1300
|
+
webhookBasicAuth: "hasWebhookBasicAuth",
|
|
1301
|
+
braveSearchApiKey: "hasBraveSearchApiKey",
|
|
1302
|
+
tavilyApiKey: "hasTavilyApiKey"
|
|
1303
|
+
};
|
|
1304
|
+
function credentialName(name) {
|
|
1305
|
+
if (!Object.hasOwn(credentialFlags, name)) {
|
|
1306
|
+
throw new CliError(`Unknown credential. Run "gezel secret list" for supported names.`);
|
|
1307
|
+
}
|
|
1308
|
+
return name;
|
|
1309
|
+
}
|
|
1310
|
+
async function readSecretInput(options, env2 = process.env, input = process.stdin) {
|
|
1311
|
+
if (Number(options.env !== void 0) + Number(options.stdin === true) !== 1) {
|
|
1312
|
+
throw new CliError("Choose exactly one secret input: --env <VARIABLE> or --stdin.");
|
|
1313
|
+
}
|
|
1314
|
+
let value;
|
|
1315
|
+
if (options.env !== void 0) {
|
|
1316
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(options.env)) {
|
|
1317
|
+
throw new CliError("Use an environment variable name with --env, not its value.");
|
|
1318
|
+
}
|
|
1319
|
+
value = env2[options.env] ?? "";
|
|
1320
|
+
} else {
|
|
1321
|
+
if (input.isTTY) {
|
|
1322
|
+
throw new CliError("--stdin requires piped input. Use --env for an existing shell variable.");
|
|
1323
|
+
}
|
|
1324
|
+
const chunks = [];
|
|
1325
|
+
let size = 0;
|
|
1326
|
+
for await (const chunk of input) {
|
|
1327
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1328
|
+
size += bytes.length;
|
|
1329
|
+
if (size > 65536) throw new CliError("Secret input exceeds 64 KiB.");
|
|
1330
|
+
chunks.push(bytes);
|
|
1331
|
+
}
|
|
1332
|
+
value = Buffer.concat(chunks).toString("utf8");
|
|
1333
|
+
}
|
|
1334
|
+
value = value.replace(/[\r\n]+$/, "");
|
|
1335
|
+
if (!value.trim())
|
|
1336
|
+
throw new CliError('Secret input is empty; use "gezel secret remove" to clear it.');
|
|
1337
|
+
if (Buffer.byteLength(value) > 65536) throw new CliError("Secret input exceeds 64 KiB.");
|
|
1338
|
+
if (/[\r\n\0]/.test(value))
|
|
1339
|
+
throw new CliError("Secret input must be a single line without NUL bytes.");
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
async function writeCredential(client, patch) {
|
|
1343
|
+
try {
|
|
1344
|
+
await client.updateConfig(patch);
|
|
1345
|
+
} catch (error) {
|
|
1346
|
+
const status = error instanceof GezelApiError2 ? ` (HTTP ${error.status})` : "";
|
|
1347
|
+
throw new CliError(
|
|
1348
|
+
`Could not update the credential${status}. Check the service connection and permissions.`
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
function registerSecretCommands(program2, connect, output = console.log) {
|
|
1353
|
+
const secret = program2.command("secret").description("Manage write-only provider credentials");
|
|
1354
|
+
secret.command("list").description("Show supported names and whether each is configured").option("--json", "Output names and configured flags as JSON").action(async (options) => {
|
|
1355
|
+
const config = await (await connect()).getConfig();
|
|
1356
|
+
const credentials = Object.entries(credentialFlags).map(([name, flag]) => ({
|
|
1357
|
+
name,
|
|
1358
|
+
configured: config[flag] === true
|
|
1359
|
+
}));
|
|
1360
|
+
output(
|
|
1361
|
+
options.json ? JSON.stringify({ credentials }) : credentials.map((c) => `${c.name} ${c.configured ? "configured" : "not configured"}`).join("\n")
|
|
1362
|
+
);
|
|
1363
|
+
});
|
|
1364
|
+
secret.command("set <name>").description("Save a provider credential in the service credential store").option("--env <VARIABLE>", "Read the value from this environment variable").option("--stdin", "Read the value from piped stdin").option("--use-for-search", "Also select this Brave credential as the web search provider").option("--json", "Output status as JSON without the value").action(async (name, options) => {
|
|
1365
|
+
const key = credentialName(name);
|
|
1366
|
+
if (options.useForSearch && key === "tavilyApiKey")
|
|
1367
|
+
throw new CliError(
|
|
1368
|
+
"Tavily search is not available yet. Save the key without --use-for-search, and use braveSearchApiKey (or the built-in Wikipedia search) for now."
|
|
1369
|
+
);
|
|
1370
|
+
const provider = key === "braveSearchApiKey" ? "brave" : void 0;
|
|
1371
|
+
if (options.useForSearch && !provider)
|
|
1372
|
+
throw new CliError("--use-for-search requires braveSearchApiKey.");
|
|
1373
|
+
const value = await readSecretInput(options);
|
|
1374
|
+
const client = await connect();
|
|
1375
|
+
const patch = { [key]: value };
|
|
1376
|
+
if (options.useForSearch) {
|
|
1377
|
+
const config = await client.getConfig();
|
|
1378
|
+
patch.webSearch = { ...config.webSearch, provider };
|
|
1379
|
+
}
|
|
1380
|
+
await writeCredential(client, patch);
|
|
1381
|
+
output(
|
|
1382
|
+
options.json ? JSON.stringify({
|
|
1383
|
+
name: key,
|
|
1384
|
+
configured: true,
|
|
1385
|
+
...options.useForSearch ? { searchProvider: provider } : {}
|
|
1386
|
+
}) : `${key}: configured${options.useForSearch ? `; web search: ${provider}` : ""}`
|
|
1387
|
+
);
|
|
1388
|
+
});
|
|
1389
|
+
secret.command("remove <name>").description("Remove a provider credential").option("--json", "Output status as JSON without the value").action(async (name, options) => {
|
|
1390
|
+
const key = credentialName(name);
|
|
1391
|
+
await writeCredential(await connect(), { [key]: "" });
|
|
1392
|
+
output(options.json ? JSON.stringify({ name: key, configured: false }) : `${key}: removed`);
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// src/settings-command.ts
|
|
1397
|
+
import { resolveSecurityPolicy } from "@bendyline/gezel";
|
|
1398
|
+
function enabledValue(state) {
|
|
1399
|
+
if (state === void 0) return void 0;
|
|
1400
|
+
if (state === "on") return true;
|
|
1401
|
+
if (state === "off") return false;
|
|
1402
|
+
throw new CliError("Use on or off.");
|
|
1403
|
+
}
|
|
1404
|
+
function registerSecurityCommands(program2, connect) {
|
|
1405
|
+
program2.command("security").description("Inspect or explicitly change security settings").command("external-services [state]").description("Show or set on/off for model-initiated external services, including web search").option("--json", "Output the setting as JSON").action(async (state, options) => {
|
|
1406
|
+
const enabled = enabledValue(state);
|
|
1407
|
+
const client = await connect();
|
|
1408
|
+
const policy = resolveSecurityPolicy(await client.getConfig());
|
|
1409
|
+
if (enabled !== void 0) {
|
|
1410
|
+
await client.updateConfig({
|
|
1411
|
+
securityPolicy: { ...policy, level: "custom", allowExternalServices: enabled }
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
const result = { allowExternalServices: enabled ?? policy.allowExternalServices };
|
|
1415
|
+
console.log(
|
|
1416
|
+
options.json ? JSON.stringify(result) : `External services: ${result.allowExternalServices ? "on" : "off"}`
|
|
1417
|
+
);
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
function registerProjectSettingsCommands(env2, connect, projectFor) {
|
|
1421
|
+
env2.command("indexing [state]").description("Show or set on/off for background workspace indexing in the current project").option("--json", "Output the project setting as JSON").action(async (state, options) => {
|
|
1422
|
+
const enabled = enabledValue(state);
|
|
1423
|
+
const client = await connect();
|
|
1424
|
+
const projectId = await projectFor(client);
|
|
1425
|
+
const project = enabled === void 0 ? await client.getProject(projectId) : await client.updateProject(projectId, { indexingEnabled: enabled });
|
|
1426
|
+
const result = { projectId, indexingEnabled: project.indexingEnabled !== false };
|
|
1427
|
+
console.log(
|
|
1428
|
+
options.json ? JSON.stringify(result) : `${projectId}: workspace indexing ${result.indexingEnabled ? "on" : "off"}`
|
|
1429
|
+
);
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
|
|
985
1433
|
// src/signal-cleanup.ts
|
|
986
1434
|
function installSignalCleanup(cleanup, options = {}) {
|
|
987
1435
|
if (!cleanup) return () => {
|
|
@@ -1186,71 +1634,155 @@ function resolveRestoreSelection(review, opts) {
|
|
|
1186
1634
|
return { items, skipped };
|
|
1187
1635
|
}
|
|
1188
1636
|
|
|
1189
|
-
// src/
|
|
1637
|
+
// src/unknown-command.ts
|
|
1638
|
+
function unknownCommandMessage(operands, known) {
|
|
1639
|
+
const word = operands[0] ?? "";
|
|
1640
|
+
const lines = [`error: unknown command '${word}'`];
|
|
1641
|
+
const looksLikePrompt = operands.length > 1 || /\s/.test(word) || word.length > 24;
|
|
1642
|
+
const suggestion = looksLikePrompt ? void 0 : closestCommand(word, known);
|
|
1643
|
+
if (suggestion) lines.push(`(Did you mean ${suggestion}?)`);
|
|
1644
|
+
if (looksLikePrompt) {
|
|
1645
|
+
lines.push('To send a prompt, use: gezel run "<prompt>"');
|
|
1646
|
+
}
|
|
1647
|
+
lines.push("Run `gezel --help` to see every command.");
|
|
1648
|
+
return lines.join("\n");
|
|
1649
|
+
}
|
|
1650
|
+
function closestCommand(word, known) {
|
|
1651
|
+
const target = word.toLowerCase();
|
|
1652
|
+
if (!target) return void 0;
|
|
1653
|
+
const limit = Math.max(1, Math.floor(target.length * 0.4));
|
|
1654
|
+
let best;
|
|
1655
|
+
for (const name of known) {
|
|
1656
|
+
const distance = editDistance(target, name.toLowerCase());
|
|
1657
|
+
if (distance > limit) continue;
|
|
1658
|
+
if (!best || distance < best.distance) best = { name, distance };
|
|
1659
|
+
}
|
|
1660
|
+
return best?.name;
|
|
1661
|
+
}
|
|
1662
|
+
function editDistance(a, b) {
|
|
1663
|
+
const rows = a.length + 1;
|
|
1664
|
+
const cols = b.length + 1;
|
|
1665
|
+
const d = Array.from(
|
|
1666
|
+
{ length: rows },
|
|
1667
|
+
(_, i) => Array.from({ length: cols }, (_2, j) => i === 0 ? j : j === 0 ? i : 0)
|
|
1668
|
+
);
|
|
1669
|
+
for (let i = 1; i < rows; i += 1) {
|
|
1670
|
+
for (let j = 1; j < cols; j += 1) {
|
|
1671
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
1672
|
+
let value = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
1673
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1674
|
+
value = Math.min(value, d[i - 2][j - 2] + 1);
|
|
1675
|
+
}
|
|
1676
|
+
d[i][j] = value;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
return d[a.length][b.length];
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
// src/workflow-command.ts
|
|
1683
|
+
import { realpath } from "fs/promises";
|
|
1684
|
+
import { isAbsolute as isAbsolute2, relative, resolve as resolve5 } from "path";
|
|
1685
|
+
import { pathToFileURL } from "url";
|
|
1190
1686
|
import {
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
visibleCatalogItems
|
|
1687
|
+
craftbookFromDoc,
|
|
1688
|
+
formatCraftbookDocErrors,
|
|
1689
|
+
nowIso,
|
|
1690
|
+
parseCraftbookDoc
|
|
1196
1691
|
} from "@bendyline/gezel";
|
|
1197
|
-
function
|
|
1198
|
-
const
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
role: manifest.role ?? "general",
|
|
1213
|
-
category: resolveCraftbookCategory(manifest)
|
|
1214
|
-
});
|
|
1692
|
+
function validateWorkflowCraftbook(document) {
|
|
1693
|
+
const parsed = parseCraftbookDoc(JSON.stringify(document), "json");
|
|
1694
|
+
if (!parsed.ok) throw new CliError(formatCraftbookDocErrors(parsed.errors));
|
|
1695
|
+
const built = craftbookFromDoc(parsed.doc, { now: nowIso() });
|
|
1696
|
+
if (!built.ok) throw new CliError(formatCraftbookDocErrors(built.errors));
|
|
1697
|
+
return built.craftbook;
|
|
1698
|
+
}
|
|
1699
|
+
async function runWorkflow(client, projectId, workspace, file, args, log = console.error, invocation) {
|
|
1700
|
+
const named = /^[a-z][a-z0-9-]*$/.test(file);
|
|
1701
|
+
const path = await realpath(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
|
|
1702
|
+
if (invocation) {
|
|
1703
|
+
const local = relative(await realpath(workspace), path);
|
|
1704
|
+
if (isAbsolute2(local) || local === ".." || local.startsWith("../") || local.startsWith("..\\")) {
|
|
1705
|
+
throw new CliError("A craftbook workflow module must remain inside its project workspace.");
|
|
1706
|
+
}
|
|
1215
1707
|
}
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1708
|
+
const module = await import(pathToFileURL(path).href);
|
|
1709
|
+
if (typeof module.run !== "function")
|
|
1710
|
+
throw new CliError(`workflow ${path} must export an async run(context) function`);
|
|
1711
|
+
return module.run({
|
|
1712
|
+
client,
|
|
1713
|
+
projectId,
|
|
1714
|
+
workspace: resolve5(workspace),
|
|
1715
|
+
args,
|
|
1716
|
+
...invocation ?? {},
|
|
1717
|
+
log,
|
|
1718
|
+
validateCraftbook: validateWorkflowCraftbook,
|
|
1719
|
+
runCraftbook: async (id, params, options = {}) => {
|
|
1720
|
+
let ref = options.taskRef;
|
|
1721
|
+
if (!ref) {
|
|
1722
|
+
const { craftbook: book } = await client.getCraftbook(id, { projectId, source: "project" });
|
|
1723
|
+
const parsed = parseCraftbookParams(
|
|
1724
|
+
book,
|
|
1725
|
+
Object.entries(params).map(([key, value]) => `${key}=${value}`)
|
|
1726
|
+
);
|
|
1727
|
+
const task2 = await client.createTask(projectId, {
|
|
1728
|
+
title: options.title ?? book.name,
|
|
1729
|
+
description: `Run the project craftbook ${book.name}. Follow every step and satisfy its required outcomes before completing this task.`,
|
|
1730
|
+
craftbookId: id,
|
|
1731
|
+
craftbookSourceId: "project",
|
|
1732
|
+
craftbookVersion: book.version,
|
|
1733
|
+
craftbookParams: parsed,
|
|
1734
|
+
dispatchEntry: true,
|
|
1735
|
+
roleBasedNameOnlyMode: true,
|
|
1736
|
+
trustScripts: true,
|
|
1737
|
+
...options.parentTaskRef ? { parentTaskRef: options.parentTaskRef } : {}
|
|
1738
|
+
});
|
|
1739
|
+
await options.onCreated?.(task2);
|
|
1740
|
+
ref = task2.ref;
|
|
1741
|
+
}
|
|
1742
|
+
log(`Following ${ref}`);
|
|
1743
|
+
return waitForTask(client, ref, {
|
|
1744
|
+
timeoutMs: options.timeoutMs ?? invocation?.timeoutMs ?? 72e5,
|
|
1745
|
+
onProgress: (task2) => log(`${task2.ref}: ${task2.status} (${task2.activeStepId ?? "finished"})`)
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
});
|
|
1233
1749
|
}
|
|
1234
1750
|
|
|
1235
1751
|
// src/bin/gezel.ts
|
|
1236
1752
|
var program = new Command();
|
|
1237
|
-
program.name("gezel").description("Gezel \u2014
|
|
1753
|
+
program.name("gezel").description("Gezel \u2014 assemble a team of AI companions (gezels) and put them to work.").version(GEZEL_VERSION).option(
|
|
1238
1754
|
"--connect <url>",
|
|
1239
1755
|
"Connect to this Gezel service (first use asks for approval in the Gezel app)."
|
|
1240
|
-
).option("--token <token>", "Bearer token for --connect (must have CLI access).").option(
|
|
1756
|
+
).option("--token <token>", "Bearer token for --connect (must have CLI access).").option("--http1", "Use HTTP/1.1 for daemon requests, keeping TLS certificate validation.").option(
|
|
1241
1757
|
"--standalone",
|
|
1242
|
-
"
|
|
1758
|
+
"Always use your own per-user Gezel service, even if an older machine-wide install is present."
|
|
1243
1759
|
).option("--home <dir>", "Use this user-owned Gezel home (default: $GEZEL_HOME or ~/.gezel).").option(
|
|
1244
1760
|
"--project [folder]",
|
|
1245
1761
|
"Use this folder as the active project (default and bare flag: cwd)."
|
|
1246
1762
|
);
|
|
1247
1763
|
var cliGlobals = () => program.opts();
|
|
1764
|
+
registerSecretCommands(program, () => connectOwned(cliGlobals()));
|
|
1765
|
+
registerSecurityCommands(program, () => connectOwned(cliGlobals()));
|
|
1248
1766
|
program.hook("preAction", () => {
|
|
1249
1767
|
const globals = cliGlobals();
|
|
1250
1768
|
validateGlobals(globals);
|
|
1769
|
+
if (globals.http1) process.env.GEZEL_HTTP_VERSION = "1.1";
|
|
1251
1770
|
applyHome(globals);
|
|
1252
1771
|
});
|
|
1253
1772
|
program.action(async () => {
|
|
1773
|
+
if (program.args.length > 0) {
|
|
1774
|
+
const known = program.commands.flatMap((command) => [command.name(), ...command.aliases()]);
|
|
1775
|
+
throw new CliError(unknownCommandMessage(program.args, known));
|
|
1776
|
+
}
|
|
1777
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
1778
|
+
throw new CliError(
|
|
1779
|
+
[
|
|
1780
|
+
"The interactive Gezel terminal needs a terminal window, and this one is not interactive.",
|
|
1781
|
+
'For a one-shot reply, use: gezel run "<prompt>"',
|
|
1782
|
+
"Run `gezel --help` to see every command."
|
|
1783
|
+
].join("\n")
|
|
1784
|
+
);
|
|
1785
|
+
}
|
|
1254
1786
|
const globals = cliGlobals();
|
|
1255
1787
|
resolveDevHome(globals);
|
|
1256
1788
|
const connection = await connectForTui(globals);
|
|
@@ -1387,10 +1919,10 @@ async function startForeground(env2) {
|
|
|
1387
1919
|
process.on("SIGINT", requestStop);
|
|
1388
1920
|
process.on("SIGTERM", requestStop);
|
|
1389
1921
|
try {
|
|
1390
|
-
await new Promise((
|
|
1922
|
+
await new Promise((resolve6) => {
|
|
1391
1923
|
child.on("exit", (code) => {
|
|
1392
1924
|
process.exitCode = code ?? 0;
|
|
1393
|
-
|
|
1925
|
+
resolve6();
|
|
1394
1926
|
});
|
|
1395
1927
|
});
|
|
1396
1928
|
} finally {
|
|
@@ -1398,7 +1930,7 @@ async function startForeground(env2) {
|
|
|
1398
1930
|
process.off("SIGTERM", requestStop);
|
|
1399
1931
|
}
|
|
1400
1932
|
}
|
|
1401
|
-
program.command("status").description("Show daemon status").action(async () => {
|
|
1933
|
+
program.command("status").description("Show daemon status (exits 1 when gezeld is not running or not healthy)").action(async () => {
|
|
1402
1934
|
const globals = cliGlobals();
|
|
1403
1935
|
if (globals.connect) {
|
|
1404
1936
|
const client2 = await connectOwned(globals);
|
|
@@ -1434,11 +1966,16 @@ program.command("status").description("Show daemon status").action(async () => {
|
|
|
1434
1966
|
const runtime = await readRuntime2();
|
|
1435
1967
|
if (!runtime) {
|
|
1436
1968
|
console.log("gezeld is not running");
|
|
1969
|
+
process.exitCode = 1;
|
|
1437
1970
|
return;
|
|
1438
1971
|
}
|
|
1439
1972
|
const alive = isProcessAlive2(runtime.pid);
|
|
1973
|
+
if (!alive) {
|
|
1974
|
+
console.log(`gezeld is not running (stale runtime record for pid ${runtime.pid})`);
|
|
1975
|
+
process.exitCode = 1;
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1440
1978
|
console.log(`gezeld pid=${runtime.pid} port=${runtime.port} alive=${alive}`);
|
|
1441
|
-
if (!alive) return;
|
|
1442
1979
|
const client = new GezelClient2({
|
|
1443
1980
|
baseUrl: runtime.baseUrl,
|
|
1444
1981
|
// Health is intentionally unauthenticated; diagnostics do not need to
|
|
@@ -1454,17 +1991,21 @@ program.command("status").description("Show daemon status").action(async () => {
|
|
|
1454
1991
|
);
|
|
1455
1992
|
} catch (err) {
|
|
1456
1993
|
console.error(`health failed: ${err.message}`);
|
|
1994
|
+
process.exitCode = 1;
|
|
1457
1995
|
}
|
|
1458
1996
|
});
|
|
1459
|
-
program.command("stop").description(
|
|
1997
|
+
program.command("stop").description(
|
|
1998
|
+
"Hard stop all AI work and switch Gezel to Reactive mode; gezeld keeps running (use --daemon to shut it down)"
|
|
1999
|
+
).option("--daemon", "Shut down the user-owned daemon process itself").action(async (opts) => {
|
|
1460
2000
|
const globals = cliGlobals();
|
|
1461
2001
|
if (opts.daemon) {
|
|
1462
2002
|
await stopUserDaemon(globals);
|
|
1463
2003
|
return;
|
|
1464
2004
|
}
|
|
2005
|
+
let userRuntime = null;
|
|
1465
2006
|
if (!globals.connect && !await findHealthySystemService(globals)) {
|
|
1466
|
-
|
|
1467
|
-
if (!
|
|
2007
|
+
userRuntime = await readRuntime2();
|
|
2008
|
+
if (!userRuntime || !isProcessAlive2(userRuntime.pid)) {
|
|
1468
2009
|
console.log("Gezel has no running AI work to stop.");
|
|
1469
2010
|
return;
|
|
1470
2011
|
}
|
|
@@ -1479,7 +2020,32 @@ program.command("stop").description("Hard stop all AI work and switch Gezel to R
|
|
|
1479
2020
|
console.log(
|
|
1480
2021
|
`Hard stop complete: ${details.join(", ")}. Local engines unloaded; Gezel is Reactive.`
|
|
1481
2022
|
);
|
|
2023
|
+
if (userRuntime) {
|
|
2024
|
+
console.log(
|
|
2025
|
+
`gezeld is still running (pid ${userRuntime.pid}); run \`gezel stop --daemon\` to shut it down.`
|
|
2026
|
+
);
|
|
2027
|
+
}
|
|
1482
2028
|
});
|
|
2029
|
+
async function clearStaleRuntime(stoppedPid) {
|
|
2030
|
+
const { readFile: readFile3, rm: rm3 } = await import("fs/promises");
|
|
2031
|
+
const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
|
|
2032
|
+
const runtime = gezelPaths2().runtime;
|
|
2033
|
+
const recorded = Number.parseInt(
|
|
2034
|
+
(await readFile3(runtime.pid, "utf8").catch(() => "")).trim(),
|
|
2035
|
+
10
|
|
2036
|
+
);
|
|
2037
|
+
if (recorded !== stoppedPid || isProcessAlive2(stoppedPid)) return;
|
|
2038
|
+
await Promise.all(
|
|
2039
|
+
[
|
|
2040
|
+
runtime.pid,
|
|
2041
|
+
runtime.port,
|
|
2042
|
+
runtime.token,
|
|
2043
|
+
runtime.cert,
|
|
2044
|
+
runtime.fingerprint,
|
|
2045
|
+
runtime.webUiToken
|
|
2046
|
+
].map((path) => rm3(path, { force: true }))
|
|
2047
|
+
);
|
|
2048
|
+
}
|
|
1483
2049
|
async function stopUserDaemon(globals) {
|
|
1484
2050
|
if (globals.connect) {
|
|
1485
2051
|
throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
|
|
@@ -1498,6 +2064,7 @@ async function stopUserDaemon(globals) {
|
|
|
1498
2064
|
}
|
|
1499
2065
|
const stopped = await stopProcessByPid(runtime.pid);
|
|
1500
2066
|
if (stopped) {
|
|
2067
|
+
await clearStaleRuntime(runtime.pid);
|
|
1501
2068
|
console.log(`stopped gezeld pid=${runtime.pid}`);
|
|
1502
2069
|
} else {
|
|
1503
2070
|
console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
|
|
@@ -1531,6 +2098,8 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
|
|
|
1531
2098
|
}
|
|
1532
2099
|
const previousLogOutput = getLogOutput();
|
|
1533
2100
|
setLogOutput("stderr");
|
|
2101
|
+
const previousLogLevel = getLogLevel();
|
|
2102
|
+
if (!process.env.GEZEL_LOG_LEVEL && previousLogLevel === "info") setLogLevel("warn");
|
|
1534
2103
|
let conn;
|
|
1535
2104
|
let removeSignalCleanup;
|
|
1536
2105
|
try {
|
|
@@ -1545,6 +2114,12 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
|
|
|
1545
2114
|
const { client } = conn;
|
|
1546
2115
|
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1547
2116
|
const gezelId = opts.gezel ?? await ensureCliProjectLead(client, projectId);
|
|
2117
|
+
const readiness = await checkRunReadiness(client, gezelId);
|
|
2118
|
+
if (!readiness.ready) {
|
|
2119
|
+
console.error(readiness.message);
|
|
2120
|
+
process.exitCode = 1;
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
1548
2123
|
const session = await client.createChatSession({ gezelId, projectId });
|
|
1549
2124
|
await client.sendToChatSession(session.id, prompt);
|
|
1550
2125
|
let printed = false;
|
|
@@ -1576,50 +2151,159 @@ ${ev.error}`);
|
|
|
1576
2151
|
if (conn?.stop) await conn.stop();
|
|
1577
2152
|
} finally {
|
|
1578
2153
|
setLogOutput(previousLogOutput);
|
|
2154
|
+
setLogLevel(previousLogLevel);
|
|
1579
2155
|
}
|
|
1580
2156
|
}
|
|
1581
2157
|
});
|
|
1582
|
-
program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").
|
|
1583
|
-
|
|
2158
|
+
program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").option(
|
|
2159
|
+
"--param <key=value>",
|
|
2160
|
+
"named craftbook parameter (repeatable)",
|
|
2161
|
+
(value, values) => [...values, value],
|
|
2162
|
+
[]
|
|
2163
|
+
).option("--wait", "wait for completion; exit nonzero when blocked, canceled, or timed out").option("--timeout <seconds>", "wait budget in seconds; timeout leaves the task running", "7200").option("--json", "emit one JSON result on stdout").option(
|
|
2164
|
+
"--strict-sandbox",
|
|
2165
|
+
"require OS network isolation for custom scripts (CLI launches otherwise trust this recipe snapshot)"
|
|
2166
|
+
).action(
|
|
2167
|
+
async (craftbookParts, opts) => {
|
|
2168
|
+
const timeoutMs = positiveSeconds(opts.timeout);
|
|
2169
|
+
const client = await connectOwned(cliGlobals());
|
|
2170
|
+
const projectId = await resolveRunProject(client, cliGlobals());
|
|
2171
|
+
const [config, result] = await Promise.all([
|
|
2172
|
+
client.getConfig(),
|
|
2173
|
+
client.listProjectCraftbooks(projectId)
|
|
2174
|
+
]);
|
|
2175
|
+
const craftbooks = normalizeCraftbooks(
|
|
2176
|
+
result.items,
|
|
2177
|
+
config.showWorkInProgressFeatures === true
|
|
2178
|
+
);
|
|
2179
|
+
const { book, args } = resolveCraftbookInvocation(craftbooks, craftbookParts);
|
|
2180
|
+
const { craftbook } = await client.getCraftbook(book.id, {
|
|
2181
|
+
projectId,
|
|
2182
|
+
source: book.source,
|
|
2183
|
+
version: book.version
|
|
2184
|
+
});
|
|
2185
|
+
const craftbookParams = parseCraftbookParams(craftbook, [...args, ...opts.param]);
|
|
2186
|
+
if (craftbook.cliWorkflow) {
|
|
2187
|
+
if (book.source !== "project")
|
|
2188
|
+
throw new CliError("CLI workflow craftbooks must belong to this project.");
|
|
2189
|
+
if (opts.strictSandbox)
|
|
2190
|
+
throw new CliError(
|
|
2191
|
+
"CLI workflows execute ordinary repository code and cannot use --strict-sandbox."
|
|
2192
|
+
);
|
|
2193
|
+
const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
|
|
2194
|
+
console.error(`Running ${craftbook.name}: ${craftbook.cliWorkflow.module}`);
|
|
2195
|
+
const result2 = await runWorkflow(
|
|
2196
|
+
client,
|
|
2197
|
+
projectId,
|
|
2198
|
+
workspace,
|
|
2199
|
+
craftbook.cliWorkflow.module,
|
|
2200
|
+
[],
|
|
2201
|
+
console.error,
|
|
2202
|
+
{
|
|
2203
|
+
craftbook,
|
|
2204
|
+
params: craftbookParams,
|
|
2205
|
+
timeoutMs
|
|
2206
|
+
}
|
|
2207
|
+
);
|
|
2208
|
+
printWorkflowResult(result2, opts.json);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
const created = await client.createTask(projectId, {
|
|
2212
|
+
...craftbookStartRequest(book),
|
|
2213
|
+
craftbookParams,
|
|
2214
|
+
trustScripts: !opts.strictSandbox,
|
|
2215
|
+
roleBasedNameOnlyMode: true
|
|
2216
|
+
});
|
|
2217
|
+
if (opts.wait) {
|
|
2218
|
+
console.error(`started ${created.ref} \u2014 ${created.title}`);
|
|
2219
|
+
await printTaskWait(client, created.ref, { ...opts, timeoutMs });
|
|
2220
|
+
} else
|
|
2221
|
+
console.log(
|
|
2222
|
+
opts.json ? JSON.stringify(created) : `started ${created.ref} \u2014 ${created.title}`
|
|
2223
|
+
);
|
|
2224
|
+
}
|
|
2225
|
+
);
|
|
2226
|
+
function positiveSeconds(value) {
|
|
2227
|
+
const seconds = Number(value);
|
|
2228
|
+
if (!Number.isFinite(seconds) || seconds <= 0)
|
|
2229
|
+
throw new CliError("--timeout must be a positive number of seconds");
|
|
2230
|
+
return seconds * 1e3;
|
|
2231
|
+
}
|
|
2232
|
+
program.command("workflow <file> [args...]").description(
|
|
2233
|
+
"Run a trusted project workflow module (ordinary local code, with your account permissions); names resolve in .gezel/workflows/"
|
|
2234
|
+
).option("--json", "emit the workflow result as JSON").action(async (file, args, opts) => {
|
|
1584
2235
|
const client = await connectOwned(cliGlobals());
|
|
1585
2236
|
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1586
|
-
const
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
)
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
2237
|
+
const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
|
|
2238
|
+
const result = await runWorkflow(client, projectId, workspace, file, args);
|
|
2239
|
+
printWorkflowResult(result, opts.json);
|
|
2240
|
+
});
|
|
2241
|
+
function printWorkflowResult(result, json) {
|
|
2242
|
+
if (result !== void 0)
|
|
2243
|
+
console.log(json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
|
|
2244
|
+
if (result && typeof result === "object" && "exitCode" in result) {
|
|
2245
|
+
const code = Number(result.exitCode);
|
|
2246
|
+
if (Number.isInteger(code) && code >= 0 && code <= 255) process.exitCode = code;
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
async function printTaskWait(client, ref, opts) {
|
|
2250
|
+
const result = await waitForTask(client, ref, {
|
|
2251
|
+
timeoutMs: opts.timeoutMs,
|
|
2252
|
+
onProgress: (task2) => console.error(
|
|
2253
|
+
`${task2.ref}: ${task2.status}${task2.activeStepId ? ` (${task2.activeStepId})` : ""}`
|
|
2254
|
+
)
|
|
1601
2255
|
});
|
|
1602
|
-
console.log(
|
|
2256
|
+
console.log(opts.json ? JSON.stringify(result) : `${result.task.ref}: ${result.outcome}`);
|
|
2257
|
+
process.exitCode = result.exitCode;
|
|
2258
|
+
}
|
|
2259
|
+
var agent = program.command("agent").description("Manage your gezels (your AI companions)");
|
|
2260
|
+
agent.command("output-limit <id> [tokens]").description(
|
|
2261
|
+
"Show or set one gezel's output-token limit, including reasoning; auto clears its override"
|
|
2262
|
+
).option("--json", "Output the per-gezel override as JSON").action(async (id, tokens, opts) => {
|
|
2263
|
+
if (tokens !== void 0 && tokens !== "auto" && (!/^\d+$/.test(tokens) || !Number.isSafeInteger(Number(tokens)) || Number(tokens) < 1)) {
|
|
2264
|
+
throw new CliError("Output limit must be a positive integer, or auto.");
|
|
2265
|
+
}
|
|
2266
|
+
const client = await connectOwned(cliGlobals());
|
|
2267
|
+
const { parsed } = await client.getGezel(id);
|
|
2268
|
+
const tuning = { ...parsed.frontmatter.tuning };
|
|
2269
|
+
const sampling = { ...tuning.sampling };
|
|
2270
|
+
if (tokens !== void 0) {
|
|
2271
|
+
if (tokens === "auto") delete sampling.maxTokens;
|
|
2272
|
+
else sampling.maxTokens = Number(tokens);
|
|
2273
|
+
if (Object.keys(sampling).length) tuning.sampling = sampling;
|
|
2274
|
+
else delete tuning.sampling;
|
|
2275
|
+
await client.updateGezelSettings(id, { tuning: Object.keys(tuning).length ? tuning : null });
|
|
2276
|
+
}
|
|
2277
|
+
const result = { gezelId: id, outputTokens: sampling.maxTokens ?? null };
|
|
2278
|
+
console.log(
|
|
2279
|
+
opts.json ? JSON.stringify(result) : `${id}: ${result.outputTokens === null ? "auto (inherits model/profile defaults)" : `${result.outputTokens} output tokens, including reasoning`}`
|
|
2280
|
+
);
|
|
1603
2281
|
});
|
|
1604
|
-
|
|
1605
|
-
agent.command("list").description("List agents").action(async () => {
|
|
2282
|
+
agent.command("list").description("List your gezels").action(async () => {
|
|
1606
2283
|
const client = await connectOwned(cliGlobals());
|
|
1607
2284
|
const res = await client.listGezels();
|
|
1608
2285
|
for (const a of res.gezels) {
|
|
1609
2286
|
console.log(`${a.id.padEnd(20)} ${a.name}`);
|
|
1610
2287
|
}
|
|
1611
2288
|
});
|
|
1612
|
-
agent.command("create <name>").description("Create a new
|
|
2289
|
+
agent.command("create <name>").description("Create a new gezel").option("-d, --description <text>", "description").option("-m, --model <model>", "model identifier").action(async (name, opts) => {
|
|
1613
2290
|
const client = await connectOwned(cliGlobals());
|
|
1614
2291
|
const created = await client.createGezel({ name, ...opts });
|
|
1615
|
-
console.log(`created
|
|
2292
|
+
console.log(`created gezel ${created.id}`);
|
|
1616
2293
|
});
|
|
1617
|
-
agent.command("show <id>").description("Show
|
|
2294
|
+
agent.command("show <id>").description("Show one gezel").action(async (id) => {
|
|
1618
2295
|
const client = await connectOwned(cliGlobals());
|
|
1619
|
-
const a = await client.getGezel(id)
|
|
2296
|
+
const a = await client.getGezel(id).catch((err) => {
|
|
2297
|
+
throw isNotFound(err) ? new CliError(`No gezel with id "${id}". Run \`gezel agent list\` to see your gezels.`) : err;
|
|
2298
|
+
});
|
|
1620
2299
|
console.log(a.parsed.source);
|
|
1621
2300
|
});
|
|
1622
|
-
var env = program.command("env").description("Manage projects");
|
|
2301
|
+
var env = program.command("env").alias("project").description("Manage projects (also available as `gezel project`)");
|
|
2302
|
+
registerProjectSettingsCommands(
|
|
2303
|
+
env,
|
|
2304
|
+
() => connectOwned(cliGlobals()),
|
|
2305
|
+
(client) => resolveRunProject(client, cliGlobals())
|
|
2306
|
+
);
|
|
1623
2307
|
env.command("list").description("List projects").action(async () => {
|
|
1624
2308
|
const client = await connectOwned(cliGlobals());
|
|
1625
2309
|
const res = await client.listProjects();
|
|
@@ -1704,13 +2388,13 @@ skills.command("import <source>").description("Convert a discovered skill (by it
|
|
|
1704
2388
|
skills.command("convert <path>").description("Convert a SKILL.md file to a craftbook document on stdout (no daemon)").option("--md", "emit the markdown encoding instead of JSON").option("--released-at <iso>", "stamp releasedAt (catalog authoring)").action(async (path, opts) => {
|
|
1705
2389
|
const { readFile: readFsFile } = await import("fs/promises");
|
|
1706
2390
|
const { basename: base, dirname: dir } = await import("path");
|
|
1707
|
-
const { parseSkillDoc, skillToCraftbookDoc, serializeCraftbookDoc, craftbookFromDoc } = await import("@bendyline/gezel");
|
|
2391
|
+
const { parseSkillDoc, skillToCraftbookDoc, serializeCraftbookDoc, craftbookFromDoc: craftbookFromDoc2 } = await import("@bendyline/gezel");
|
|
1708
2392
|
const raw = await readFsFile(path, "utf8");
|
|
1709
2393
|
const skill = parseSkillDoc(raw, { fallbackName: base(dir(path)) });
|
|
1710
2394
|
const result = skillToCraftbookDoc(skill, {
|
|
1711
2395
|
...opts.releasedAt ? { releasedAt: opts.releasedAt } : {}
|
|
1712
2396
|
});
|
|
1713
|
-
const check =
|
|
2397
|
+
const check = craftbookFromDoc2(result.doc, { now: "1970-01-01T00:00:00.000Z" });
|
|
1714
2398
|
if (!check.ok) {
|
|
1715
2399
|
console.error("conversion produced an invalid craftbook:");
|
|
1716
2400
|
for (const e of check.errors) console.error(` ${e.where}: ${e.message}`);
|
|
@@ -1826,7 +2510,7 @@ knowledge.command("install <source>").description("Install a .gezk catalog into
|
|
|
1826
2510
|
try {
|
|
1827
2511
|
started = await client.installKnowledgeCatalog({ source: installSource });
|
|
1828
2512
|
} catch (err) {
|
|
1829
|
-
if (err instanceof
|
|
2513
|
+
if (err instanceof GezelApiError3 && err.status === 403) {
|
|
1830
2514
|
throw new CliError(
|
|
1831
2515
|
"Downloading knowledge catalogs needs app network access, which the security policy turns off (Settings \u2192 Security)."
|
|
1832
2516
|
);
|
|
@@ -1991,6 +2675,40 @@ appCmd.command("schemas").description("The JSON Schemas an AI App author codes a
|
|
|
1991
2675
|
await runAppSchemas(opts);
|
|
1992
2676
|
});
|
|
1993
2677
|
var task = program.command("task").description("Manage tasks");
|
|
2678
|
+
task.command("pause <ref>").description("Pause one active task without stopping other tasks or the daemon").option("--json", "emit the task reference and status as JSON").action(async (ref, opts) => {
|
|
2679
|
+
const client = await connectOwned(cliGlobals());
|
|
2680
|
+
let current = await client.getTaskByRef(ref);
|
|
2681
|
+
if (current.status !== "active" && current.status !== "paused") {
|
|
2682
|
+
throw new CliError(
|
|
2683
|
+
`task ${ref} is ${current.status}; pause requires an active or paused task`
|
|
2684
|
+
);
|
|
2685
|
+
}
|
|
2686
|
+
if (current.status === "active") {
|
|
2687
|
+
current = await client.setTaskStatus(current.projectId, current.num, "paused");
|
|
2688
|
+
}
|
|
2689
|
+
console.log(
|
|
2690
|
+
opts.json ? JSON.stringify({ taskRef: current.ref, status: current.status }) : `paused ${current.ref}`
|
|
2691
|
+
);
|
|
2692
|
+
});
|
|
2693
|
+
for (const verb of ["wait", "resume"]) {
|
|
2694
|
+
task.command(`${verb} <ref>`).description(
|
|
2695
|
+
verb === "wait" ? "Wait for a task to finish or need attention" : "Retry a paused task and wait for its result"
|
|
2696
|
+
).option(
|
|
2697
|
+
"--timeout <seconds>",
|
|
2698
|
+
"wait budget in seconds; timeout leaves the task running",
|
|
2699
|
+
"7200"
|
|
2700
|
+
).option("--json", "emit one JSON result on stdout").action(async (ref, opts) => {
|
|
2701
|
+
const timeoutMs = positiveSeconds(opts.timeout);
|
|
2702
|
+
const client = await connectOwned(cliGlobals());
|
|
2703
|
+
if (verb === "resume") {
|
|
2704
|
+
const current = await client.getTaskByRef(ref);
|
|
2705
|
+
if (current.status !== "paused")
|
|
2706
|
+
throw new CliError(`task ${ref} is ${current.status}; resume requires a paused task`);
|
|
2707
|
+
await client.retryTask(current.projectId, current.num);
|
|
2708
|
+
}
|
|
2709
|
+
await printTaskWait(client, ref, { ...opts, timeoutMs });
|
|
2710
|
+
});
|
|
2711
|
+
}
|
|
1994
2712
|
task.command("list").description("List tasks across every project").option("-s, --status <status>", "filter by status (paused|active|complete|canceled)").action(async (opts) => {
|
|
1995
2713
|
const client = await connectOwned(cliGlobals());
|
|
1996
2714
|
const res = await client.listTasks(
|
|
@@ -2019,9 +2737,37 @@ task.command("create <projectId> <title>").description("Create a task with a sin
|
|
|
2019
2737
|
);
|
|
2020
2738
|
task.command("show <ref>").description("Show one task (format: projectId/num)").action(async (ref) => {
|
|
2021
2739
|
const client = await connectOwned(cliGlobals());
|
|
2022
|
-
const t = await client.getTaskByRef(ref)
|
|
2740
|
+
const t = await client.getTaskByRef(ref).catch((err) => {
|
|
2741
|
+
throw isNotFound(err) ? new CliError(`No task "${ref}". Run \`gezel task list\` to see task references.`) : err;
|
|
2742
|
+
});
|
|
2023
2743
|
console.log(JSON.stringify(t, null, 2));
|
|
2024
2744
|
});
|
|
2745
|
+
task.command("notes <ref>").description("Read task notes, including pause reasons and failed checks").option("--warnings", "Also include model/runtime warnings from the latest 20 task sessions").option("--json", "Output the notes as JSON").action(async (ref, opts) => {
|
|
2746
|
+
const client = await connectOwned(cliGlobals());
|
|
2747
|
+
const current = await client.getTaskByRef(ref);
|
|
2748
|
+
const result = await client.listTaskNotes(current.projectId, current.num);
|
|
2749
|
+
const warnings = [];
|
|
2750
|
+
if (opts.warnings) {
|
|
2751
|
+
const { sessions } = await client.listTaskSessions(current.projectId, current.num);
|
|
2752
|
+
for (const session of sessions.slice(0, 20)) {
|
|
2753
|
+
const full = await client.getChatSession(session.id);
|
|
2754
|
+
for (const message of full.messages) {
|
|
2755
|
+
for (const text of message.warnings ?? [])
|
|
2756
|
+
warnings.push({ sessionId: session.id, at: message.at, text });
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
console.log(
|
|
2761
|
+
opts.json ? JSON.stringify({ ...result, ...opts.warnings ? { warnings } : {} }) : [
|
|
2762
|
+
...result.notes.map(
|
|
2763
|
+
(note) => `${note.at}${note.stepId ? ` [${note.stepId}]` : ""}
|
|
2764
|
+
${note.text}`
|
|
2765
|
+
),
|
|
2766
|
+
...warnings.map((warning) => `${warning.at} [runtime warning]
|
|
2767
|
+
${warning.text}`)
|
|
2768
|
+
].join("\n\n") || "(no task notes)"
|
|
2769
|
+
);
|
|
2770
|
+
});
|
|
2025
2771
|
program.command("create-image [prompt...]").description("Generate an image from a prompt (or --file) via the configured image engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "image model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("-s, --steps <n>", "sampler steps (default: the model recommendation)").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the image here (default: ./<artifact name>)").action(
|
|
2026
2772
|
async (promptParts, opts) => {
|
|
2027
2773
|
const prompt = await resolvePromptText(promptParts, opts.file, "prompt");
|
|
@@ -2126,15 +2872,21 @@ program.command("create-audio [text...]").description("Synthesize speech from te
|
|
|
2126
2872
|
);
|
|
2127
2873
|
});
|
|
2128
2874
|
var native = program.command("native").description("Manage native engine binaries");
|
|
2129
|
-
native.command("install").description(
|
|
2875
|
+
native.command("install").description(
|
|
2876
|
+
"Download, verify, and activate the native inference toolkit (or one engine with --engine)"
|
|
2877
|
+
).option("--variant <backend>", "llama.cpp backend: cuda | vulkan | metal | cpu").option("--engine <name>", "install only this engine, e.g. duckdb or llama-server").action(async (opts) => {
|
|
2130
2878
|
const variant = parseNativeVariant(opts.variant);
|
|
2879
|
+
const engine = parseNativeEngine(opts.engine);
|
|
2131
2880
|
const client = await connectOwned(cliGlobals());
|
|
2132
2881
|
const installed = await installNativeToolkit(client, {
|
|
2133
2882
|
...variant ? { variant } : {},
|
|
2883
|
+
...engine ? { engines: [engine] } : {},
|
|
2134
2884
|
output: { writeProgress: (text) => process.stderr.write(text) }
|
|
2135
2885
|
});
|
|
2136
|
-
console.log(
|
|
2137
|
-
|
|
2886
|
+
console.log(
|
|
2887
|
+
`${engine ? `${engine} ready` : "native toolkit ready"}
|
|
2888
|
+
${formatNativeStatus(installed)}`
|
|
2889
|
+
);
|
|
2138
2890
|
});
|
|
2139
2891
|
native.command("list").description("List native executables and their install state").action(async () => {
|
|
2140
2892
|
const client = await connectOwned(cliGlobals());
|
|
@@ -2208,8 +2960,46 @@ function resolveModelProvider(raw) {
|
|
|
2208
2960
|
}
|
|
2209
2961
|
return raw;
|
|
2210
2962
|
}
|
|
2211
|
-
return process.platform
|
|
2963
|
+
return resolveOnDeviceProvider(process.platform, process.arch);
|
|
2212
2964
|
}
|
|
2965
|
+
model.command("concurrency [slots]").description("Show or set local inference slots; use auto to restore automatic sizing").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").option("--json", "Output the slot override as JSON").action(async (slots, opts) => {
|
|
2966
|
+
const provider = resolveModelProvider(opts.provider);
|
|
2967
|
+
if (slots !== void 0 && slots !== "auto" && (!/^\d+$/.test(slots) || !Number.isSafeInteger(Number(slots)) || Number(slots) < 1)) {
|
|
2968
|
+
throw new CliError("Concurrency must be a positive integer, or auto.");
|
|
2969
|
+
}
|
|
2970
|
+
const client = await connectOwned(cliGlobals());
|
|
2971
|
+
const config = await client.getConfig();
|
|
2972
|
+
const concurrency = { ...config.providerConcurrency };
|
|
2973
|
+
if (slots !== void 0) {
|
|
2974
|
+
if (slots === "auto") delete concurrency[provider];
|
|
2975
|
+
else concurrency[provider] = Number(slots);
|
|
2976
|
+
await client.updateConfig({ providerConcurrency: concurrency });
|
|
2977
|
+
}
|
|
2978
|
+
const result = { provider, slots: concurrency[provider] ?? null };
|
|
2979
|
+
console.log(
|
|
2980
|
+
opts.json ? JSON.stringify(result) : `${provider}: ${result.slots ?? "auto"}${result.slots === null ? "" : " inference slots"}${slots === void 0 ? "" : " (applies when idle sessions reload)"}`
|
|
2981
|
+
);
|
|
2982
|
+
});
|
|
2983
|
+
model.command("context <id> [tokens]").description("Show or set a model context window in tokens; use auto to clear an override").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").option("--json", "Output the context override as JSON").action(
|
|
2984
|
+
async (id, tokens, opts) => {
|
|
2985
|
+
const provider = resolveModelProvider(opts.provider);
|
|
2986
|
+
let contextTokens;
|
|
2987
|
+
if (tokens !== void 0) {
|
|
2988
|
+
contextTokens = tokens === "auto" ? null : Number(tokens);
|
|
2989
|
+
if (contextTokens !== null && (!/^\d+$/.test(tokens) || !Number.isInteger(contextTokens) || contextTokens < 32768 || contextTokens > 4194304)) {
|
|
2990
|
+
throw new CliError("Context must be an integer from 32768 to 4194304 tokens, or auto.");
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
const client = await connectOwned(cliGlobals());
|
|
2994
|
+
const result = contextTokens === void 0 ? {
|
|
2995
|
+
modelId: id,
|
|
2996
|
+
contextTokens: (await client.getModelContextOverrides(provider)).overrides[id] ?? null
|
|
2997
|
+
} : await client.updateModelContextOverride(provider, id, contextTokens);
|
|
2998
|
+
console.log(
|
|
2999
|
+
opts.json ? JSON.stringify({ provider, ...result }) : `${provider}/${id}: ${result.contextTokens ?? "auto"}${result.contextTokens === null ? "" : " tokens"}${tokens === void 0 ? "" : " (applies on the next model launch)"}`
|
|
3000
|
+
);
|
|
3001
|
+
}
|
|
3002
|
+
);
|
|
2213
3003
|
model.command("list").description("List local chat models for an engine").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").action(async (opts) => {
|
|
2214
3004
|
const client = await connectOwned(cliGlobals());
|
|
2215
3005
|
const provider = resolveModelProvider(opts.provider);
|
|
@@ -2387,7 +3177,10 @@ Wrote ${outPath}`);
|
|
|
2387
3177
|
program.command("restore <file>").description("Restore gezels, projects, and documents from a backup file").option("--list", "Show what the backup holds without restoring anything").option(
|
|
2388
3178
|
"--only <item...>",
|
|
2389
3179
|
"Restore just these items, by id (repeatable, e.g. --only tamsin roof-survey)"
|
|
2390
|
-
).option("--replace", "Overwrite items that already exist here").option(
|
|
3180
|
+
).option("--replace", "Overwrite items that already exist here").option(
|
|
3181
|
+
"--settings",
|
|
3182
|
+
"Also restore which gezels hold roles such as the meester (never providers, folders or security)"
|
|
3183
|
+
).action(
|
|
2391
3184
|
async (file, opts) => {
|
|
2392
3185
|
const client = await connectOwned(cliGlobals());
|
|
2393
3186
|
const review = await client.scanRestore({ path: resolvePath(file) });
|
|
@@ -2447,9 +3240,11 @@ async function pollStorageJob(client, jobId) {
|
|
|
2447
3240
|
await new Promise((r) => setTimeout(r, 250));
|
|
2448
3241
|
}
|
|
2449
3242
|
}
|
|
3243
|
+
program.allowExcessArguments();
|
|
2450
3244
|
program.parseAsync(process.argv).catch((err) => {
|
|
2451
|
-
|
|
2452
|
-
|
|
3245
|
+
const friendly = formatCliFailure(err);
|
|
3246
|
+
if (friendly !== null) {
|
|
3247
|
+
console.error(friendly);
|
|
2453
3248
|
} else {
|
|
2454
3249
|
console.error(err);
|
|
2455
3250
|
}
|