wildcrane 0.11.35 → 0.11.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/kanban.mjs +986 -832
  3. package/package.json +1 -1
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.35 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.36 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
3
3
  // Do not edit: every change belongs in cli/src/, and a build overwrites this file.
4
4
  import { createRequire as __ai4kanbanRequire } from 'node:module'
5
5
  const require = __ai4kanbanRequire(import.meta.url)
@@ -727,167 +727,603 @@ var init_paths = __esm({
727
727
  }
728
728
  });
729
729
 
730
- // src/lib/cloud/avatar.ts
731
- async function heldAvatar(url) {
732
- if (!url) return null;
733
- const held4 = readSession();
734
- if (!held4) return null;
735
- if (held4.avatar?.url === url) return held4.avatar.data;
736
- const data = await download(url);
737
- if (!data) return null;
738
- const now = readSession();
739
- if (now) writeSession({ ...now, avatar: { url, data } });
740
- return data;
741
- }
742
- async function download(url) {
743
- try {
744
- const response = await fetch(sized(url), { signal: AbortSignal.timeout(TIMEOUT_MS) });
745
- if (!response.ok) return null;
746
- const type = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
747
- if (!type.startsWith("image/")) return null;
748
- const bytes2 = Buffer.from(await response.arrayBuffer());
749
- if (bytes2.byteLength === 0 || bytes2.byteLength > MAX_BYTES) return null;
750
- return `data:${type};base64,${bytes2.toString("base64")}`;
751
- } catch {
752
- return null;
753
- }
754
- }
755
- function sized(url) {
756
- try {
757
- const asked = new URL(url);
758
- asked.searchParams.set("s", String(PIXELS));
759
- return asked.toString();
760
- } catch {
761
- return url;
730
+ // src/lib/yaml.ts
731
+ function yamlScalar(s) {
732
+ const text4 = String(s);
733
+ if (text4 === "") return '""';
734
+ if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text4) || /:\s/.test(text4) || /[\n"]/.test(text4) || /^\s|\s$/.test(text4)) {
735
+ return JSON.stringify(text4);
762
736
  }
737
+ return text4;
763
738
  }
764
- var PIXELS, MAX_BYTES, TIMEOUT_MS;
765
- var init_avatar = __esm({
766
- "src/lib/cloud/avatar.ts"() {
767
- "use strict";
768
- init_session();
769
- PIXELS = 80;
770
- MAX_BYTES = 256 * 1024;
771
- TIMEOUT_MS = 5e3;
739
+ function unquote(v) {
740
+ const text4 = String(v).trim();
741
+ if (text4.startsWith('"') && text4.endsWith('"')) {
742
+ try {
743
+ return JSON.parse(text4);
744
+ } catch {
745
+ return text4.slice(1, -1);
746
+ }
772
747
  }
773
- });
774
-
775
- // src/lib/cloud/pro.ts
776
- import fs5 from "node:fs";
777
- import path6 from "node:path";
778
- function forgetPro() {
779
- fs5.rmSync(heldFile(), { force: true });
748
+ if (text4.startsWith("'") && text4.endsWith("'")) return text4.slice(1, -1);
749
+ return text4;
780
750
  }
781
- var FRESH_MS, GRACE_MS, heldFile;
782
- var init_pro = __esm({
783
- "src/lib/cloud/pro.ts"() {
751
+ var init_yaml = __esm({
752
+ "src/lib/yaml.ts"() {
784
753
  "use strict";
785
- init_home();
786
- init_config();
787
- init_session();
788
- FRESH_MS = 10 * 6e4;
789
- GRACE_MS = 7 * 24 * 60 * 6e4;
790
- heldFile = () => path6.join(machineHome(), "pro.json");
791
754
  }
792
755
  });
793
756
 
794
- // src/lib/cloud/account.ts
795
- async function readCloudAccount() {
796
- const blank = {
797
- state: "signed-out",
798
- handle: null,
799
- name: null,
800
- avatarUrl: null,
801
- avatarData: null,
802
- email: null,
803
- message: null,
804
- inviteRequestedAt: null,
805
- sessionFile: sessionFile(),
806
- configured: cloudConfigured()
807
- };
808
- if (!blank.configured) return { ...blank, message: NOT_CONFIGURED };
809
- const token2 = await accessToken();
810
- if (!token2.ok) {
811
- if (token2.reason === "signed-out") return blank;
812
- if (token2.reason === "unreachable") {
813
- return { ...blank, ...held(), state: "signed-in", error: token2.error };
814
- }
815
- return { ...blank, ...held(), state: "expired" };
816
- }
817
- let response;
818
- try {
819
- response = await fetch(`${cloudEndpoints().api}/v1/session`, {
820
- headers: { authorization: `Bearer ${token2.token}` }
821
- });
822
- } catch (e) {
823
- return {
824
- ...blank,
825
- ...held(),
826
- state: "signed-in",
827
- error: e instanceof Error ? e.message : String(e)
757
+ // src/lib/question-block.ts
758
+ function normalizeQuestion(raw) {
759
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
760
+ const source = raw;
761
+ const text4 = withoutTag(String(source.question ?? source.text ?? ""));
762
+ const extra = {
763
+ ...typeof source.agent === "string" && source.agent.trim() ? { agent: source.agent.trim() } : {}
828
764
  };
765
+ const options = (Array.isArray(source.options) ? source.options : []).map((o) => String(o).trim()).filter(Boolean);
766
+ if (options.length === 0) return { text: text4, ...extra };
767
+ const mode = MODES.includes(String(source.mode)) ? String(source.mode) : "single";
768
+ const recommend = (Array.isArray(source.recommend) ? source.recommend : []).map(Number).filter((n) => Number.isInteger(n) && n >= 1 && n <= options.length);
769
+ return { text: text4, mode, options, recommend: mode === "single" ? recommend.slice(0, 1) : recommend, ...extra };
829
770
  }
830
- const body = await response.json().catch(() => ({}));
831
- if (!response.ok) {
832
- const refusal2 = body.error;
833
- if (refusal2?.code === "unauthenticated") {
834
- return { ...blank, ...held(), state: "expired", message: refusal2.message ?? null };
771
+ return { text: withoutTag(String(raw)) };
772
+ }
773
+ function parseQuestionsBlock(lines) {
774
+ const out = [];
775
+ for (let i = 0; i < lines.length; i++) {
776
+ const m = lines[i].match(/^\s*-\s+([\s\S]*)$/);
777
+ if (!m) continue;
778
+ const head2 = m[1];
779
+ const opened = head2.match(/^question:\s*(.*)$/);
780
+ if (!opened) {
781
+ out.push(normalizeQuestion(unquote(head2)));
782
+ continue;
835
783
  }
836
- if (refusal2?.code === "not_admitted") {
837
- return { ...blank, ...held(), state: "not-admitted", message: refusal2.message ?? null };
784
+ let skipped = false;
785
+ const q = {
786
+ question: unquote(opened[1]),
787
+ options: [],
788
+ recommend: []
789
+ };
790
+ while (i + 1 < lines.length && !/^\s*-\s/.test(lines[i + 1])) {
791
+ const field2 = lines[i + 1].match(/^\s*([A-Za-z_]+):\s*(.*)$/);
792
+ i++;
793
+ if (!field2) continue;
794
+ const [, key, val] = field2;
795
+ if (key === "options") {
796
+ while (i + 1 < lines.length && /^\s*-\s+/.test(lines[i + 1])) {
797
+ q.options.push(unquote(lines[i + 1].replace(/^\s*-\s+/, "")));
798
+ i++;
799
+ }
800
+ } else if (key === "recommend") {
801
+ q.recommend = val.replace(/^\[|\]$/g, "").split(",").map((s) => Number(s.trim())).filter((n) => Number.isInteger(n));
802
+ } else if (key === "mode") {
803
+ q.mode = unquote(val);
804
+ } else if (key === "agent") {
805
+ q.agent = unquote(val);
806
+ } else if (key === "skipped") {
807
+ skipped = unquote(val) === "true";
808
+ }
838
809
  }
839
- return { ...blank, ...held(), state: "signed-in", error: refusal2?.message };
810
+ if (!skipped) out.push(normalizeQuestion(q));
840
811
  }
841
- const session = body.session ?? {};
842
- const avatarUrl = session.avatar_url ?? session.avatarUrl ?? null;
843
- const attested = {
844
- handle: session.handle ?? null,
845
- name: session.name ?? null,
846
- avatarUrl,
847
- // Costs a fetch the first time this address is seen and a file read every time after,
848
- // so the picture is on the machine before any screen asks to draw it.
849
- avatarData: await heldAvatar(avatarUrl),
850
- email: session.email ?? null,
851
- inviteRequestedAt: session.inviteRequestedAt ?? null
852
- };
853
- return session.admitted ? { ...blank, ...attested, state: "signed-in" } : { ...blank, ...attested, state: "not-admitted", message: body.refusal?.message ?? null };
812
+ return out;
854
813
  }
855
- function signOutOfCloud() {
856
- clearSession();
857
- forgetPro();
858
- return { ok: true };
814
+ var MODES, withoutTag;
815
+ var init_question_block = __esm({
816
+ "src/lib/question-block.ts"() {
817
+ "use strict";
818
+ init_yaml();
819
+ MODES = ["single", "multi"];
820
+ withoutTag = (text4) => text4.replace(/^\[user\]\s+/, "");
821
+ }
822
+ });
823
+
824
+ // src/lib/view/rules.ts
825
+ function creationRefusal(id, creation, what, discard = false) {
826
+ if (!creation || creation.state === "unfinished" && discard) return null;
827
+ const run2 = creation.runId.slice(0, 8);
828
+ return creation.state === "creating" ? `#${id} is still being created by run ${run2} \u2014 \`${what}\` is refused until that run finishes.` : `#${id} was never finished being created: run ${run2} stopped short. \`${what}\` is refused until that run is picked back up from the board and finishes. Use reject --discard to discard it instead.`;
859
829
  }
860
- function held() {
861
- const session = readSession();
862
- return {
863
- handle: session?.handle ?? null,
864
- name: session?.name ?? null,
865
- avatarUrl: session?.avatarUrl ?? null,
866
- avatarData: session?.avatar?.data ?? null,
867
- email: session?.email ?? null
868
- };
830
+ function hasOptions(q) {
831
+ return Array.isArray(q.options) && q.options.length > 0;
869
832
  }
870
- var init_account = __esm({
871
- "src/lib/cloud/account.ts"() {
833
+ function planDeliveryGap(card) {
834
+ if (card.questions.length > 0) return "questions";
835
+ if (!planDeliverables(card.body).length) return "deliverable";
836
+ if (!/^[ \t]*[-*]\s+\[[xX]\].*`[^`]+`/m.test(card.body)) return "command";
837
+ const { total, done: done2 } = card.todos;
838
+ return total > 0 && done2 === total ? null : "todos";
839
+ }
840
+ function awaitingApproval(card) {
841
+ const { stages, stage } = card;
842
+ if (!stages || !stage || stage >= stages || card.status !== "ready") return null;
843
+ return card.questions.length ? null : stage;
844
+ }
845
+ function byDispatchOrder(a, b) {
846
+ return rank(LEVEL_RANK, a.priority) - rank(LEVEL_RANK, b.priority) || a.id - b.id;
847
+ }
848
+ function canRefine(card) {
849
+ if (card.isGroup) return false;
850
+ if (awaitingApproval(card)) return false;
851
+ if (card.status !== "todo" && !planUnfinished(card)) return false;
852
+ const { total, done: done2 } = card.todos;
853
+ if (total > 0 && done2 === total && !planUnfinished(card)) return false;
854
+ if (card.questions.length > 0 && card.questions.every(hasOptions)) return false;
855
+ return true;
856
+ }
857
+ var PLAN_DELIVERABLE, PAGES_STORYBOARD, planDeliverables, planUnfinished, LEVEL_RANK, rank;
858
+ var init_rules = __esm({
859
+ "src/lib/view/rules.ts"() {
872
860
  "use strict";
873
- init_avatar();
874
- init_config();
875
- init_pro();
876
- init_session();
861
+ PLAN_DELIVERABLE = /\.(mp4|webm|mov|m4v|pptx|md|mdx)$/i;
862
+ PAGES_STORYBOARD = /(^|\/)pages-[^/]*\.json$/i;
863
+ planDeliverables = (body) => [
864
+ ...[...body.matchAll(/<Asset\s[^>]*src="([^"]+)"/gi)].map((m) => m[1]).filter((src) => PLAN_DELIVERABLE.test(src)),
865
+ ...[...body.matchAll(/<Storyboard\s[^>]*src="([^"]+)"/gi)].map((m) => m[1]).filter((src) => PAGES_STORYBOARD.test(src))
866
+ ];
867
+ planUnfinished = (card) => card.deliversIn === "plan" && planDeliveryGap(card) !== null;
868
+ LEVEL_RANK = { high: 0, med: 1, low: 2 };
869
+ rank = (table, value) => table[value] ?? Object.keys(table).length;
877
870
  }
878
871
  });
879
872
 
880
- // src/commands/cloud.ts
881
- import fs6 from "node:fs";
882
- import path7 from "node:path";
883
- async function cmdCloud(args, program2) {
884
- const [sub] = args;
885
- if (sub === "sign-out") {
886
- signOutOfCloud();
887
- say("Signed out. This machine no longer reaches Cloud; nothing on any board changed.");
888
- return { signedOut: true };
889
- }
890
- if (sub !== void 0) {
873
+ // src/lib/frontmatter.ts
874
+ function serializeFrontmatter(m) {
875
+ const out = ["---"];
876
+ out.push(`title: ${yamlScalar(m.title)}`);
877
+ out.push(`priority: ${m.priority}`);
878
+ out.push(`status: ${STATUSES.includes(String(m.status)) ? m.status : "todo"}`);
879
+ out.push(`blocked_by: [${(m.blocked_by || []).join(", ")}]`);
880
+ out.push(`related: [${(m.related || []).join(", ")}]`);
881
+ out.push(`modules: [${(m.modules || []).join(", ")}]`);
882
+ if (m.workflow) out.push(`workflow: ${yamlScalar(m.workflow)}`);
883
+ if (m.triage) out.push(`triage: ${yamlScalar(m.triage)}`);
884
+ if (m.source?.length) {
885
+ out.push("source:");
886
+ for (const ref of m.source) out.push(` - ${yamlScalar(ref)}`);
887
+ }
888
+ if (m.previews) out.push(`previews: [${m.previews.join(", ")}]`);
889
+ if ((m.stages ?? 0) > 0) out.push(`stages: ${m.stages}`);
890
+ if ((m.phase ?? 0) > 1) out.push(`phase: ${m.phase}`);
891
+ if (m.preview_approved) out.push("preview_approved: true");
892
+ if (m.archived) out.push(`archived: ${yamlScalar(m.archived)}`);
893
+ if (m.rejected) out.push("rejected: true");
894
+ if (m.rejected_reason) out.push(`rejected_reason: ${yamlScalar(m.rejected_reason)}`);
895
+ if (m.rejected_at) out.push(`rejected_at: ${yamlScalar(m.rejected_at)}`);
896
+ if (m.rejected_by) out.push(`rejected_by: ${m.rejected_by}`);
897
+ if (!m.questions || m.questions.length === 0) out.push("questions: []");
898
+ else {
899
+ out.push("questions:");
900
+ for (const raw of m.questions) {
901
+ const q = normalizeQuestion(raw);
902
+ if (!hasOptions(q) && !q.agent) {
903
+ out.push(` - ${yamlScalar(q.text)}`);
904
+ continue;
905
+ }
906
+ out.push(` - question: ${yamlScalar(q.text)}`);
907
+ if (hasOptions(q)) {
908
+ out.push(` mode: ${q.mode}`);
909
+ out.push(" options:");
910
+ for (const o of q.options) out.push(` - ${yamlScalar(o)}`);
911
+ out.push(` recommend: [${q.recommend.join(", ")}]`);
912
+ }
913
+ if (q.agent) out.push(` agent: ${yamlScalar(q.agent)}`);
914
+ }
915
+ }
916
+ out.push("---");
917
+ return out.join("\n");
918
+ }
919
+ function parseFrontmatter(text4) {
920
+ const lines = text4.split("\n");
921
+ if (lines[0].trim() !== "---") return { meta: null, body: text4 };
922
+ let i = 1;
923
+ const fm = [];
924
+ while (i < lines.length && lines[i].trim() !== "---") {
925
+ fm.push(lines[i]);
926
+ i++;
927
+ }
928
+ if (i >= lines.length) return { meta: null, body: text4 };
929
+ const meta = {};
930
+ for (let j = 0; j < fm.length; j++) {
931
+ const m = fm[j].match(/^([A-Za-z_]+):\s*(.*)$/);
932
+ if (!m) continue;
933
+ const key = m[1];
934
+ const val = m[2];
935
+ if (key === "questions") {
936
+ if (val === "") {
937
+ const block = [];
938
+ while (j + 1 < fm.length && /^\s/.test(fm[j + 1]) && fm[j + 1].trim() !== "") {
939
+ block.push(fm[j + 1]);
940
+ j++;
941
+ }
942
+ meta.questions = parseQuestionsBlock(block);
943
+ } else {
944
+ meta.questions = val.trim() === "[]" ? [] : [normalizeQuestion(unquote(val))];
945
+ }
946
+ continue;
947
+ }
948
+ if (val === "") {
949
+ const items = [];
950
+ while (j + 1 < fm.length && /^\s*-\s+/.test(fm[j + 1])) {
951
+ items.push(unquote(fm[j + 1].replace(/^\s*-\s+/, "")));
952
+ j++;
953
+ }
954
+ meta[key] = items;
955
+ } else if (val.startsWith("[")) {
956
+ const inner = val.slice(1, val.lastIndexOf("]"));
957
+ meta[key] = inner.split(",").map((s) => s.trim()).filter(Boolean).map(unquote);
958
+ } else {
959
+ meta[key] = unquote(val);
960
+ }
961
+ }
962
+ for (const k of ["blocked_by", "related"]) {
963
+ const value = meta[k];
964
+ if (Array.isArray(value)) {
965
+ meta[k] = value.map((x) => Number(String(x).replace(/^#/, ""))).filter((n) => Number.isInteger(n));
966
+ } else {
967
+ meta[k] = [];
968
+ }
969
+ }
970
+ if (!Array.isArray(meta.questions)) {
971
+ meta.questions = meta.questions ? [normalizeQuestion(meta.questions)] : [];
972
+ }
973
+ meta.priority = typeof meta.priority === "string" ? meta.priority.trim() : "";
974
+ if (!Array.isArray(meta.modules)) meta.modules = [];
975
+ delete meta.channels;
976
+ delete meta.decided;
977
+ delete meta.verify;
978
+ delete meta.release;
979
+ delete meta.schedule;
980
+ delete meta.roi;
981
+ meta.workflow = typeof meta.workflow === "string" && meta.workflow.trim() ? meta.workflow.trim() : "";
982
+ meta.triage = typeof meta.triage === "string" ? meta.triage.trim() : "";
983
+ meta.source = (Array.isArray(meta.source) ? meta.source : typeof meta.source === "string" ? [meta.source] : []).map((ref) => String(ref).trim()).filter(Boolean);
984
+ delete meta.phases;
985
+ if (Array.isArray(meta.previews)) meta.previews = meta.previews.map((name) => String(name).trim()).filter(Boolean);
986
+ else delete meta.previews;
987
+ meta.stages = /^\d+$/.test(String(meta.stages ?? "").trim()) ? Number(meta.stages) : 0;
988
+ meta.phase = /^\d+$/.test(String(meta.phase ?? "").trim()) ? Number(meta.phase) : 0;
989
+ meta.preview_approved = meta.preview_approved === "true";
990
+ meta.archived = typeof meta.archived === "string" && meta.archived.trim() ? meta.archived.trim() : "";
991
+ meta.rejected = meta.rejected === "true";
992
+ meta.rejected_reason = typeof meta.rejected_reason === "string" ? meta.rejected_reason : "";
993
+ meta.rejected_at = typeof meta.rejected_at === "string" ? meta.rejected_at.trim() : "";
994
+ meta.rejected_by = meta.rejected_by === "user" || meta.rejected_by === "agent" ? meta.rejected_by : "";
995
+ return { meta, body: lines.slice(i + 1).join("\n") };
996
+ }
997
+ function frontmatterEnd(lines) {
998
+ if (lines[0]?.trim() !== "---") return 0;
999
+ let i = 1;
1000
+ while (i < lines.length && lines[i].trim() !== "---") i++;
1001
+ return i >= lines.length ? 0 : i;
1002
+ }
1003
+ function frontmatterField(lines, i) {
1004
+ for (let j = i; j > 0; j--) {
1005
+ const m = lines[j].match(/^([A-Za-z_]+):/);
1006
+ if (m) return m[1];
1007
+ }
1008
+ return "frontmatter";
1009
+ }
1010
+ var STATUSES;
1011
+ var init_frontmatter = __esm({
1012
+ "src/lib/frontmatter.ts"() {
1013
+ "use strict";
1014
+ init_yaml();
1015
+ init_question_block();
1016
+ init_rules();
1017
+ STATUSES = ["todo", "ready", "implementing"];
1018
+ }
1019
+ });
1020
+
1021
+ // src/lib/questions.ts
1022
+ function newDraft(flag, value) {
1023
+ const text4 = value.trim();
1024
+ if (!text4) die(`--${flag} must not be empty`);
1025
+ if (text4.startsWith("[user]")) die(`"${text4}" starts with [user] \u2014 drop the prefix; every open question is the user's`);
1026
+ return { question: text4, options: [], recommended: [] };
1027
+ }
1028
+ function addToDraft(q, key, value) {
1029
+ if (key === "mode") {
1030
+ const m = value.toLowerCase();
1031
+ if (!MODES.includes(m)) die(`--mode must be single | multi (got "${value}")`);
1032
+ q.mode = m;
1033
+ return;
1034
+ }
1035
+ const text4 = value.trim();
1036
+ if (!text4) die(`--${key} must not be empty`);
1037
+ if (key === "agent") {
1038
+ q.agent = text4;
1039
+ return;
1040
+ }
1041
+ if (q.options.includes(text4)) die(`"${text4}" is listed twice as an option of "${q.question}"`);
1042
+ q.options.push(text4);
1043
+ if (key === "recommended-option") q.recommended.push(text4);
1044
+ }
1045
+ function finalizeDraft(q) {
1046
+ if (q.options.length === 0) missingChoices(q.question);
1047
+ if (q.options.length < 2) {
1048
+ die(`a question with options needs at least 2 \u2014 add another --option ("${q.question}")`);
1049
+ }
1050
+ q.mode = q.mode || "single";
1051
+ if (q.mode === "single" && q.recommended.length > 1) {
1052
+ die(`--mode single takes at most one --recommended-option ("${q.question}")`);
1053
+ }
1054
+ q.recommend = q.recommended.map((text4) => q.options.indexOf(text4) + 1).sort((a, b) => a - b);
1055
+ return normalizeQuestion(q);
1056
+ }
1057
+ function collectQuestions(order) {
1058
+ const out = [];
1059
+ for (const [key, value] of order) {
1060
+ if (key === "question") {
1061
+ out.push(newDraft("question", value));
1062
+ } else if (key === "option" || key === "mode" || key === "recommended-option") {
1063
+ const q = out[out.length - 1];
1064
+ if (!q) die(`--${key} must come after the --question it belongs to`);
1065
+ addToDraft(q, key, value);
1066
+ }
1067
+ }
1068
+ return out.map(finalizeDraft);
1069
+ }
1070
+ function missingChoices(text4) {
1071
+ die(
1072
+ `"${text4}" needs choices to tick \u2014 add 2 or more --option "a \u2014 why". The user always gets a free-text choice too, so never write one yourself.`
1073
+ );
1074
+ }
1075
+ function readQuestionOps(typed) {
1076
+ const ops = [];
1077
+ for (let i = 0; i < typed.length; i++) {
1078
+ const [key, value] = typed[i];
1079
+ if (key === "clear") {
1080
+ ops.push({ kind: "clear" });
1081
+ } else if (key === "drop") {
1082
+ ops.push({ kind: key, ns: value });
1083
+ } else if (key === "append") {
1084
+ ops.push({ kind: "append", draft: newDraft("append", value) });
1085
+ } else if (key === "update") {
1086
+ const n = Number(value);
1087
+ if (!Number.isInteger(n) || n < 1) die('--update takes a 1-based question number, then the new text: --update <n> ".."');
1088
+ const next = typed[i + 1];
1089
+ if (!next || next[0] !== "update") die('--update takes a 1-based question number, then the new text: --update <n> ".."');
1090
+ i++;
1091
+ ops.push({ kind: "update", n, draft: newDraft("update", next[1]) });
1092
+ } else {
1093
+ const last = ops[ops.length - 1];
1094
+ if (!last || !last.draft) die(`--${key} must come after the --append or --update it belongs to`);
1095
+ addToDraft(last.draft, key, value);
1096
+ }
1097
+ }
1098
+ if (!ops.length) {
1099
+ die('update-questions needs at least one op: --append ".." | --update <n> ".." | --drop n[,n...] | --clear');
1100
+ }
1101
+ for (const op of ops) {
1102
+ if (op.draft) {
1103
+ op.question = finalizeDraft(op.draft);
1104
+ delete op.draft;
1105
+ }
1106
+ }
1107
+ return ops;
1108
+ }
1109
+ var init_questions = __esm({
1110
+ "src/lib/questions.ts"() {
1111
+ "use strict";
1112
+ init_paths();
1113
+ init_question_block();
1114
+ init_question_block();
1115
+ init_rules();
1116
+ }
1117
+ });
1118
+
1119
+ // src/lib/question-ops.ts
1120
+ function questionPositions(raw, count3, flag) {
1121
+ const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
1122
+ if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
1123
+ throw new QuestionOpError(`--${flag} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
1124
+ }
1125
+ const over = ns.find((n) => n > count3);
1126
+ if (over !== void 0) throw new QuestionOpError(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
1127
+ return ns;
1128
+ }
1129
+ function applyQuestionOps(start, ops, asker) {
1130
+ let questions = [...start];
1131
+ const changes = [];
1132
+ const closed2 = [];
1133
+ const positions = (op, flag) => questionPositions(op.ns ?? String(op.n), questions.length, flag);
1134
+ for (const op of ops) {
1135
+ if (op.kind === "clear") {
1136
+ closed2.push(...questions);
1137
+ questions = [];
1138
+ changes.push("cleared");
1139
+ } else if (op.kind === "drop") {
1140
+ const ns = positions(op, "drop");
1141
+ closed2.push(...ns.map((n) => questions[n - 1]));
1142
+ questions = questions.filter((_, i) => !ns.includes(i + 1));
1143
+ changes.push(`dropped ${ns.join(",")}`);
1144
+ } else if (op.kind === "append") {
1145
+ const agent = op.question.agent ?? asker;
1146
+ questions.push(agent ? { ...op.question, agent } : op.question);
1147
+ changes.push("appended");
1148
+ } else {
1149
+ const [n] = positions(op, "update");
1150
+ const agent = op.question.agent ?? questions[n - 1].agent;
1151
+ questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
1152
+ changes.push(`rewrote ${n}`);
1153
+ }
1154
+ }
1155
+ return { questions, changes, closed: closed2 };
1156
+ }
1157
+ var QuestionOpError;
1158
+ var init_question_ops = __esm({
1159
+ "src/lib/question-ops.ts"() {
1160
+ "use strict";
1161
+ QuestionOpError = class extends Error {
1162
+ };
1163
+ }
1164
+ });
1165
+
1166
+ // src/lib/cloud/avatar.ts
1167
+ async function heldAvatar(url) {
1168
+ if (!url) return null;
1169
+ const held4 = readSession();
1170
+ if (!held4) return null;
1171
+ if (held4.avatar?.url === url) return held4.avatar.data;
1172
+ const data = await download(url);
1173
+ if (!data) return null;
1174
+ const now = readSession();
1175
+ if (now) writeSession({ ...now, avatar: { url, data } });
1176
+ return data;
1177
+ }
1178
+ async function download(url) {
1179
+ try {
1180
+ const response = await fetch(sized(url), { signal: AbortSignal.timeout(TIMEOUT_MS) });
1181
+ if (!response.ok) return null;
1182
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
1183
+ if (!type.startsWith("image/")) return null;
1184
+ const bytes2 = Buffer.from(await response.arrayBuffer());
1185
+ if (bytes2.byteLength === 0 || bytes2.byteLength > MAX_BYTES) return null;
1186
+ return `data:${type};base64,${bytes2.toString("base64")}`;
1187
+ } catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ function sized(url) {
1192
+ try {
1193
+ const asked = new URL(url);
1194
+ asked.searchParams.set("s", String(PIXELS));
1195
+ return asked.toString();
1196
+ } catch {
1197
+ return url;
1198
+ }
1199
+ }
1200
+ var PIXELS, MAX_BYTES, TIMEOUT_MS;
1201
+ var init_avatar = __esm({
1202
+ "src/lib/cloud/avatar.ts"() {
1203
+ "use strict";
1204
+ init_session();
1205
+ PIXELS = 80;
1206
+ MAX_BYTES = 256 * 1024;
1207
+ TIMEOUT_MS = 5e3;
1208
+ }
1209
+ });
1210
+
1211
+ // src/lib/cloud/pro.ts
1212
+ import fs5 from "node:fs";
1213
+ import path6 from "node:path";
1214
+ function forgetPro() {
1215
+ fs5.rmSync(heldFile(), { force: true });
1216
+ }
1217
+ var FRESH_MS, GRACE_MS, heldFile;
1218
+ var init_pro = __esm({
1219
+ "src/lib/cloud/pro.ts"() {
1220
+ "use strict";
1221
+ init_home();
1222
+ init_config();
1223
+ init_session();
1224
+ FRESH_MS = 10 * 6e4;
1225
+ GRACE_MS = 7 * 24 * 60 * 6e4;
1226
+ heldFile = () => path6.join(machineHome(), "pro.json");
1227
+ }
1228
+ });
1229
+
1230
+ // src/lib/cloud/account.ts
1231
+ async function readCloudAccount() {
1232
+ const blank = {
1233
+ state: "signed-out",
1234
+ handle: null,
1235
+ name: null,
1236
+ avatarUrl: null,
1237
+ avatarData: null,
1238
+ email: null,
1239
+ message: null,
1240
+ inviteRequestedAt: null,
1241
+ sessionFile: sessionFile(),
1242
+ configured: cloudConfigured()
1243
+ };
1244
+ if (!blank.configured) return { ...blank, message: NOT_CONFIGURED };
1245
+ const token2 = await accessToken();
1246
+ if (!token2.ok) {
1247
+ if (token2.reason === "signed-out") return blank;
1248
+ if (token2.reason === "unreachable") {
1249
+ return { ...blank, ...held(), state: "signed-in", error: token2.error };
1250
+ }
1251
+ return { ...blank, ...held(), state: "expired" };
1252
+ }
1253
+ let response;
1254
+ try {
1255
+ response = await fetch(`${cloudEndpoints().api}/v1/session`, {
1256
+ headers: { authorization: `Bearer ${token2.token}` }
1257
+ });
1258
+ } catch (e) {
1259
+ return {
1260
+ ...blank,
1261
+ ...held(),
1262
+ state: "signed-in",
1263
+ error: e instanceof Error ? e.message : String(e)
1264
+ };
1265
+ }
1266
+ const body = await response.json().catch(() => ({}));
1267
+ if (!response.ok) {
1268
+ const refusal2 = body.error;
1269
+ if (refusal2?.code === "unauthenticated") {
1270
+ return { ...blank, ...held(), state: "expired", message: refusal2.message ?? null };
1271
+ }
1272
+ if (refusal2?.code === "not_admitted") {
1273
+ return { ...blank, ...held(), state: "not-admitted", message: refusal2.message ?? null };
1274
+ }
1275
+ return { ...blank, ...held(), state: "signed-in", error: refusal2?.message };
1276
+ }
1277
+ const session = body.session ?? {};
1278
+ const avatarUrl = session.avatar_url ?? session.avatarUrl ?? null;
1279
+ const attested = {
1280
+ handle: session.handle ?? null,
1281
+ name: session.name ?? null,
1282
+ avatarUrl,
1283
+ // Costs a fetch the first time this address is seen and a file read every time after,
1284
+ // so the picture is on the machine before any screen asks to draw it.
1285
+ avatarData: await heldAvatar(avatarUrl),
1286
+ email: session.email ?? null,
1287
+ inviteRequestedAt: session.inviteRequestedAt ?? null
1288
+ };
1289
+ return session.admitted ? { ...blank, ...attested, state: "signed-in" } : { ...blank, ...attested, state: "not-admitted", message: body.refusal?.message ?? null };
1290
+ }
1291
+ function signOutOfCloud() {
1292
+ clearSession();
1293
+ forgetPro();
1294
+ return { ok: true };
1295
+ }
1296
+ function held() {
1297
+ const session = readSession();
1298
+ return {
1299
+ handle: session?.handle ?? null,
1300
+ name: session?.name ?? null,
1301
+ avatarUrl: session?.avatarUrl ?? null,
1302
+ avatarData: session?.avatar?.data ?? null,
1303
+ email: session?.email ?? null
1304
+ };
1305
+ }
1306
+ var init_account = __esm({
1307
+ "src/lib/cloud/account.ts"() {
1308
+ "use strict";
1309
+ init_avatar();
1310
+ init_config();
1311
+ init_pro();
1312
+ init_session();
1313
+ }
1314
+ });
1315
+
1316
+ // src/commands/cloud.ts
1317
+ import fs6 from "node:fs";
1318
+ import path7 from "node:path";
1319
+ async function cmdCloud(args, program2) {
1320
+ const [sub] = args;
1321
+ if (sub === "sign-out") {
1322
+ signOutOfCloud();
1323
+ say("Signed out. This machine no longer reaches Cloud; nothing on any board changed.");
1324
+ return { signedOut: true };
1325
+ }
1326
+ if (sub !== void 0) {
891
1327
  die(
892
1328
  `unknown \`account\` command "${sub}". Try \`${program2} account\` or \`${program2} account sign-out\`.`,
893
1329
  { kind: "unknown-move" }
@@ -1029,11 +1465,13 @@ function refuse(m, fallback) {
1029
1465
  async function generate(g) {
1030
1466
  const token2 = await accessToken();
1031
1467
  if (!token2.ok) refuse(SAID[token2.reason], g.fallback);
1468
+ const task = workspaceTask();
1032
1469
  let res;
1033
1470
  try {
1034
1471
  res = await fetch(`${cloudEndpoints().api}${g.endpoint}`, {
1035
1472
  method: "POST",
1036
- headers: { authorization: `Bearer ${token2.token}`, "content-type": "application/json" },
1473
+ // The task this spends credits for, inside a Runner task (#629).
1474
+ headers: { authorization: `Bearer ${token2.token}`, "content-type": "application/json", ...task ? { "x-wildcrane-task": task } : {} },
1037
1475
  body: JSON.stringify(g.body)
1038
1476
  });
1039
1477
  } catch {
@@ -1062,6 +1500,7 @@ var init_cloud = __esm({
1062
1500
  init_account();
1063
1501
  init_config();
1064
1502
  init_session();
1503
+ init_tasks();
1065
1504
  init_paths();
1066
1505
  init_io();
1067
1506
  SAID = {
@@ -1134,436 +1573,172 @@ async function all(route2) {
1134
1573
  function linked() {
1135
1574
  for (let dir = process.cwd(); ; dir = path8.dirname(dir)) {
1136
1575
  if (fs7.existsSync(path8.join(dir, ".akb", "base.json"))) {
1137
- const link2 = linkedProject("", dir);
1138
- return link2.ok ? link2.value : null;
1139
- }
1140
- if (path8.dirname(dir) === dir) return null;
1141
- }
1142
- }
1143
- async function project(asked) {
1144
- const id = asked ?? linked();
1145
- if (id) return id;
1146
- const rows = await all("/v1/projects");
1147
- return refuse2(`Pick a project with --project: ${rows.map(projectLine).join(", ") || "none yet"}`, "no_project");
1148
- }
1149
- async function workspace(asked) {
1150
- if (asked) return asked;
1151
- const prj = linked();
1152
- if (prj) return (await cloud("GET", `/v1/projects/${enc(prj)}`)).workspace;
1153
- const rows = await all("/v1/workspaces");
1154
- return refuse2(`Pick a workspace with --workspace: ${rows.map((w) => `${w.id} ${w.name}`).join(", ")}`, "no_project");
1155
- }
1156
- async function taskRef(asked) {
1157
- if (!/^\d+$/.test(asked.trim())) return asked.trim();
1158
- const prj = linked();
1159
- if (!prj) refuse2("Write the full task key, like WC-12, or run this in a linked folder.", "no_project");
1160
- return `${(await cloud("GET", `/v1/projects/${enc(prj)}`)).prefix}-${asked.trim()}`;
1161
- }
1162
- async function taskList(opts) {
1163
- const scope = opts.project || !opts.workspace ? `project=${enc(await project(opts.project))}` : `workspace=${enc(opts.workspace)}`;
1164
- const page = await cloud("GET", `/v1/tasks?${scope}&limit=100${opts.status ? `&status=${enc(opts.status)}` : ""}`);
1165
- for (const t of page.data) say(`${t.key} ${t.status} ${t.title}`);
1166
- return { ...page };
1167
- }
1168
- async function taskShow(id) {
1169
- const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1170
- const card = task.workflow ? await cloud("GET", `/v1/tasks/${enc(task.id)}/card`).catch(() => null) : null;
1171
- say(`${task.key} ${task.title}`);
1172
- say(`${task.status}${task.workflow ? ` ${task.workflow.name}` : ""} ${taskUrl(task.key)}`);
1173
- if (card?.body) say(`
1174
- ${card.body.trim()}`);
1175
- return { ...task, card };
1176
- }
1177
- async function taskCreate(request2, opts) {
1178
- const text4 = request2.trim();
1179
- if (!text4) die("Say what the task is.", { kind: "bad-args", exitCode: 2 });
1180
- const line = text4.split("\n")[0].trim();
1181
- const title = line.length > 80 ? `${line.slice(0, 79)}\u2026` : line;
1182
- const task = await cloud("POST", "/v1/tasks", {
1183
- title,
1184
- request: text4,
1185
- project: await project(opts.project),
1186
- ...opts.workflow ? { workflow: cloudWorkflow(opts.workflow) } : {},
1187
- source: "api"
1188
- });
1189
- say(`Created ${task.key}: ${task.title} ${taskUrl(task.key)}`);
1190
- return { ...task };
1191
- }
1192
- async function act(id, route2, body, done2) {
1193
- const ref = await taskRef(id);
1194
- const value = await cloud("POST", `/v1/tasks/${enc(ref)}/${route2}`, body);
1195
- say(done2(ref));
1196
- return value;
1197
- }
1198
- async function taskApprove(id, comment) {
1199
- const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1200
- return act(task.key, "decisions", {
1201
- decision: "approve",
1202
- ...comment?.trim() ? { comment: comment.trim() } : {},
1203
- ...task.review ? { review_revision: task.review.revision } : {}
1204
- }, (k) => `Approved ${k}.`);
1205
- }
1206
- async function workspaceList() {
1207
- const data = await all("/v1/workspaces");
1208
- for (const w of data) say(`${w.id} ${w.name}`);
1209
- return { data };
1210
- }
1211
- async function projectList(opts) {
1212
- const data = await all(`/v1/projects${opts.workspace ? `?workspace=${enc(opts.workspace)}` : ""}`);
1213
- for (const p of data) say(projectLine(p));
1214
- return { data };
1215
- }
1216
- async function runnerList(opts) {
1217
- const held4 = await cloud("GET", `/v1/workspaces/${enc(await workspace(opts.workspace))}/runners`);
1218
- for (const r of held4.runners) say(`${r.name} ${r.connected ? "online" : "offline"}`);
1219
- return held4;
1220
- }
1221
- var refuse2, enc, WEB, taskUrl, projectLine, taskChat, taskRemove, taskResume, taskStop, taskComment;
1222
- var init_task = __esm({
1223
- "src/commands/task.ts"() {
1224
- "use strict";
1225
- init_config();
1226
- init_session();
1227
- init_tasks();
1228
- init_io();
1229
- init_paths();
1230
- init_cloud();
1231
- refuse2 = (message, code) => die(message, { kind: code, code });
1232
- enc = encodeURIComponent;
1233
- WEB = () => process.env.WILDCRANE_WEB_URL || "https://app.wildcrane.ai";
1234
- taskUrl = (key) => `${WEB()}/tasks/${enc(key)}`;
1235
- projectLine = (p) => `${p.id} ${p.prefix} ${p.name}`;
1236
- taskChat = (id, message) => act(id, "chat", { body: message }, (k) => `Sent to ${k}.`);
1237
- taskRemove = (id, reason) => act(id, "cancel", reason.trim() ? { reason: reason.trim() } : void 0, (k) => `Removed ${k}. Restore it on the web.`);
1238
- taskResume = (id) => act(id, "resume", void 0, (k) => `Resumed ${k}.`);
1239
- taskStop = (id) => act(id, "stop", void 0, (k) => `Stopped ${k}.`);
1240
- taskComment = (id, text4) => act(id, "comments", { body: text4 }, (k) => `Commented on ${k}.`);
1241
- }
1242
- });
1243
-
1244
- // src/lib/spec-agent-names.ts
1245
- var LEGACY_SPEC_AGENT_NAMES, FOLDED_SPEC_AGENTS, canonicalSpecAgent, specAgentNames;
1246
- var init_spec_agent_names = __esm({
1247
- "src/lib/spec-agent-names.ts"() {
1248
- "use strict";
1249
- LEGACY_SPEC_AGENT_NAMES = {
1250
- "recommend-tech-stack": "tech-stack-advisor",
1251
- "technology-selection": "tech-stack-advisor",
1252
- "ui-design": "ui-designer",
1253
- // Renamed in #945 and folded into the editor in #1057; its asset memory stays in
1254
- // `memory/agents/video-assets/`.
1255
- "video-assets": "hyperframes-editor",
1256
- // Renamed in #1502: it reads chats, and writes memory as a result.
1257
- "memory-reviewer": "chat-reviewer",
1258
- // Folded into `copywriting` in #1582.
1259
- "user-docs": "copywriting"
1260
- };
1261
- FOLDED_SPEC_AGENTS = /* @__PURE__ */ new Set(["user-docs"]);
1262
- canonicalSpecAgent = (name) => {
1263
- const asked = name.trim();
1264
- return LEGACY_SPEC_AGENT_NAMES[asked] ?? asked;
1265
- };
1266
- specAgentNames = (name) => {
1267
- const canonical = canonicalSpecAgent(name);
1268
- return [
1269
- canonical,
1270
- ...Object.entries(LEGACY_SPEC_AGENT_NAMES).filter(([, current]) => current === canonical).map(([legacy2]) => legacy2)
1271
- ];
1272
- };
1273
- }
1274
- });
1275
-
1276
- // src/lib/yaml.ts
1277
- function yamlScalar(s) {
1278
- const text4 = String(s);
1279
- if (text4 === "") return '""';
1280
- if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text4) || /:\s/.test(text4) || /[\n"]/.test(text4) || /^\s|\s$/.test(text4)) {
1281
- return JSON.stringify(text4);
1282
- }
1283
- return text4;
1284
- }
1285
- function unquote(v) {
1286
- const text4 = String(v).trim();
1287
- if (text4.startsWith('"') && text4.endsWith('"')) {
1288
- try {
1289
- return JSON.parse(text4);
1290
- } catch {
1291
- return text4.slice(1, -1);
1292
- }
1293
- }
1294
- if (text4.startsWith("'") && text4.endsWith("'")) return text4.slice(1, -1);
1295
- return text4;
1296
- }
1297
- var init_yaml = __esm({
1298
- "src/lib/yaml.ts"() {
1299
- "use strict";
1300
- }
1301
- });
1302
-
1303
- // src/lib/question-block.ts
1304
- function normalizeQuestion(raw) {
1305
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
1306
- const source = raw;
1307
- const text4 = withoutTag(String(source.question ?? source.text ?? ""));
1308
- const extra = {
1309
- ...typeof source.agent === "string" && source.agent.trim() ? { agent: source.agent.trim() } : {},
1310
- ...source.skipped === true || source.skipped === "true" ? { skipped: true } : {}
1311
- };
1312
- const options = (Array.isArray(source.options) ? source.options : []).map((o) => String(o).trim()).filter(Boolean);
1313
- if (options.length === 0) return { text: text4, ...extra };
1314
- const mode = MODES.includes(String(source.mode)) ? String(source.mode) : "single";
1315
- const recommend = (Array.isArray(source.recommend) ? source.recommend : []).map(Number).filter((n) => Number.isInteger(n) && n >= 1 && n <= options.length);
1316
- return { text: text4, mode, options, recommend: mode === "single" ? recommend.slice(0, 1) : recommend, ...extra };
1317
- }
1318
- return { text: withoutTag(String(raw)) };
1319
- }
1320
- function parseQuestionsBlock(lines) {
1321
- const out = [];
1322
- for (let i = 0; i < lines.length; i++) {
1323
- const m = lines[i].match(/^\s*-\s+([\s\S]*)$/);
1324
- if (!m) continue;
1325
- const head2 = m[1];
1326
- const opened = head2.match(/^question:\s*(.*)$/);
1327
- if (!opened) {
1328
- out.push(normalizeQuestion(unquote(head2)));
1329
- continue;
1330
- }
1331
- const q = {
1332
- question: unquote(opened[1]),
1333
- options: [],
1334
- recommend: []
1335
- };
1336
- while (i + 1 < lines.length && !/^\s*-\s/.test(lines[i + 1])) {
1337
- const field2 = lines[i + 1].match(/^\s*([A-Za-z_]+):\s*(.*)$/);
1338
- i++;
1339
- if (!field2) continue;
1340
- const [, key, val] = field2;
1341
- if (key === "options") {
1342
- while (i + 1 < lines.length && /^\s*-\s+/.test(lines[i + 1])) {
1343
- q.options.push(unquote(lines[i + 1].replace(/^\s*-\s+/, "")));
1344
- i++;
1345
- }
1346
- } else if (key === "recommend") {
1347
- q.recommend = val.replace(/^\[|\]$/g, "").split(",").map((s) => Number(s.trim())).filter((n) => Number.isInteger(n));
1348
- } else if (key === "mode") {
1349
- q.mode = unquote(val);
1350
- } else if (key === "agent") {
1351
- q.agent = unquote(val);
1352
- } else if (key === "skipped") {
1353
- q.skipped = unquote(val) === "true";
1354
- }
1576
+ const link2 = linkedProject("", dir);
1577
+ return link2.ok ? link2.value : null;
1355
1578
  }
1356
- out.push(normalizeQuestion(q));
1579
+ if (path8.dirname(dir) === dir) return null;
1357
1580
  }
1358
- return out;
1359
1581
  }
1360
- var MODES, withoutTag;
1361
- var init_question_block = __esm({
1362
- "src/lib/question-block.ts"() {
1363
- "use strict";
1364
- init_yaml();
1365
- MODES = ["single", "multi"];
1366
- withoutTag = (text4) => text4.replace(/^\[user\]\s+/, "");
1367
- }
1368
- });
1369
-
1370
- // src/lib/view/rules.ts
1371
- function creationRefusal(id, creation, what, discard = false) {
1372
- if (!creation || creation.state === "unfinished" && discard) return null;
1373
- const run2 = creation.runId.slice(0, 8);
1374
- return creation.state === "creating" ? `#${id} is still being created by run ${run2} \u2014 \`${what}\` is refused until that run finishes.` : `#${id} was never finished being created: run ${run2} stopped short. \`${what}\` is refused until that run is picked back up from the board and finishes. Use reject --discard to discard it instead.`;
1582
+ async function project(asked) {
1583
+ const id = asked ?? linked();
1584
+ if (id) return id;
1585
+ const rows = await all("/v1/projects");
1586
+ return refuse2(`Pick a project with --project: ${rows.map(projectLine).join(", ") || "none yet"}`, "no_project");
1375
1587
  }
1376
- function hasOptions(q) {
1377
- return Array.isArray(q.options) && q.options.length > 0;
1588
+ async function workspace(asked) {
1589
+ if (asked) return asked;
1590
+ const prj = linked();
1591
+ if (prj) return (await cloud("GET", `/v1/projects/${enc(prj)}`)).workspace;
1592
+ const rows = await all("/v1/workspaces");
1593
+ return refuse2(`Pick a workspace with --workspace: ${rows.map((w) => `${w.id} ${w.name}`).join(", ")}`, "no_project");
1378
1594
  }
1379
- function planDeliveryGap(card) {
1380
- if (openOf(card.questions).length > 0) return "questions";
1381
- if (!planDeliverables(card.body).length) return "deliverable";
1382
- if (!/^[ \t]*[-*]\s+\[[xX]\].*`[^`]+`/m.test(card.body)) return "command";
1383
- const { total, done: done2 } = card.todos;
1384
- return total > 0 && done2 === total ? null : "todos";
1595
+ async function taskRef(asked) {
1596
+ if (!/^\d+$/.test(asked.trim())) return asked.trim();
1597
+ const prj = linked();
1598
+ if (!prj) refuse2("Write the full task key, like WC-12, or run this in a linked folder.", "no_project");
1599
+ return `${(await cloud("GET", `/v1/projects/${enc(prj)}`)).prefix}-${asked.trim()}`;
1385
1600
  }
1386
- function awaitingApproval(card) {
1387
- const { stages, stage } = card;
1388
- if (!stages || !stage || stage >= stages || card.status !== "ready") return null;
1389
- return openOf(card.questions).length ? null : stage;
1601
+ async function taskList(opts) {
1602
+ const scope = opts.project || !opts.workspace ? `project=${enc(await project(opts.project))}` : `workspace=${enc(opts.workspace)}`;
1603
+ const page = await cloud("GET", `/v1/tasks?${scope}&limit=100${opts.status ? `&status=${enc(opts.status)}` : ""}`);
1604
+ for (const t of page.data) say(`${t.key} ${t.status} ${t.title}`);
1605
+ return { ...page };
1390
1606
  }
1391
- function byDispatchOrder(a, b) {
1392
- return rank(LEVEL_RANK, a.priority) - rank(LEVEL_RANK, b.priority) || a.id - b.id;
1607
+ async function taskShow(id) {
1608
+ const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1609
+ const card = task.workflow ? await cloud("GET", `/v1/tasks/${enc(task.id)}/card`).catch(() => null) : null;
1610
+ say(`${task.key} ${task.title}`);
1611
+ say(`${task.status}${task.workflow ? ` ${task.workflow.name}` : ""} ${taskUrl(task.key)}`);
1612
+ if (card?.body) say(`
1613
+ ${card.body.trim()}`);
1614
+ return { ...task, card };
1393
1615
  }
1394
- function canRefine(card) {
1395
- if (card.isGroup) return false;
1396
- if (awaitingApproval(card)) return false;
1397
- if (card.status !== "todo" && !planUnfinished(card)) return false;
1398
- const { total, done: done2 } = card.todos;
1399
- if (total > 0 && done2 === total && !planUnfinished(card)) return false;
1400
- const open3 = openOf(card.questions);
1401
- if (open3.length > 0 && open3.every(hasOptions)) return false;
1402
- return true;
1616
+ async function taskCreate(request2, opts) {
1617
+ const text4 = request2.trim();
1618
+ if (!text4) die("Say what the task is.", { kind: "bad-args", exitCode: 2 });
1619
+ const line = text4.split("\n")[0].trim();
1620
+ const title = line.length > 80 ? `${line.slice(0, 79)}\u2026` : line;
1621
+ const task = await cloud("POST", "/v1/tasks", {
1622
+ title,
1623
+ request: text4,
1624
+ project: await project(opts.project),
1625
+ ...opts.workflow ? { workflow: cloudWorkflow(opts.workflow) } : {},
1626
+ source: "api"
1627
+ });
1628
+ say(`Created ${task.key}: ${task.title} ${taskUrl(task.key)}`);
1629
+ return { ...task };
1403
1630
  }
1404
- var openOf, PLAN_DELIVERABLE, PAGES_STORYBOARD, planDeliverables, planUnfinished, LEVEL_RANK, rank;
1405
- var init_rules = __esm({
1406
- "src/lib/view/rules.ts"() {
1407
- "use strict";
1408
- openOf = (questions) => questions.filter((q) => !q.skipped);
1409
- PLAN_DELIVERABLE = /\.(mp4|webm|mov|m4v|pptx|md|mdx)$/i;
1410
- PAGES_STORYBOARD = /(^|\/)pages-[^/]*\.json$/i;
1411
- planDeliverables = (body) => [
1412
- ...[...body.matchAll(/<Asset\s[^>]*src="([^"]+)"/gi)].map((m) => m[1]).filter((src) => PLAN_DELIVERABLE.test(src)),
1413
- ...[...body.matchAll(/<Storyboard\s[^>]*src="([^"]+)"/gi)].map((m) => m[1]).filter((src) => PAGES_STORYBOARD.test(src))
1414
- ];
1415
- planUnfinished = (card) => card.deliversIn === "plan" && planDeliveryGap(card) !== null;
1416
- LEVEL_RANK = { high: 0, med: 1, low: 2 };
1417
- rank = (table, value) => table[value] ?? Object.keys(table).length;
1418
- }
1419
- });
1420
-
1421
- // src/lib/frontmatter.ts
1422
- function serializeFrontmatter(m) {
1423
- const out = ["---"];
1424
- out.push(`title: ${yamlScalar(m.title)}`);
1425
- out.push(`priority: ${m.priority}`);
1426
- out.push(`status: ${STATUSES.includes(String(m.status)) ? m.status : "todo"}`);
1427
- out.push(`blocked_by: [${(m.blocked_by || []).join(", ")}]`);
1428
- out.push(`related: [${(m.related || []).join(", ")}]`);
1429
- out.push(`modules: [${(m.modules || []).join(", ")}]`);
1430
- if (m.workflow) out.push(`workflow: ${yamlScalar(m.workflow)}`);
1431
- if (m.triage) out.push(`triage: ${yamlScalar(m.triage)}`);
1432
- if (m.source?.length) {
1433
- out.push("source:");
1434
- for (const ref of m.source) out.push(` - ${yamlScalar(ref)}`);
1435
- }
1436
- if (m.previews) out.push(`previews: [${m.previews.join(", ")}]`);
1437
- if ((m.stages ?? 0) > 0) out.push(`stages: ${m.stages}`);
1438
- if ((m.phase ?? 0) > 1) out.push(`phase: ${m.phase}`);
1439
- if (m.preview_approved) out.push("preview_approved: true");
1440
- if (m.archived) out.push(`archived: ${yamlScalar(m.archived)}`);
1441
- if (m.rejected) out.push("rejected: true");
1442
- if (m.rejected_reason) out.push(`rejected_reason: ${yamlScalar(m.rejected_reason)}`);
1443
- if (m.rejected_at) out.push(`rejected_at: ${yamlScalar(m.rejected_at)}`);
1444
- if (m.rejected_by) out.push(`rejected_by: ${m.rejected_by}`);
1445
- if (!m.questions || m.questions.length === 0) out.push("questions: []");
1446
- else {
1447
- out.push("questions:");
1448
- for (const raw of m.questions) {
1449
- const q = normalizeQuestion(raw);
1450
- if (!hasOptions(q) && !q.agent && !q.skipped) {
1451
- out.push(` - ${yamlScalar(q.text)}`);
1452
- continue;
1453
- }
1454
- out.push(` - question: ${yamlScalar(q.text)}`);
1455
- if (hasOptions(q)) {
1456
- out.push(` mode: ${q.mode}`);
1457
- out.push(" options:");
1458
- for (const o of q.options) out.push(` - ${yamlScalar(o)}`);
1459
- out.push(` recommend: [${q.recommend.join(", ")}]`);
1460
- }
1461
- if (q.agent) out.push(` agent: ${yamlScalar(q.agent)}`);
1462
- if (q.skipped) out.push(" skipped: true");
1463
- }
1464
- }
1465
- out.push("---");
1466
- return out.join("\n");
1631
+ async function act(id, route2, body, done2) {
1632
+ const ref = await taskRef(id);
1633
+ const value = await cloud("POST", `/v1/tasks/${enc(ref)}/${route2}`, body);
1634
+ say(done2(ref));
1635
+ return value;
1467
1636
  }
1468
- function parseFrontmatter(text4) {
1469
- const lines = text4.split("\n");
1470
- if (lines[0].trim() !== "---") return { meta: null, body: text4 };
1471
- let i = 1;
1472
- const fm = [];
1473
- while (i < lines.length && lines[i].trim() !== "---") {
1474
- fm.push(lines[i]);
1475
- i++;
1476
- }
1477
- if (i >= lines.length) return { meta: null, body: text4 };
1478
- const meta = {};
1479
- for (let j = 0; j < fm.length; j++) {
1480
- const m = fm[j].match(/^([A-Za-z_]+):\s*(.*)$/);
1481
- if (!m) continue;
1482
- const key = m[1];
1483
- const val = m[2];
1484
- if (key === "questions") {
1485
- if (val === "") {
1486
- const block = [];
1487
- while (j + 1 < fm.length && /^\s/.test(fm[j + 1]) && fm[j + 1].trim() !== "") {
1488
- block.push(fm[j + 1]);
1489
- j++;
1490
- }
1491
- meta.questions = parseQuestionsBlock(block);
1492
- } else {
1493
- meta.questions = val.trim() === "[]" ? [] : [normalizeQuestion(unquote(val))];
1494
- }
1495
- continue;
1496
- }
1497
- if (val === "") {
1498
- const items = [];
1499
- while (j + 1 < fm.length && /^\s*-\s+/.test(fm[j + 1])) {
1500
- items.push(unquote(fm[j + 1].replace(/^\s*-\s+/, "")));
1501
- j++;
1502
- }
1503
- meta[key] = items;
1504
- } else if (val.startsWith("[")) {
1505
- const inner = val.slice(1, val.lastIndexOf("]"));
1506
- meta[key] = inner.split(",").map((s) => s.trim()).filter(Boolean).map(unquote);
1507
- } else {
1508
- meta[key] = unquote(val);
1509
- }
1510
- }
1511
- for (const k of ["blocked_by", "related"]) {
1512
- const value = meta[k];
1513
- if (Array.isArray(value)) {
1514
- meta[k] = value.map((x) => Number(String(x).replace(/^#/, ""))).filter((n) => Number.isInteger(n));
1515
- } else {
1516
- meta[k] = [];
1517
- }
1518
- }
1519
- if (!Array.isArray(meta.questions)) {
1520
- meta.questions = meta.questions ? [normalizeQuestion(meta.questions)] : [];
1637
+ async function taskApprove(id, comment) {
1638
+ const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1639
+ return act(task.key, "decisions", {
1640
+ decision: "approve",
1641
+ ...comment?.trim() ? { comment: comment.trim() } : {},
1642
+ ...task.review ? { review_revision: task.review.revision } : {}
1643
+ }, (k) => `Approved ${k}.`);
1644
+ }
1645
+ async function taskUpdateQuestions(id, typed) {
1646
+ const ops = readQuestionOps(typed);
1647
+ const ref = await taskRef(id);
1648
+ const card = await cloud("GET", `/v1/tasks/${enc(ref)}/card`);
1649
+ const questions = parseFrontmatter(card.body).meta?.questions ?? [];
1650
+ let changes;
1651
+ let open3;
1652
+ try {
1653
+ const done2 = applyQuestionOps(questions, ops);
1654
+ changes = done2.changes;
1655
+ open3 = done2.questions.length;
1656
+ } catch (e) {
1657
+ if (e instanceof QuestionOpError) die(`${ref}: ${e.message}`);
1658
+ throw e;
1521
1659
  }
1522
- meta.priority = typeof meta.priority === "string" ? meta.priority.trim() : "";
1523
- if (!Array.isArray(meta.modules)) meta.modules = [];
1524
- delete meta.channels;
1525
- delete meta.decided;
1526
- delete meta.verify;
1527
- delete meta.release;
1528
- delete meta.schedule;
1529
- delete meta.roi;
1530
- meta.workflow = typeof meta.workflow === "string" && meta.workflow.trim() ? meta.workflow.trim() : "";
1531
- meta.triage = typeof meta.triage === "string" ? meta.triage.trim() : "";
1532
- meta.source = (Array.isArray(meta.source) ? meta.source : typeof meta.source === "string" ? [meta.source] : []).map((ref) => String(ref).trim()).filter(Boolean);
1533
- delete meta.phases;
1534
- if (Array.isArray(meta.previews)) meta.previews = meta.previews.map((name) => String(name).trim()).filter(Boolean);
1535
- else delete meta.previews;
1536
- meta.stages = /^\d+$/.test(String(meta.stages ?? "").trim()) ? Number(meta.stages) : 0;
1537
- meta.phase = /^\d+$/.test(String(meta.phase ?? "").trim()) ? Number(meta.phase) : 0;
1538
- meta.preview_approved = meta.preview_approved === "true";
1539
- meta.archived = typeof meta.archived === "string" && meta.archived.trim() ? meta.archived.trim() : "";
1540
- meta.rejected = meta.rejected === "true";
1541
- meta.rejected_reason = typeof meta.rejected_reason === "string" ? meta.rejected_reason : "";
1542
- meta.rejected_at = typeof meta.rejected_at === "string" ? meta.rejected_at.trim() : "";
1543
- meta.rejected_by = meta.rejected_by === "user" || meta.rejected_by === "agent" ? meta.rejected_by : "";
1544
- return { meta, body: lines.slice(i + 1).join("\n") };
1660
+ const body = ops.map((op) => {
1661
+ const q = op.question && { text: op.question.text, options: op.question.options, recommend: op.question.recommend, mode: op.question.mode, agent: op.question.agent };
1662
+ if (op.kind === "append") return { append: q };
1663
+ if (op.kind === "update") return { update: op.n, question: q };
1664
+ if (op.kind === "drop") return { drop: questionPositions(op.ns, Infinity, "drop") };
1665
+ if (op.kind === "clear") return { clear: true };
1666
+ return die(`akb task update-questions has no --${op.kind}; --drop removes a question`);
1667
+ });
1668
+ const task = await cloud("PATCH", `/v1/tasks/${enc(ref)}/questions`, { base_version: card.version, ops: body });
1669
+ say(`updated ${task.key} questions: ${changes.join(", ")} (${open3} open)`);
1670
+ return { ...task, changes, open: open3 };
1545
1671
  }
1546
- function frontmatterEnd(lines) {
1547
- if (lines[0]?.trim() !== "---") return 0;
1548
- let i = 1;
1549
- while (i < lines.length && lines[i].trim() !== "---") i++;
1550
- return i >= lines.length ? 0 : i;
1672
+ async function workspaceList() {
1673
+ const data = await all("/v1/workspaces");
1674
+ for (const w of data) say(`${w.id} ${w.name}`);
1675
+ return { data };
1551
1676
  }
1552
- function frontmatterField(lines, i) {
1553
- for (let j = i; j > 0; j--) {
1554
- const m = lines[j].match(/^([A-Za-z_]+):/);
1555
- if (m) return m[1];
1556
- }
1557
- return "frontmatter";
1677
+ async function projectList(opts) {
1678
+ const data = await all(`/v1/projects${opts.workspace ? `?workspace=${enc(opts.workspace)}` : ""}`);
1679
+ for (const p of data) say(projectLine(p));
1680
+ return { data };
1681
+ }
1682
+ async function runnerList(opts) {
1683
+ const held4 = await cloud("GET", `/v1/workspaces/${enc(await workspace(opts.workspace))}/runners`);
1684
+ for (const r of held4.runners) say(`${r.name} ${r.connected ? "online" : "offline"}`);
1685
+ return held4;
1558
1686
  }
1559
- var STATUSES;
1560
- var init_frontmatter = __esm({
1561
- "src/lib/frontmatter.ts"() {
1687
+ var refuse2, enc, WEB, taskUrl, projectLine, taskChat, taskRemove, taskResume, taskStop, taskComment;
1688
+ var init_task = __esm({
1689
+ "src/commands/task.ts"() {
1562
1690
  "use strict";
1563
- init_yaml();
1564
- init_question_block();
1565
- init_rules();
1566
- STATUSES = ["todo", "ready", "implementing"];
1691
+ init_config();
1692
+ init_session();
1693
+ init_tasks();
1694
+ init_io();
1695
+ init_paths();
1696
+ init_frontmatter();
1697
+ init_questions();
1698
+ init_question_ops();
1699
+ init_cloud();
1700
+ refuse2 = (message, code) => die(message, { kind: code, code });
1701
+ enc = encodeURIComponent;
1702
+ WEB = () => process.env.WILDCRANE_WEB_URL || "https://app.wildcrane.ai";
1703
+ taskUrl = (key) => `${WEB()}/tasks/${enc(key)}`;
1704
+ projectLine = (p) => `${p.id} ${p.prefix} ${p.name}`;
1705
+ taskChat = (id, message) => act(id, "chat", { body: message }, (k) => `Sent to ${k}.`);
1706
+ taskRemove = (id, reason) => act(id, "cancel", reason.trim() ? { reason: reason.trim() } : void 0, (k) => `Removed ${k}. Restore it on the web.`);
1707
+ taskResume = (id) => act(id, "resume", void 0, (k) => `Resumed ${k}.`);
1708
+ taskStop = (id) => act(id, "stop", void 0, (k) => `Stopped ${k}.`);
1709
+ taskComment = (id, text4) => act(id, "comments", { body: text4 }, (k) => `Commented on ${k}.`);
1710
+ }
1711
+ });
1712
+
1713
+ // src/lib/spec-agent-names.ts
1714
+ var LEGACY_SPEC_AGENT_NAMES, FOLDED_SPEC_AGENTS, canonicalSpecAgent, specAgentNames;
1715
+ var init_spec_agent_names = __esm({
1716
+ "src/lib/spec-agent-names.ts"() {
1717
+ "use strict";
1718
+ LEGACY_SPEC_AGENT_NAMES = {
1719
+ "recommend-tech-stack": "tech-stack-advisor",
1720
+ "technology-selection": "tech-stack-advisor",
1721
+ "ui-design": "ui-designer",
1722
+ // Renamed in #945 and folded into the editor in #1057; its asset memory stays in
1723
+ // `memory/agents/video-assets/`.
1724
+ "video-assets": "hyperframes-editor",
1725
+ // Renamed in #1502: it reads chats, and writes memory as a result.
1726
+ "memory-reviewer": "chat-reviewer",
1727
+ // Folded into `copywriting` in #1582.
1728
+ "user-docs": "copywriting"
1729
+ };
1730
+ FOLDED_SPEC_AGENTS = /* @__PURE__ */ new Set(["user-docs"]);
1731
+ canonicalSpecAgent = (name) => {
1732
+ const asked = name.trim();
1733
+ return LEGACY_SPEC_AGENT_NAMES[asked] ?? asked;
1734
+ };
1735
+ specAgentNames = (name) => {
1736
+ const canonical = canonicalSpecAgent(name);
1737
+ return [
1738
+ canonical,
1739
+ ...Object.entries(LEGACY_SPEC_AGENT_NAMES).filter(([, current]) => current === canonical).map(([legacy2]) => legacy2)
1740
+ ];
1741
+ };
1567
1742
  }
1568
1743
  });
1569
1744
 
@@ -2256,12 +2431,13 @@ function insideRun() {
2256
2431
  function runEnv(env2, value) {
2257
2432
  return { ...env2, [RUN_ENV]: value };
2258
2433
  }
2259
- var RUN_ENV, SCHEDULED_AGENTS_ENV, STOP_ENV, SESSION_VARS;
2434
+ var RUN_ENV, SCHEDULED_AGENTS_ENV, SESSION_COST_ENV, STOP_ENV, SESSION_VARS;
2260
2435
  var init_env = __esm({
2261
2436
  "src/lib/agent/env.ts"() {
2262
2437
  "use strict";
2263
2438
  RUN_ENV = "KANBAN_RUN";
2264
2439
  SCHEDULED_AGENTS_ENV = "AI4KANBAN_SCHEDULED_AGENTS";
2440
+ SESSION_COST_ENV = "AI4KANBAN_SESSION_COST";
2265
2441
  STOP_ENV = "KANBAN_STOP_ID";
2266
2442
  SESSION_VARS = {
2267
2443
  "claude-code": "CLAUDE_CODE_SESSION_ID",
@@ -2914,6 +3090,11 @@ function createEventCollector() {
2914
3090
  const t = target ? targetOf(target) : void 0;
2915
3091
  queue.push({ kind: "tool_call", data: { toolCallId, title, kind, status: "in_progress", ...t ? { target: t } : {} } });
2916
3092
  },
3093
+ /** A subagent the agent started, titled by its task; it ends with its call's `toolResult`. */
3094
+ subagent(toolCallId, title) {
3095
+ close();
3096
+ queue.push({ kind: "tool_call", data: { toolCallId, title: targetOf(title) ?? "subagent", kind: "other", status: "in_progress", subagent: true } });
3097
+ },
2917
3098
  toolResult(toolCallId, status, result) {
2918
3099
  close();
2919
3100
  queue.push({ kind: "tool_call_update", data: { toolCallId, status, ...result.trim() ? { result: result.trim() } : {} } });
@@ -3093,6 +3274,13 @@ function createStreamRenderer() {
3093
3274
  const backgrounded = /* @__PURE__ */ new Set();
3094
3275
  const events = createEventCollector();
3095
3276
  const plans = /* @__PURE__ */ new Set();
3277
+ const subagents = /* @__PURE__ */ new Map();
3278
+ const detached = /* @__PURE__ */ new Set();
3279
+ const endSubagent = (id, status) => {
3280
+ if (subagents.get(id) !== false) return;
3281
+ subagents.set(id, true);
3282
+ events.toolResult(id, status, "");
3283
+ };
3096
3284
  const renderLine = (line) => {
3097
3285
  if (!line.trim()) return "";
3098
3286
  const ev = frame(line);
@@ -3102,6 +3290,7 @@ function createStreamRenderer() {
3102
3290
  `;
3103
3291
  }
3104
3292
  if (model === void 0) model = eventModel(ev);
3293
+ if (str(ev.parent_tool_use_id)) return "";
3105
3294
  switch (ev.type) {
3106
3295
  case "assistant": {
3107
3296
  const msg = ev.message;
@@ -3119,7 +3308,12 @@ function createStreamRenderer() {
3119
3308
  } else if (b?.type === "tool_use" && typeof b.name === "string") {
3120
3309
  out.push(`\u23FA ${b.name}${argHint(b.input, ARG_KEYS)}
3121
3310
  `);
3122
- if (b.name === "TodoWrite") {
3311
+ if (SUBAGENT_TOOLS.has(b.name)) {
3312
+ const input = obj(b.input);
3313
+ subagents.set(str(b.id), false);
3314
+ if (input.run_in_background === true) detached.add(str(b.id));
3315
+ events.subagent(str(b.id), str(input.description) || str(input.subagent_type) || b.name);
3316
+ } else if (b.name === "TodoWrite") {
3123
3317
  plans.add(str(b.id));
3124
3318
  events.plan(obj(b.input).todos);
3125
3319
  } else {
@@ -3134,6 +3328,10 @@ function createStreamRenderer() {
3134
3328
  for (const raw of Array.isArray(content) ? content : []) {
3135
3329
  const b = obj(raw);
3136
3330
  if (b.type !== "tool_result" || plans.has(str(b.tool_use_id))) continue;
3331
+ if (subagents.has(str(b.tool_use_id))) {
3332
+ if (!detached.has(str(b.tool_use_id))) endSubagent(str(b.tool_use_id), b.is_error === true ? "failed" : "completed");
3333
+ continue;
3334
+ }
3137
3335
  events.toolResult(str(b.tool_use_id), b.is_error === true ? "failed" : "completed", resultText(b.content));
3138
3336
  }
3139
3337
  return "";
@@ -3161,6 +3359,9 @@ function createStreamRenderer() {
3161
3359
  case "system":
3162
3360
  if (ev.subtype === "background_tasks_changed" && Array.isArray(ev.tasks)) background = ev.tasks.length;
3163
3361
  if (ev.subtype === "task_started" && ev.is_backgrounded === true) backgrounded.add(str(ev.task_id));
3362
+ if (ev.subtype === "task_notification" && subagents.has(str(ev.tool_use_id))) {
3363
+ endSubagent(str(ev.tool_use_id), str(ev.status) === "completed" ? "completed" : "failed");
3364
+ }
3164
3365
  if (ev.subtype === "task_notification" && backgrounded.has(str(ev.task_id)) && str(ev.summary)) {
3165
3366
  return `\u23FA ${str(ev.summary)}
3166
3367
  `;
@@ -3195,7 +3396,7 @@ function usageOf(raw) {
3195
3396
  };
3196
3397
  return parsed.input + parsed.cacheCreation + parsed.cacheRead + parsed.output > 0 ? parsed : void 0;
3197
3398
  }
3198
- var ARG_KEYS, TOOL_KINDS2, USER_FIXES, addUsage;
3399
+ var ARG_KEYS, TOOL_KINDS2, SUBAGENT_TOOLS, USER_FIXES, addUsage;
3199
3400
  var init_claude_stream = __esm({
3200
3401
  "src/lib/agent/wire/claude-stream.ts"() {
3201
3402
  "use strict";
@@ -3215,6 +3416,7 @@ var init_claude_stream = __esm({
3215
3416
  WebFetch: "fetch",
3216
3417
  WebSearch: "fetch"
3217
3418
  };
3419
+ SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Agent", "Task"]);
3218
3420
  USER_FIXES = [
3219
3421
  [/failed to authenticate|invalid api key|oauth token|please run \/login|not logged in/i, "Sign in to Claude Code again: run `claude` and enter /login."],
3220
3422
  [/usage limit|credit balance is too low|quota/i, "Wait for the usage limit to reset, or add credit, then press Resume."]
@@ -3766,6 +3968,8 @@ function createKimiStreamRenderer(cwd) {
3766
3968
  let sessionId;
3767
3969
  let facts;
3768
3970
  let lookedAt = 0;
3971
+ const events = createEventCollector();
3972
+ const subagents = /* @__PURE__ */ new Set();
3769
3973
  const look = (now) => {
3770
3974
  const at = Date.now();
3771
3975
  if (!now && at - lookedAt < LOOK_EVERY_MS2) return;
@@ -3782,6 +3986,18 @@ function createKimiStreamRenderer(cwd) {
3782
3986
  case "assistant": {
3783
3987
  const said2 = str(row.content).trim();
3784
3988
  if (said2) final = said2;
3989
+ if (said2) events.message(said2);
3990
+ for (const raw of Array.isArray(row.tool_calls) ? row.tool_calls : []) {
3991
+ const call2 = obj(raw);
3992
+ const name = str(obj(call2.function).name) || "tool";
3993
+ const args = obj(callArgs(obj(call2.function).arguments));
3994
+ if (name === "Agent") {
3995
+ subagents.add(str(call2.id));
3996
+ events.subagent(str(call2.id), str(args.description) || name);
3997
+ } else {
3998
+ events.toolCall(str(call2.id), name, kindOf(name), ARG_KEYS2.map((k) => str(args[k])).find((v) => v.trim()));
3999
+ }
4000
+ }
3785
4001
  return `${said2 ? `${said2}
3786
4002
 
3787
4003
  ` : ""}${toolCalls(row)}`;
@@ -3789,6 +4005,13 @@ function createKimiStreamRenderer(cwd) {
3789
4005
  case "meta":
3790
4006
  if (row.type === "session.resume_hint") sessionId ??= str(row.session_id).trim() || void 0;
3791
4007
  return row.type === "turn.step.retrying" ? retry(row) : "";
4008
+ case "tool": {
4009
+ const id = str(row.tool_call_id);
4010
+ const text4 = str(row.content);
4011
+ if (subagents.delete(id)) events.toolResult(id, /^status: completed$/m.test(text4) ? "completed" : "failed", "");
4012
+ else events.toolResult(id, "completed", text4);
4013
+ return "";
4014
+ }
3792
4015
  default:
3793
4016
  return "";
3794
4017
  }
@@ -3802,6 +4025,7 @@ function createKimiStreamRenderer(cwd) {
3802
4025
  return out;
3803
4026
  },
3804
4027
  result: () => final,
4028
+ events: events.events,
3805
4029
  usage: () => facts?.usage,
3806
4030
  context: () => {
3807
4031
  look(false);
@@ -3820,14 +4044,23 @@ function createKimiStreamRenderer(cwd) {
3820
4044
  }
3821
4045
  };
3822
4046
  }
3823
- var ARG_KEYS2, LOOK_EVERY_MS2;
4047
+ var ARG_KEYS2, TOOL_KINDS3, kindOf, LOOK_EVERY_MS2;
3824
4048
  var init_kimi_stream = __esm({
3825
4049
  "src/lib/agent/wire/kimi-stream.ts"() {
3826
4050
  "use strict";
4051
+ init_events();
3827
4052
  init_json();
3828
4053
  init_stream();
3829
4054
  init_kimi_session();
3830
4055
  ARG_KEYS2 = ["command", "path", "pattern", "query", "url", "prompt", "prompt_template", "description"];
4056
+ TOOL_KINDS3 = [
4057
+ [/read/i, "read"],
4058
+ [/grep|glob|search/i, "search"],
4059
+ [/fetch|web/i, "fetch"],
4060
+ [/bash|shell/i, "execute"],
4061
+ [/write|edit|replace/i, "edit"]
4062
+ ];
4063
+ kindOf = (name) => TOOL_KINDS3.find(([re]) => re.test(name))?.[1] ?? "other";
3831
4064
  LOOK_EVERY_MS2 = 3e3;
3832
4065
  }
3833
4066
  });
@@ -3975,7 +4208,7 @@ var init_package = __esm({
3975
4208
  "package.json"() {
3976
4209
  package_default = {
3977
4210
  name: "wildcrane",
3978
- version: "0.11.35",
4211
+ version: "0.11.36",
3979
4212
  akbContract: 8,
3980
4213
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
3981
4214
  keywords: [
@@ -7422,7 +7655,8 @@ function parseRuntime(value) {
7422
7655
  for (const [key, v] of Object.entries(configBlock(raw.settings))) {
7423
7656
  if (typeof v === "string" && v.trim()) settings[key] = v.trim();
7424
7657
  }
7425
- return { id, name: id === GLOBAL_ID ? GLOBAL_NAME : name, harness, settings };
7658
+ const away = typeof raw.away === "string" && raw.away.trim() ? { away: raw.away.trim() } : {};
7659
+ return { id, name: id === GLOBAL_ID ? GLOBAL_NAME : name, harness, settings, ...away };
7426
7660
  }
7427
7661
  function dedupe(list) {
7428
7662
  const seen = /* @__PURE__ */ new Set();
@@ -7488,6 +7722,20 @@ function runtimeOfAgent(names3, table = readAgentRuntime()) {
7488
7722
  }
7489
7723
  return void 0;
7490
7724
  }
7725
+ function replaceAgentRuntimes(picks) {
7726
+ return writeConfig((cfg) => {
7727
+ const global = readRuntimes(cfg)[0];
7728
+ const rows = /* @__PURE__ */ new Map();
7729
+ for (const r of Object.values(picks)) if (r.id !== GLOBAL_ID) rows.set(r.id, r);
7730
+ cfg.runtimes = [global, ...rows.values()];
7731
+ delete cfg.harnessSettings;
7732
+ delete cfg.harness;
7733
+ delete cfg.agentHarness;
7734
+ const block = Object.fromEntries(Object.entries(picks).filter(([, r]) => rows.has(r.id)).map(([agent, r]) => [agent, r.id]));
7735
+ if (Object.keys(block).length) cfg.agentRuntime = block;
7736
+ else delete cfg.agentRuntime;
7737
+ });
7738
+ }
7491
7739
  function setRuntimeHarness(id, harness) {
7492
7740
  const known2 = harnessByName(harness);
7493
7741
  if (!known2) return { ok: false, ...noHarness(harness) };
@@ -8606,7 +8854,7 @@ function specAgentSelector(id, workflow, meta) {
8606
8854
  // own job.
8607
8855
  "<preview-agents>",
8608
8856
  "The preview agents of this card's current stage, each writing one part of the card.",
8609
- ...agents.map((a) => `- \`${a.name}\` \u2014 ${a.description}${a.session ? " \xB7 runs in a session of its own: leave out `--print`" : ""}`),
8857
+ ...agents.map((a) => `- \`${a.name}\` \u2014 ${a.description}${a.session || agentRun(a.name).own ? " \xB7 runs in a session of its own: leave out `--print`" : ""}`),
8610
8858
  `Command: \`akb raw previews <agent> ${id} <short note>\` \u2014 add \`--print\` to run it in this session, as \`akb guide refine\` says.`,
8611
8859
  "</preview-agents>"
8612
8860
  ].join("\n");
@@ -9436,17 +9684,32 @@ function mcpProblem(text4) {
9436
9684
  return null;
9437
9685
  }
9438
9686
  function checkWorkflowFiles(value, official = false) {
9439
- const fail = (file, reason, tooLarge = false) => ({ ok: false, file, reason, ...tooLarge ? { tooLarge } : {} });
9687
+ const read3 = inspect(value, official);
9688
+ const first = read3.problems[0];
9689
+ return first ? { ok: false, ...first } : { ok: true, def: read3.def, files: read3.files };
9690
+ }
9691
+ function inspect(value, official) {
9692
+ const problems = [];
9693
+ const fail = (file, reason, tooLarge = false) => {
9694
+ problems.push({ file, reason, ...tooLarge ? { tooLarge } : {} });
9695
+ return { problems };
9696
+ };
9440
9697
  if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
9441
- value = Object.fromEntries(Object.entries(value).filter(([file]) => file !== VERSION_FILE));
9442
- const entries = Object.entries(value);
9698
+ const files = Object.fromEntries(Object.entries(value).filter(([file]) => file !== VERSION_FILE));
9699
+ const entries = Object.entries(files);
9443
9700
  if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
9444
9701
  let total = 0;
9445
9702
  const folders2 = /* @__PURE__ */ new Map();
9446
9703
  const skills = /* @__PURE__ */ new Set();
9447
9704
  for (const [file, text4] of entries) {
9448
- if (typeof text4 !== "string" || text4.includes("\0")) return fail(file, "is not a text file");
9449
- if (file.length > FILE_LIMITS.path) return fail(file, `the path is longer than ${FILE_LIMITS.path} characters`);
9705
+ if (typeof text4 !== "string" || text4.includes("\0")) {
9706
+ fail(file, "is not a text file");
9707
+ continue;
9708
+ }
9709
+ if (file.length > FILE_LIMITS.path) {
9710
+ fail(file, `the path is longer than ${FILE_LIMITS.path} characters`);
9711
+ continue;
9712
+ }
9450
9713
  const size = bytes(text4);
9451
9714
  if (size > FILE_LIMITS.file) return fail(file, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
9452
9715
  total += size;
@@ -9454,49 +9717,56 @@ function checkWorkflowFiles(value, official = false) {
9454
9717
  if (file === WORKFLOW_FILE) continue;
9455
9718
  if (official && file === MCP_FILE) {
9456
9719
  const problem = mcpProblem(text4);
9457
- if (problem) return fail(file, problem);
9720
+ if (problem) fail(file, problem);
9458
9721
  continue;
9459
9722
  }
9460
9723
  if (official && isAboutFile(file)) continue;
9461
9724
  if (official && file.startsWith("skills/")) {
9462
- if (!folderPath(file, "skills")) return fail(file, "is not inside skills/<name>/");
9463
- skills.add(file.split("/")[1]);
9725
+ if (!folderPath(file, "skills")) fail(file, "is not inside skills/<name>/");
9726
+ else skills.add(file.split("/")[1]);
9464
9727
  continue;
9465
9728
  }
9466
9729
  const at = folderPath(file, "agents");
9467
- if (!at) return fail(file, `is neither ${WORKFLOW_FILE} nor inside agents/<name>/`);
9730
+ if (!at) {
9731
+ fail(file, `is neither ${WORKFLOW_FILE} nor inside agents/<name>/`);
9732
+ continue;
9733
+ }
9468
9734
  if (!folders2.has(at[0])) folders2.set(at[0], /* @__PURE__ */ new Map());
9469
9735
  folders2.get(at[0]).set(at[1], text4);
9470
9736
  }
9471
9737
  for (const name of skills) {
9472
- if (value[`skills/${name}/SKILL.md`] === void 0) return fail(`skills/${name}/SKILL.md`, "is missing");
9738
+ if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
9473
9739
  }
9474
- const source = value[WORKFLOW_FILE];
9475
- if (source === void 0) return fail(WORKFLOW_FILE, "is missing");
9476
- const read3 = parseWorkflowFile("workflow", source, WORKFLOW_FILE);
9477
- if ("problem" in read3) return fail(WORKFLOW_FILE, read3.problem.replace(`${WORKFLOW_FILE}: `, ""));
9478
- const def = read3.def;
9740
+ const source = files[WORKFLOW_FILE];
9741
+ const read3 = typeof source === "string" ? parseWorkflowFile("workflow", source, WORKFLOW_FILE) : null;
9742
+ if (!read3) fail(WORKFLOW_FILE, "is missing");
9743
+ else if ("problem" in read3) fail(WORKFLOW_FILE, read3.problem.replace(`${WORKFLOW_FILE}: `, ""));
9479
9744
  const agents = /* @__PURE__ */ new Map();
9480
9745
  for (const [name, own] of folders2) {
9481
9746
  const from = `agents/${name}/AGENT.md`;
9482
9747
  const text4 = own.get("AGENT.md");
9483
- if (text4 === void 0) return fail(from, "is missing");
9748
+ if (text4 === void 0) {
9749
+ fail(from, "is missing");
9750
+ continue;
9751
+ }
9484
9752
  const parsed = parseSpecAgent(text4, from, (p) => own.get(p) ?? null, false, () => [...own.keys()].filter((p) => p !== "AGENT.md"));
9485
- if ("problem" in parsed) return fail(from, parsed.problem.replace(`${from}: `, ""));
9486
- if (parsed.agent.name !== name) return fail(from, `calls itself \`${parsed.agent.name}\`; it must match its folder`);
9487
- agents.set(name, parsed.agent);
9753
+ if ("problem" in parsed) fail(from, parsed.problem.replace(`${from}: `, ""));
9754
+ else if (parsed.agent.name !== name) fail(from, `calls itself \`${parsed.agent.name}\`; it must match its folder`);
9755
+ else agents.set(name, parsed.agent);
9488
9756
  }
9757
+ if (!read3 || "problem" in read3) return { problems };
9758
+ const def = read3.def;
9489
9759
  const named2 = [
9490
9760
  ...def.previews.map((h) => [h.agent, "it previews with"]),
9491
9761
  ...def.land.map((h) => [h.agent, "it lands with"]),
9492
9762
  ...def.scheduled.map((s) => [s.agent, "it schedules"])
9493
9763
  ];
9494
9764
  for (const [name, why2] of named2) {
9495
- if (!agents.has(name)) return fail(WORKFLOW_FILE, `${why2} \`${name}\`, which has no agents/${name}/AGENT.md`);
9765
+ if (!agents.has(name) && !folders2.has(name)) fail(WORKFLOW_FILE, `${why2} \`${name}\`, which has no agents/${name}/AGENT.md`);
9496
9766
  }
9497
- return { ok: true, def, files: value };
9767
+ return { problems, def, files };
9498
9768
  }
9499
- var WORKFLOW_FILE, MCP_FILE, VERSION_FILE, versionText, KB, FILE_LIMITS, officialId, hashInput, landsOf, SEGMENT, isAboutFile, bytes;
9769
+ var WORKFLOW_FILE, MCP_FILE, VERSION_FILE, versionText, KB, FILE_LIMITS, officialId, hashInput, landsOf, SEGMENT, isAboutFile, bytes, workflowFilesProblems;
9500
9770
  var init_workflow_files = __esm({
9501
9771
  "src/lib/shared/workflow-files.ts"() {
9502
9772
  "use strict";
@@ -9516,6 +9786,7 @@ var init_workflow_files = __esm({
9516
9786
  SEGMENT = /^[\w.-]+$/;
9517
9787
  isAboutFile = (file) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file);
9518
9788
  bytes = (text4) => new TextEncoder().encode(text4).length;
9789
+ workflowFilesProblems = (value, official = false) => inspect(value, official).problems;
9519
9790
  }
9520
9791
  });
9521
9792
 
@@ -10634,9 +10905,9 @@ var init_goal_cloud = __esm({
10634
10905
  }
10635
10906
  });
10636
10907
 
10637
- // node_modules/commander/lib/error.js
10908
+ // ../../../../cli/node_modules/commander/lib/error.js
10638
10909
  var require_error = __commonJS({
10639
- "node_modules/commander/lib/error.js"(exports) {
10910
+ "../../../../cli/node_modules/commander/lib/error.js"(exports) {
10640
10911
  var CommanderError2 = class extends Error {
10641
10912
  /**
10642
10913
  * Constructs the CommanderError class
@@ -10669,9 +10940,9 @@ var require_error = __commonJS({
10669
10940
  }
10670
10941
  });
10671
10942
 
10672
- // node_modules/commander/lib/argument.js
10943
+ // ../../../../cli/node_modules/commander/lib/argument.js
10673
10944
  var require_argument = __commonJS({
10674
- "node_modules/commander/lib/argument.js"(exports) {
10945
+ "../../../../cli/node_modules/commander/lib/argument.js"(exports) {
10675
10946
  var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
10676
10947
  var Argument2 = class {
10677
10948
  /**
@@ -10796,9 +11067,9 @@ var require_argument = __commonJS({
10796
11067
  }
10797
11068
  });
10798
11069
 
10799
- // node_modules/commander/lib/help.js
11070
+ // ../../../../cli/node_modules/commander/lib/help.js
10800
11071
  var require_help = __commonJS({
10801
- "node_modules/commander/lib/help.js"(exports) {
11072
+ "../../../../cli/node_modules/commander/lib/help.js"(exports) {
10802
11073
  var { humanReadableArgName } = require_argument();
10803
11074
  var Help2 = class {
10804
11075
  constructor() {
@@ -11365,9 +11636,9 @@ ${itemIndentStr}`);
11365
11636
  }
11366
11637
  });
11367
11638
 
11368
- // node_modules/commander/lib/option.js
11639
+ // ../../../../cli/node_modules/commander/lib/option.js
11369
11640
  var require_option = __commonJS({
11370
- "node_modules/commander/lib/option.js"(exports) {
11641
+ "../../../../cli/node_modules/commander/lib/option.js"(exports) {
11371
11642
  var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
11372
11643
  var Option2 = class {
11373
11644
  /**
@@ -11666,9 +11937,9 @@ var require_option = __commonJS({
11666
11937
  }
11667
11938
  });
11668
11939
 
11669
- // node_modules/commander/lib/suggestSimilar.js
11940
+ // ../../../../cli/node_modules/commander/lib/suggestSimilar.js
11670
11941
  var require_suggestSimilar = __commonJS({
11671
- "node_modules/commander/lib/suggestSimilar.js"(exports) {
11942
+ "../../../../cli/node_modules/commander/lib/suggestSimilar.js"(exports) {
11672
11943
  var maxDistance = 3;
11673
11944
  function editDistance2(a, b) {
11674
11945
  if (Math.abs(a.length - b.length) > maxDistance)
@@ -11746,9 +12017,9 @@ var require_suggestSimilar = __commonJS({
11746
12017
  }
11747
12018
  });
11748
12019
 
11749
- // node_modules/commander/lib/command.js
12020
+ // ../../../../cli/node_modules/commander/lib/command.js
11750
12021
  var require_command = __commonJS({
11751
- "node_modules/commander/lib/command.js"(exports) {
12022
+ "../../../../cli/node_modules/commander/lib/command.js"(exports) {
11752
12023
  var EventEmitter = __require("node:events").EventEmitter;
11753
12024
  var childProcess = __require("node:child_process");
11754
12025
  var path85 = __require("node:path");
@@ -13905,9 +14176,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
13905
14176
  }
13906
14177
  });
13907
14178
 
13908
- // node_modules/commander/index.js
14179
+ // ../../../../cli/node_modules/commander/index.js
13909
14180
  var require_commander = __commonJS({
13910
- "node_modules/commander/index.js"(exports) {
14181
+ "../../../../cli/node_modules/commander/index.js"(exports) {
13911
14182
  var { Argument: Argument2 } = require_argument();
13912
14183
  var { Command: Command2 } = require_command();
13913
14184
  var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
@@ -13927,10 +14198,10 @@ var require_commander = __commonJS({
13927
14198
  }
13928
14199
  });
13929
14200
 
13930
- // node_modules/commander/esm.mjs
14201
+ // ../../../../cli/node_modules/commander/esm.mjs
13931
14202
  var import_index, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
13932
14203
  var init_esm = __esm({
13933
- "node_modules/commander/esm.mjs"() {
14204
+ "../../../../cli/node_modules/commander/esm.mjs"() {
13934
14205
  import_index = __toESM(require_commander(), 1);
13935
14206
  ({
13936
14207
  program,
@@ -14948,15 +15219,6 @@ var init_pause = __esm({
14948
15219
  function answerOutcome(delivery) {
14949
15220
  return pendingAnswers(delivery).some((a) => a.outcome === "changed") ? "changed" : "unchanged";
14950
15221
  }
14951
- function takeUnchanged(delivery) {
14952
- if (!pendingAnswers(delivery).some((a) => a.outcome === "unchanged")) return;
14953
- withStore((store) => {
14954
- const live = store.deliveries.find((d) => d.deliveryId === delivery.deliveryId);
14955
- if (!live) return;
14956
- const now = Date.now();
14957
- for (const answer2 of live.answers ?? []) if (!answer2.actedAt && answer2.outcome === "unchanged") answer2.actedAt = now;
14958
- });
14959
- }
14960
15222
  function recordAnswer(deliveryId, outcome, why2) {
14961
15223
  const line = why2.trim();
14962
15224
  if (!line) return { ok: false, error: "say in one sentence what the answers did \u2014 an unexplained conclusion is not one." };
@@ -15653,7 +15915,6 @@ var init_deliveries = __esm({
15653
15915
  init_flows();
15654
15916
  init_pause();
15655
15917
  init_rules2();
15656
- init_rules();
15657
15918
  init_workflows();
15658
15919
  init_store();
15659
15920
  init_types();
@@ -15676,7 +15937,7 @@ var init_deliveries = __esm({
15676
15937
  ];
15677
15938
  isApproved = (heading) => APPROVED.some((re) => re.test(heading));
15678
15939
  cardStatus = (cardId2) => cardMeta2(cardId2)?.status || "todo";
15679
- openQuestions = (cardId2) => openOf(cardMeta2(cardId2)?.questions ?? []).length;
15940
+ openQuestions = (cardId2) => cardMeta2(cardId2)?.questions.length ?? 0;
15680
15941
  activeIn = (store, cardId2) => store.deliveries.find((d) => d.status === "active" && d.cardId === cardId2);
15681
15942
  listDeliveries = () => readStore().deliveries;
15682
15943
  withWorkflow = (req) => req.workflow ? req : {
@@ -16654,7 +16915,7 @@ function cardNow(cardId2) {
16654
16915
  if (!file) return null;
16655
16916
  const { meta } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
16656
16917
  if (!meta) return null;
16657
- return { status: meta.status || "todo", questions: openOf(meta.questions).length, title: meta.title };
16918
+ return { status: meta.status || "todo", questions: meta.questions.length, title: meta.title };
16658
16919
  } catch {
16659
16920
  return null;
16660
16921
  }
@@ -16956,6 +17217,8 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID4(), said2) {
16956
17217
  const parent = req.action === "sub" && req.parentId ? peekRun(req.parentId) : void 0;
16957
17218
  const cwd = parent?.cwd ?? deliveryCwd(start ?? joining ?? {});
16958
17219
  const plan = said2 ? { ...said2.plan(cwd, sessionId), note: null } : planRun(sessionId, cwd, agentForRun(req), req.runtime ? { pin: req.runtime } : {});
17220
+ const away = plan.runtime ? runtimeById(plan.runtime)?.away : void 0;
17221
+ if (away) return refusal("runtimeAway", away, { id: plan.runtime });
16959
17222
  if (plan.note) notes = [...notes, plan.note];
16960
17223
  const record = {
16961
17224
  sessionId,
@@ -16983,6 +17246,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID4(), said2) {
16983
17246
  // a fork is a fresh session of its own.
16984
17247
  ...said2 && !said2.fork ? { resumeId: plan.resumeId ?? void 0 } : {},
16985
17248
  ...said2?.continues ? { continues: { resumeId: said2.continues, ...said2.fork ? { fork: true } : {} } } : {},
17249
+ ...said2?.continues && said2.continues === req.carry?.resumeId && req.carry.costFrom ? { sessionCostFrom: req.carry.costFrom } : {},
16986
17250
  logPath: logPathOf(sessionId),
16987
17251
  // Which agent this is, on the action that is one — so the run list can name it, and so
16988
17252
  // a resume starts the same agent rather than a different one.
@@ -17834,113 +18098,6 @@ var init_inbox = __esm({
17834
18098
  }
17835
18099
  });
17836
18100
 
17837
- // src/lib/questions.ts
17838
- function newDraft(flag, value) {
17839
- const text4 = value.trim();
17840
- if (!text4) die(`--${flag} must not be empty`);
17841
- if (text4.startsWith("[user]")) die(`"${text4}" starts with [user] \u2014 drop the prefix; every open question is the user's`);
17842
- return { question: text4, options: [], recommended: [] };
17843
- }
17844
- function addToDraft(q, key, value) {
17845
- if (key === "mode") {
17846
- const m = value.toLowerCase();
17847
- if (!MODES.includes(m)) die(`--mode must be single | multi (got "${value}")`);
17848
- q.mode = m;
17849
- return;
17850
- }
17851
- const text4 = value.trim();
17852
- if (!text4) die(`--${key} must not be empty`);
17853
- if (key === "agent") {
17854
- q.agent = text4;
17855
- return;
17856
- }
17857
- if (q.options.includes(text4)) die(`"${text4}" is listed twice as an option of "${q.question}"`);
17858
- q.options.push(text4);
17859
- if (key === "recommended-option") q.recommended.push(text4);
17860
- }
17861
- function finalizeDraft(q) {
17862
- if (q.options.length === 0) missingChoices(q.question);
17863
- if (q.options.length < 2) {
17864
- die(`a question with options needs at least 2 \u2014 add another --option ("${q.question}")`);
17865
- }
17866
- q.mode = q.mode || "single";
17867
- if (q.mode === "single" && q.recommended.length > 1) {
17868
- die(`--mode single takes at most one --recommended-option ("${q.question}")`);
17869
- }
17870
- q.recommend = q.recommended.map((text4) => q.options.indexOf(text4) + 1).sort((a, b) => a - b);
17871
- return normalizeQuestion(q);
17872
- }
17873
- function collectQuestions(order) {
17874
- const out = [];
17875
- for (const [key, value] of order) {
17876
- if (key === "question") {
17877
- out.push(newDraft("question", value));
17878
- } else if (key === "option" || key === "mode" || key === "recommended-option") {
17879
- const q = out[out.length - 1];
17880
- if (!q) die(`--${key} must come after the --question it belongs to`);
17881
- addToDraft(q, key, value);
17882
- }
17883
- }
17884
- return out.map(finalizeDraft);
17885
- }
17886
- function missingChoices(text4) {
17887
- die(
17888
- `"${text4}" needs choices to tick \u2014 add 2 or more --option "a \u2014 why". The user always gets a free-text choice too, so never write one yourself.`
17889
- );
17890
- }
17891
- function readQuestionOps(typed) {
17892
- const ops = [];
17893
- for (let i = 0; i < typed.length; i++) {
17894
- const [key, value] = typed[i];
17895
- if (key === "clear") {
17896
- ops.push({ kind: "clear" });
17897
- } else if (key === "drop" || key === "skip" || key === "unskip") {
17898
- ops.push({ kind: key, ns: value });
17899
- } else if (key === "append") {
17900
- ops.push({ kind: "append", draft: newDraft("append", value) });
17901
- } else if (key === "update") {
17902
- const n = Number(value);
17903
- if (!Number.isInteger(n) || n < 1) die('--update takes a 1-based question number, then the new text: --update <n> ".."');
17904
- const next = typed[i + 1];
17905
- if (!next || next[0] !== "update") die('--update takes a 1-based question number, then the new text: --update <n> ".."');
17906
- i++;
17907
- ops.push({ kind: "update", n, draft: newDraft("update", next[1]) });
17908
- } else {
17909
- const last = ops[ops.length - 1];
17910
- if (!last || !last.draft) die(`--${key} must come after the --append or --update it belongs to`);
17911
- addToDraft(last.draft, key, value);
17912
- }
17913
- }
17914
- if (!ops.length) {
17915
- die('update-questions needs at least one op: --append ".." | --update <n> ".." | --drop n[,n...] | --skip n[,n...] | --unskip n[,n...] | --clear');
17916
- }
17917
- for (const op of ops) {
17918
- if (op.draft) {
17919
- op.question = finalizeDraft(op.draft);
17920
- delete op.draft;
17921
- }
17922
- }
17923
- return ops;
17924
- }
17925
- function parseQuestionPositions(raw, count3, flagName) {
17926
- const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
17927
- if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
17928
- die(`--${flagName} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
17929
- }
17930
- const over = ns.find((n) => n > count3);
17931
- if (over !== void 0) die(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
17932
- return ns;
17933
- }
17934
- var init_questions = __esm({
17935
- "src/lib/questions.ts"() {
17936
- "use strict";
17937
- init_paths();
17938
- init_question_block();
17939
- init_question_block();
17940
- init_rules();
17941
- }
17942
- });
17943
-
17944
18101
  // src/lib/source.ts
17945
18102
  function parseSourceRef(raw) {
17946
18103
  const text4 = raw.trim();
@@ -18545,7 +18702,7 @@ function bodyReferences(body) {
18545
18702
  for (const m of text4.replace(tag, "").matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^]*?["'])?\s*\)/g)) out.push({ src: m[1], types: [] });
18546
18703
  return out;
18547
18704
  }
18548
- function kindOf(ext) {
18705
+ function kindOf2(ext) {
18549
18706
  if (ext === ".tsx" || ext === ".html") return "html";
18550
18707
  if (ext === ".md" || ext === ".mdx") return "markdown";
18551
18708
  if (ext === ".tmx" || ext === ".tmj" || ext === ".tsj") return "tiled";
@@ -18685,7 +18842,7 @@ var init_collect = __esm({
18685
18842
  textKind = (ext, types) => types.find((t) => {
18686
18843
  const m = manifestOf(t);
18687
18844
  return m && !m.schema;
18688
- }) ?? kindOf(ext);
18845
+ }) ?? kindOf2(ext);
18689
18846
  kindAt = (src, types) => extOf(src) === ".json" ? types.includes("asset") ? "asset" : types[0] ?? "asset" : textKind(extOf(src), types);
18690
18847
  }
18691
18848
  });
@@ -19445,7 +19602,7 @@ function cmdUpdate(id, flags) {
19445
19602
  meta.phase = n;
19446
19603
  changes.push("phase");
19447
19604
  }
19448
- if (openOf(meta.questions).length > 0 && meta.status === "ready") {
19605
+ if (meta.questions.length > 0 && meta.status === "ready") {
19449
19606
  meta.status = "todo";
19450
19607
  changes.push("status\u2192todo (open questions)");
19451
19608
  }
@@ -19483,92 +19640,32 @@ function cmdUpdateQuestions(id, input) {
19483
19640
  const file = found2.kind === "group" ? path62.join(found2.target, "root.md") : found2.target;
19484
19641
  const { meta, body } = parseFrontmatter(fs59.readFileSync(file, "utf8"));
19485
19642
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 recreate it with \`akb raw create\``);
19486
- if (insideRun() && ops.some((op) => op.kind === "skip" || op.kind === "unskip")) {
19487
- die("only the user skips or reopens a question \u2014 a run leaves questions for them to answer");
19488
- }
19489
- const changes = [];
19490
- let skipped = 0;
19491
- let unskipped = 0;
19492
- const asker = specRunAgent();
19493
- const closed2 = [];
19494
- const verifying = !!activeDelivery(id);
19495
- const close = (qs) => {
19496
- for (const q of qs) {
19497
- closed2.push(verifying ? "questions_closed_verify" : "questions_closed_user");
19498
- }
19499
- };
19500
- const positions = (op, flag) => {
19501
- const ns = parseQuestionPositions(op.ns ?? String(op.n), meta.questions.length, flag);
19502
- const held4 = ns.find((n) => meta.questions[n - 1].skipped);
19503
- if (held4 !== void 0 && flag !== "unskip" && flag !== "skip") {
19504
- die(`question ${held4} on #${id} was skipped by the user \u2014 \`update-questions ${id} --unskip ${held4}\` reopens it first`);
19505
- }
19506
- return ns;
19507
- };
19508
19643
  for (const op of ops) {
19509
- if (op.question?.agent) {
19510
- const agent = findSpecAgent(op.question.agent);
19511
- if (!agent) die(`--agent "${op.question.agent}" is not an agent on this board`, { kind: "no-such-spec-agent", specAgent: op.question.agent });
19512
- op.question.agent = agent.name;
19513
- }
19514
- if (op.kind === "clear") {
19515
- close(meta.questions.filter((q) => !q.skipped));
19516
- meta.questions = meta.questions.filter((q) => q.skipped);
19517
- changes.push("cleared");
19518
- } else if (op.kind === "drop") {
19519
- const ns = positions(op, "drop");
19520
- close(ns.map((n) => meta.questions[n - 1]));
19521
- meta.questions = meta.questions.filter((_, i) => !ns.includes(i + 1));
19522
- changes.push(`dropped ${ns.join(",")}`);
19523
- } else if (op.kind === "skip") {
19524
- const ns = positions(op, "skip");
19525
- close(ns.map((n) => meta.questions[n - 1]).filter((q) => !q.skipped));
19526
- for (const n of ns) meta.questions[n - 1] = { ...meta.questions[n - 1], skipped: true };
19527
- skipped += ns.length;
19528
- changes.push(`skipped ${ns.join(",")}`);
19529
- } else if (op.kind === "unskip") {
19530
- const ns = positions(op, "unskip");
19531
- const open4 = ns.find((n) => !meta.questions[n - 1].skipped);
19532
- if (open4 !== void 0) die(`question ${open4} on #${id} is not skipped`);
19533
- for (const n of ns) {
19534
- const { skipped: _, ...q } = meta.questions[n - 1];
19535
- meta.questions[n - 1] = q;
19536
- }
19537
- unskipped += ns.length;
19538
- changes.push(`reopened ${ns.join(",")}`);
19539
- } else if (op.kind === "append") {
19540
- const agent = op.question.agent ?? asker;
19541
- const q = agent ? { ...op.question, agent } : op.question;
19542
- meta.questions.push(q);
19543
- changes.push("appended");
19544
- } else {
19545
- const [n] = positions(op, "update");
19546
- const was = meta.questions[n - 1];
19547
- const agent = op.question.agent ?? was.agent;
19548
- meta.questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
19549
- changes.push(`rewrote ${n}`);
19550
- }
19644
+ if (!op.question?.agent) continue;
19645
+ const agent = findSpecAgent(op.question.agent);
19646
+ if (!agent) die(`--agent "${op.question.agent}" is not an agent on this board`, { kind: "no-such-spec-agent", specAgent: op.question.agent });
19647
+ op.question.agent = agent.name;
19648
+ }
19649
+ let done2;
19650
+ try {
19651
+ done2 = applyQuestionOps(meta.questions, ops, specRunAgent());
19652
+ } catch (e) {
19653
+ if (e instanceof QuestionOpError) die(`#${id}: ${e.message}`);
19654
+ throw e;
19551
19655
  }
19552
- const open3 = openOf(meta.questions).length;
19656
+ const { changes } = done2;
19657
+ meta.questions = done2.questions;
19658
+ const open3 = meta.questions.length;
19553
19659
  if (open3 > 0 && meta.status === "ready") {
19554
19660
  meta.status = "todo";
19555
19661
  changes.push("status\u2192todo (open questions)");
19556
19662
  }
19557
19663
  fs59.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
19558
- for (const kind of closed2) countBoardEvent(kind);
19559
- settleDelivery2(id, skipped, unskipped);
19560
- say(
19561
- `updated #${id} questions: ${changes.join(", ")} (${open3} open` + (meta.questions.length > open3 ? `, ${meta.questions.length - open3} skipped` : "") + ")"
19562
- );
19664
+ const closed2 = activeDelivery(id) ? "questions_closed_verify" : "questions_closed_user";
19665
+ for (const _ of done2.closed) countBoardEvent(closed2);
19666
+ say(`updated #${id} questions: ${changes.join(", ")} (${open3} open)`);
19563
19667
  return { id, changes, open: open3, file: rel(file) };
19564
19668
  }
19565
- function settleDelivery2(id, skipped, unskipped) {
19566
- if (!skipped && !unskipped) return;
19567
- const delivery = activeDelivery(id);
19568
- if (!delivery) return;
19569
- if (unskipped) takeUnchanged(delivery);
19570
- else recordAnswer(delivery.deliveryId, "unchanged", `the user skipped ${skipped === 1 ? "a question" : `${skipped} questions`}, keeping the card as it is`);
19571
- }
19572
19669
  function specRunAgent() {
19573
19670
  const id = insideRun();
19574
19671
  if (!id) return void 0;
@@ -19586,6 +19683,7 @@ var init_card = __esm({
19586
19683
  init_workflows();
19587
19684
  init_inbox();
19588
19685
  init_questions();
19686
+ init_question_ops();
19589
19687
  init_frontmatter();
19590
19688
  init_cards();
19591
19689
  init_source();
@@ -19595,7 +19693,6 @@ var init_card = __esm({
19595
19693
  init_env();
19596
19694
  init_tasks();
19597
19695
  init_deliveries();
19598
- init_answers();
19599
19696
  init_agents();
19600
19697
  init_rules();
19601
19698
  init_readme();
@@ -20081,7 +20178,7 @@ function agentName(card, text4) {
20081
20178
  throw new Error(`the agent names \`${slug2}\` and \`${slug2}-${card.id}\` are both taken`);
20082
20179
  }
20083
20180
  function questionsToTriage(meta, agent) {
20084
- for (const q of openOf(meta.questions)) {
20181
+ for (const q of meta.questions) {
20085
20182
  const options = hasOptions(q) ? `
20086
20183
 
20087
20184
  ${q.options.map((o) => `- ${o}`).join("\n")}` : "";
@@ -20465,7 +20562,7 @@ function heldBy(card) {
20465
20562
  if (card.blockers.length) {
20466
20563
  holds.push({ kind: "blocked", text: `blocked by ${card.blockers.map((n) => `#${n}`).join(", ")}` });
20467
20564
  }
20468
- if (openOf(card.questions).length) {
20565
+ if (card.questions.length) {
20469
20566
  holds.push({ kind: "user", text: "waiting on you" });
20470
20567
  }
20471
20568
  if (card.status === "implementing") holds.push({ kind: "building", text: "being built" });
@@ -20474,7 +20571,6 @@ function heldBy(card) {
20474
20571
  var init_card_holds = __esm({
20475
20572
  "src/lib/card-holds.ts"() {
20476
20573
  "use strict";
20477
- init_rules();
20478
20574
  }
20479
20575
  });
20480
20576
 
@@ -20629,7 +20725,7 @@ function cmdList(opts) {
20629
20725
  const meta = [r.status, `priority ${r.priority}`];
20630
20726
  if (r.isRoot) meta.push("group root");
20631
20727
  if (r.blocked_by.length) meta.push(`blocked by ${r.blocked_by.map((n) => `#${n}`).join(", ")}`);
20632
- const open3 = openOf(r.questions).length;
20728
+ const open3 = r.questions.length;
20633
20729
  if (open3) meta.push(plural(open3, "open question"));
20634
20730
  say("");
20635
20731
  say(`#${r.id} ${r.title} (${rel(r.file)})`);
@@ -20653,7 +20749,6 @@ var init_list = __esm({
20653
20749
  init_scheduled();
20654
20750
  init_card_age();
20655
20751
  init_card_holds();
20656
- init_rules();
20657
20752
  plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
20658
20753
  level = (value) => value || "med";
20659
20754
  holdsOn = (row, open3) => heldBy({ blockers: row.blocked_by.filter((id) => open3.has(id)), questions: row.questions, status: row.status });
@@ -20889,7 +20984,7 @@ function attachDelivery(card) {
20889
20984
  card.delivery = {
20890
20985
  id: live.deliveryId,
20891
20986
  startedAt: live.startedAt,
20892
- state: deliveryState(live, openOf(card.questions).length),
20987
+ state: deliveryState(live, card.questions.length),
20893
20988
  commitMode: live.commitMode === "auto" || live.commitMode === "files" ? live.commitMode : "manual",
20894
20989
  supersedes: supersededBy(card.id, live),
20895
20990
  sessionId: session?.sessionId,
@@ -20963,7 +21058,6 @@ var init_read = __esm({
20963
21058
  "use strict";
20964
21059
  init_deliveries();
20965
21060
  init_pause();
20966
- init_rules();
20967
21061
  init_sessions();
20968
21062
  init_store();
20969
21063
  init_card_sources();
@@ -21955,7 +22049,7 @@ function buildBoardProgram(cli) {
21955
22049
  const opInOrder = ordered(questionOps);
21956
22050
  move("update-questions").argument("<id>", ID, cardId).summary("patch a card's open questions: append, rewrite, drop, skip, or clear").description(
21957
22051
  "Patch the open-question list in place. Ops apply in the order they were typed, and a position is read against the list as it stands when its op runs. Positions are 1-based. A question handed to the user always carries choices to tick \u2014 follow `akb guide update-questions`. --option, --recommended-option, --mode and --agent attach to the --append or --update before them."
21958
- ).option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove answered questions, e.g. 1 or 1,3", opInOrder("drop")).option("--skip <positions>", "mark questions skipped: kept as a record, no longer open", opInOrder("skip")).option("--unskip <positions>", "reopen skipped questions", opInOrder("unskip")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).option("--agent <name>", "the preview agent whose section the op before it is about", opInOrder("agent")).action(async function(id) {
22052
+ ).option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove answered questions, e.g. 1 or 1,3", opInOrder("drop")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).option("--agent <name>", "the preview agent whose section the op before it is about", opInOrder("agent")).action(async function(id) {
21959
22053
  await dispatch("update-questions", this, [String(id)], { ops: questionOps }, cli);
21960
22054
  });
21961
22055
  move("validate").argument("[id]", ID, cardId).summary("validate card format and report file, line, and repair instructions").description("Check one card, or every open card when no id is given. Reads only; exits non-zero with detailed errors until the format is valid.").action(async function(id) {
@@ -22253,8 +22347,10 @@ function cmdAgent(args) {
22253
22347
  return useAgent(rest);
22254
22348
  case "set":
22255
22349
  return setSetting(rest);
22350
+ case "picks":
22351
+ return setPicks(rest);
22256
22352
  default:
22257
- die(`unknown agent command "${word}" \u2014 try \`akb raw agent\`, or one of use, set`, {
22353
+ die(`unknown agent command "${word}" \u2014 try \`akb raw agent\`, or one of use, set, picks`, {
22258
22354
  kind: "unknown-move",
22259
22355
  move: word
22260
22356
  });
@@ -22326,6 +22422,27 @@ function useAgent(args) {
22326
22422
  say(`Global default runs ${harness.label} \u2014 every agent that named no runtime runs it.`);
22327
22423
  return showAgent();
22328
22424
  }
22425
+ function setPicks(args) {
22426
+ let given;
22427
+ try {
22428
+ given = JSON.parse(args[0] ?? "");
22429
+ } catch {
22430
+ die("give the picks as one JSON argument", { kind: "needs-input" });
22431
+ }
22432
+ const picks = {};
22433
+ for (const [agent, { secrets, ...row }] of Object.entries(given)) {
22434
+ if (!row.id || !harnessByName(row.harness)) die(`"${agent}" names no runtime this version runs`, { kind: "bad-value" });
22435
+ picks[agent] = { ...row, name: row.name || row.id, settings: row.settings ?? {} };
22436
+ for (const setting of harnessByName(row.harness).settings) {
22437
+ if (setting.kind !== "secret" || !setting.env) continue;
22438
+ const res2 = setSecret(secretVar(setting.env, row.id), secrets?.[setting.key] ?? "");
22439
+ if (!res2.ok) die(res2.error ?? "the key could not be saved", { kind: "save-failed" });
22440
+ }
22441
+ }
22442
+ const res = replaceAgentRuntimes(picks);
22443
+ if (!res.ok) die(res.error ?? "the picks could not be saved", { kind: "save-failed" });
22444
+ return { picks: Object.fromEntries(Object.entries(picks).map(([agent, r]) => [agent, r.id])) };
22445
+ }
22329
22446
  function namedRuntime(args) {
22330
22447
  const at = args.indexOf("--runtime");
22331
22448
  if (at < 0) return { rest: args };
@@ -22413,6 +22530,7 @@ var init_agent = __esm({
22413
22530
  init_resolve();
22414
22531
  init_roles();
22415
22532
  init_runtimes();
22533
+ init_settings();
22416
22534
  init_harnesses();
22417
22535
  init_io();
22418
22536
  init_paths();
@@ -22819,7 +22937,7 @@ var init_board3 = __esm({
22819
22937
  var card_chat_default;
22820
22938
  var init_card_chat = __esm({
22821
22939
  "src/guide/card-chat.md"() {
22822
- card_chat_default = "# Answer a card's conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print \"<change>\"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user's input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card, use `akb raw previews <agent> <id> --print`.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card's outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a workflow**: when the user asks to change a workflow or one of its agents, follow `akb guide update-workflow`.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Look up syntax**: when you need flags or argument details, use the command's `--help` or `akb help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n";
22940
+ card_chat_default = '# Answer a card\'s conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Where the task stands**: read it with `akb task show <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card, use `akb raw previews <agent> <id> --print`; never write embed tags by hand.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a workflow**: when the user asks to change a workflow or one of its agents, follow `akb guide update-workflow`.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n';
22823
22941
  }
22824
22942
  });
22825
22943
 
@@ -22827,7 +22945,7 @@ var init_card_chat = __esm({
22827
22945
  var update_workflow_default;
22828
22946
  var init_update_workflow = __esm({
22829
22947
  "src/guide/update-workflow.md"() {
22830
- update_workflow_default = "# Update a workflow\n\nChange one of this workspace's workflows so new tasks run the new version.\n\n## How a workflow works\n\nA workflow is steerable: agents do the work, and a person reviews and fine-tunes only the parts where precision matters most, so the result stays reliable.\n\n- **Previews**: usually one preview agent shows the first draft; add another only when a part needs precision and a mistake there is costly, such as a developer tool's screens. Each shows only what the person decides on, without overlapping another. With none, the card the `WORKFLOW.md` body writes is the only review.\n- **Unreviewable previews**: when the user finds a preview unneeded or cannot judge it, remove it; a land agent checks that part instead, or nobody does.\n- **Stages**: one stage by default. Add `after` only when a draft is too costly to make before another is approved, such as a video's storyboard, which waits for its script.\n- **Minimal**: when the user outlines the workflow, keep it that simple or simpler; add no review point or constraint they did not ask for, and let the trial show what else needs review.\n- **Judgment**: leave to an agent what it can judge; never add a hard rule for one case, and keep a rule only once real runs show it holds widely.\n- **Memory**: give an agent memory only where it has wide latitude and tends to err or be corrected to taste, naming those error-prone points as what it records; give a narrow agent none.\n- **Land**: everything else runs unattended after the last approval and follows the approved drafts, such as building and merging a change; leave `land` empty when the last approved preview is the deliverable.\n- **Scheduled**: repeating work runs as a scheduled agent without previews; a workflow may hold only scheduled agents.\n- **`WORKFLOW.md`**: list its agents under `previews`, `land` and `scheduled`; `description` says in one sentence what it does; `when` tells an agent which requests it is for, exceptions included; the body is how a card of this kind is written.\n- **Agents**: write each as `akb guide write-agent` says.\n\n## Versions\n\n- **Pinned**: a workflow and the agents it holds live in Cloud as numbered versions; a task\n keeps the version it started with, and only tasks started after a push take the new one.\n- **Project agents**: agents under the board's `agents/` folder are the project's own; a\n workflow may name them, but they are not part of its versions and an edit there applies to\n every card at once.\n- **Own workflows only**: only the workspace's own workflows take a new version; ask the user to\n copy a built-in or marketplace one on the web first.\n\n## Change it\n\n- **Standing preference**: when the user only wants a lasting rule for a workflow or one of its\n agents and the flow itself stays, set it with `akb workflow rule <workflow>` or\n `akb workflow instructions <agent>` instead of pushing; it reaches every task's later runs and\n works on built-in workflows too. Either replaces all of them, so run it bare first to read the\n current ones, and keep each unless the user asks to change or drop it.\n- **Direct or task**: push directly a change the user spelled out; start a Workflow builder task\n instead when the change adds, removes or restages agents, or when the user wants to see it\n work before it applies.\n- **Steps**: `akb workflow pull <id> <folder>`, edit the files there and keep what the request\n leaves alone, fix every problem `akb workflow list` reports, then `akb workflow push <folder>`.\n- **Moved on**: when push says Cloud has a newer version, pull again and redo the change.\n";
22948
+ update_workflow_default = "# Update a workflow\n\nChange one of this workspace's workflows so new tasks run the new version.\n\n## How a workflow works\n\nA workflow is steerable: agents do the work, and a person reviews and fine-tunes only the parts where precision matters most, so the result stays reliable.\n\n- **Previews**: usually one preview agent shows the first draft; add another only when a part needs precision and a mistake there is costly, such as a developer tool's screens. Each shows only what the person decides on, without overlapping another. With none, the card the `WORKFLOW.md` body writes is the only review.\n- **Unreviewable previews**: when the user finds a preview unneeded or cannot judge it, remove it; a land agent checks that part instead, or nobody does.\n- **Stages**: one stage by default. Add `after` only when a draft is too costly to make before another is approved, such as a video's storyboard, which waits for its script.\n- **Minimal**: when the user outlines the workflow, keep it that simple or simpler; add no review point or constraint they did not ask for, and let the trial show what else needs review.\n- **Judgment**: leave to an agent what it can judge; never add a hard rule for one case, and keep a rule only once real runs show it holds widely.\n- **Memory**: give an agent memory only where it has wide latitude and tends to err or be corrected to taste, naming those error-prone points as what it records; give a narrow agent none.\n- **Land**: everything else runs unattended after the last approval and follows the approved drafts, such as building and merging a change; leave `land` empty when the last approved preview is the deliverable.\n- **Scheduled**: repeating work runs as a scheduled agent without previews; a workflow may hold only scheduled agents.\n- **`WORKFLOW.md`**: list its agents under `previews`, `land` and `scheduled`; `description` says in one sentence what it does; `when` tells an agent which requests it is for, exceptions included; the body is how a card of this kind is written.\n- **Agents**: write each as `akb guide write-agent` says.\n\n## Versions\n\n- **Pinned**: a workflow and the agents it holds live in Cloud as numbered versions; a task\n keeps the version it started with, and only tasks started after a push take the new one.\n- **Project agents**: agents under the board's `agents/` folder are the project's own; a\n workflow may name them, but they are not part of its versions and an edit there applies to\n every card at once.\n- **Own workflows only**: only the workspace's own workflows take a new version; ask the user to\n copy a built-in or marketplace one on the web first.\n\n## Change it\n\n- **Standing preference**: when the user only wants a lasting rule for a workflow or one of its\n agents and the flow itself stays, set it with `akb workflow rule <workflow>` or\n `akb workflow instructions <agent>` instead of pushing; it reaches every task's later runs and\n works on built-in workflows too. Either replaces all of them, so run it bare first to read the\n current ones, and keep each unless the user asks to change or drop it.\n- **Direct or task**: push directly a change the user spelled out; start a Workflow builder task\n instead when the change adds, removes or restages agents, or when the user wants to see it\n work before it applies.\n- **Steps**: `akb workflow pull <id> <folder>`, edit the files there and keep what the request\n leaves alone, fix every problem `akb raw workflow validate <folder>` reports, then\n `akb workflow push <folder>`.\n- **Moved on**: when push says Cloud has a newer version, pull again and redo the change.\n";
22831
22949
  }
22832
22950
  });
22833
22951
 
@@ -22843,7 +22961,7 @@ var init_describe_project = __esm({
22843
22961
  var discuss_goal_default;
22844
22962
  var init_discuss_goal = __esm({
22845
22963
  "src/guide/discuss-goal.md"() {
22846
- discuss_goal_default = "# Discuss a goal\n\nThis flow only helps the user settle goals; refining, previewing, and running them come later.\n\n- **Remote user**: the user works remotely and sees only tasks and their previews, never local files.\n- **Software failures**: read `akb guide troubleshoot` when root cause analysis is needed.\n\n## Goals\n\n- **Missing information**: ask the user for information needed to form a goal.\n- **Save**: once a goal is clear, save or update it with `akb goal` (see `akb goal --help`), then stop; an existing build continues in its current session.\n- **Goal format**: each goal has a title, an outcome of at most 150 words, and a `## Done when` list of verifiable acceptance criteria, without technical design.\n- **Independent deliverables**: save separate deliverables as separate goals; remove a replaced goal with `akb goal drop --id <goal>`.\n- **Workflow**: pick the workflow from `akb workflow list` that fits the actual work; prefer the user\u2019s choice.\n- **Review points**: save through `--previews` the agents from `akb raw previews --triggers --workflow <id>` whose conditions the goal meets, always including those marked `Always`, or an empty list.\n- **Use judgment**: settle outcome decisions you can and explain them; ask only for decisions the user must make that change the result, with a recommendation.\n- **Plain words**: answer directly using everyday words.\n- **Hide machinery**: omit plans, files, paths, commands, tools, and connectors from replies; refer to actions by their button labels.\n";
22964
+ discuss_goal_default = '# Discuss a goal\n\nThis flow only helps the user settle goals; refining, previewing, and running them come later.\n\n- **Remote user**: the user works remotely and sees only tasks and their previews, never local files.\n- **Software failures**: read `akb guide troubleshoot` when root cause analysis is needed.\n\n## Goals\n\n- **Missing information**: ask the user for information needed to form a goal.\n- **Save**: once a goal is clear, save or update it with `akb goal` (see `akb goal --help`), then stop; an existing build continues in its current session.\n- **Goal format**: each goal has a title, an outcome of at most 150 words, and a `## Done when` list of verifiable acceptance criteria, without technical design.\n- **Independent deliverables**: save separate deliverables as separate goals; remove a replaced goal with `akb goal drop --id <goal>`.\n- **Workflow**: pick the workflow from `akb workflow list` that fits the actual work; prefer the user\u2019s choice.\n- **Review points**: save through `--previews` the agents from `akb raw previews --triggers --workflow <id>` whose conditions the goal meets, always including those marked `Always`, or an empty list.\n- **Use judgment**: settle outcome decisions you can and explain them; ask only for decisions the user must make that change the result, with a recommendation.\n- **Plain words**: answer directly using everyday words.\n- **Hide machinery**: omit plans, files, paths, commands, tools, and connectors from replies; refer to actions by their button labels.\n- **Starting a goal**: "Start now" (\u7ACB\u5373\u5F00\u59CB) begins the work directly; "Refine goal" (\u7EC6\u5316\u76EE\u6807) appears only when the goal has review points, and shows their previews for approval first.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n';
22847
22965
  }
22848
22966
  });
22849
22967
 
@@ -22939,7 +23057,7 @@ var init_preview_agent = __esm({
22939
23057
  var update_questions_default;
22940
23058
  var init_update_questions = __esm({
22941
23059
  "src/guide/update-questions.md"() {
22942
- update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a workflow\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`), and one marked\n `skipped: true` \u2014 the user declined to answer it, which grants nothing.\n\n```text\nakb raw update-questions <id> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n';
23060
+ update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a workflow\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`).\n\n```text\nakb raw update-questions <id> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n';
22943
23061
  }
22944
23062
  });
22945
23063
 
@@ -23128,6 +23246,26 @@ function cmdWorkflowDiagram(id, card) {
23128
23246
  say(tag);
23129
23247
  return { file, tag, diagram };
23130
23248
  }
23249
+ function cmdWorkflowValidate(folder) {
23250
+ const dir = path76.resolve(folder);
23251
+ if (!fs75.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder} is not a folder`, "bad-args");
23252
+ const files = readWorkflowFolder(dir);
23253
+ const read3 = parseWorkflowFile("workflow", files[WORKFLOW_FILE] ?? "", WORKFLOW_FILE);
23254
+ const def = "def" in read3 ? read3.def : null;
23255
+ const named2 = def ? new Set([...def.previews, ...def.land, ...def.scheduled].map((h) => h.agent)) : [];
23256
+ for (const name of named2) {
23257
+ if (Object.keys(files).some((f) => f.startsWith(`agents/${name}/`))) continue;
23258
+ const agent = findSpecAgent(name);
23259
+ for (const file of agent ? ["AGENT.md", ...agent.files] : []) {
23260
+ const text4 = agent.file(file);
23261
+ if (text4 !== null) files[`agents/${name}/${file}`] = text4;
23262
+ }
23263
+ }
23264
+ const problems = workflowFilesProblems(files).map((p) => `${p.file} ${p.reason}`);
23265
+ if (problems.length) die(problems.map((p) => `! ${p}`).join("\n"), { kind: "workflow-problems", bare: true, problems });
23266
+ say(`${folder}: no problems`);
23267
+ return { folder: dir, problems };
23268
+ }
23131
23269
  async function cmdWorkflowPull(id, folder) {
23132
23270
  const cloudId = cloudIdOf(id);
23133
23271
  if (!cloudId) found(id);
@@ -23158,8 +23296,10 @@ async function cmdWorkflowPush(folder, opts) {
23158
23296
  const id = workflowName(cloudId);
23159
23297
  const readOnly2 = () => die(`${id} is not this workspace's own; copy it on the web first.`, "workflow-read-only");
23160
23298
  if (cloudId.startsWith("wf_builtin_")) readOnly2();
23161
- const checked = checkWorkflowFiles(readWorkflowFolder(dir));
23162
- if (!checked.ok) die(`${checked.file} ${checked.reason}`, "bad-workflow");
23299
+ const read3 = readWorkflowFolder(dir);
23300
+ const problems = workflowFilesProblems(read3).map((p) => `${p.file} ${p.reason}`);
23301
+ if (problems.length) die(problems.map((p) => `! ${p}`).join("\n"), { kind: "bad-workflow", bare: true, problems });
23302
+ const checked = checkWorkflowFiles(read3);
23163
23303
  const { files } = checked;
23164
23304
  const now = await call("GET", `/v1/workflows/${encodeURIComponent(cloudId)}`);
23165
23305
  if (!now.ok) die(now.error, now.code === "not_found" ? "no-such-workflow" : "cloud-refused");
@@ -23264,6 +23404,7 @@ var init_workflow2 = __esm({
23264
23404
  init_workflows();
23265
23405
  init_workflow_folder();
23266
23406
  init_workflow_files();
23407
+ init_workflow_def();
23267
23408
  init_board_files();
23268
23409
  init_tasks();
23269
23410
  found = (id) => {
@@ -23416,7 +23557,7 @@ function approvalRequest(req) {
23416
23557
  const id = req.id;
23417
23558
  const card = id === void 0 ? null : findCard(id);
23418
23559
  if (!card) return { error: `task #${id} does not exist` };
23419
- if (openOf(card.questions).length) return { error: `#${card.id} has open questions \u2014 answer them before approving it.` };
23560
+ if (card.questions.length) return { error: `#${card.id} has open questions \u2014 answer them before approving it.` };
23420
23561
  if (readRuns().some((r) => r.status === "running" && r.cardId === card.id && holdsCard(r.action))) {
23421
23562
  return { error: `#${card.id} has a run in flight \u2014 approve once it ends.` };
23422
23563
  }
@@ -23902,12 +24043,11 @@ function notesField(card) {
23902
24043
  );
23903
24044
  }
23904
24045
  function questionsField(meta) {
23905
- const open3 = openOf(meta.questions).length;
23906
24046
  if (!meta.questions.length) return field("questions", "none open");
23907
24047
  const lines = meta.questions.map(
23908
- (q, i) => `${i + 1}. ${q.skipped ? "(skipped by the user \u2014 leave it) " : ""}${q.text}${q.options?.length ? ` (${q.options.length} options)` : ""}`
24048
+ (q, i) => `${i + 1}. ${q.text}${q.options?.length ? ` (${q.options.length} options)` : ""}`
23909
24049
  );
23910
- return field("questions", [`${open3} open:`, ...lines.map((s) => ` ${s}`)]);
24050
+ return field("questions", [`${meta.questions.length} open:`, ...lines.map((s) => ` ${s}`)]);
23911
24051
  }
23912
24052
  function stageField(meta) {
23913
24053
  const flow = workflowFor(meta.workflow);
@@ -23968,7 +24108,7 @@ function buildFlow(req, program2) {
23968
24108
  `write the shipped line in the memory file above \u2014 \`akb guide archive\``,
23969
24109
  delivery ? `${self} raw delivery complete ${delivery.deliveryId} \u2014 finish your step and follow its handoff; software steps in a git project supply --commit <full-sha> --branch <target>` : `${raw} archive ${req.id} \u2014 once every box is ticked and the card's goal is met`
23970
24110
  );
23971
- if (openOf(card.meta.questions).length) {
24111
+ if (card.meta.questions.length) {
23972
24112
  next.push(
23973
24113
  `${self} raw card resolve ${req.id} --print \u2014 first: the card has open questions, and building on a guess is what they are there to stop`
23974
24114
  );
@@ -24198,7 +24338,6 @@ var init_flow = __esm({
24198
24338
  init_dismissal_review();
24199
24339
  init_prompts();
24200
24340
  init_rules2();
24201
- init_rules();
24202
24341
  init_workflows();
24203
24342
  init_types();
24204
24343
  init_env();
@@ -24314,7 +24453,7 @@ function refinementRequest(req) {
24314
24453
  if (!card) return { error: `task #${req.id} does not exist` };
24315
24454
  const step = refinementStep(card);
24316
24455
  if (step === "done") {
24317
- const waiting = openOf(card.questions).length > 0 && canRefine({ ...card, questions: [] });
24456
+ const waiting = card.questions.length > 0 && canRefine({ ...card, questions: [] });
24318
24457
  return {
24319
24458
  error: waiting ? `#${card.id} is waiting for the user to answer its open questions, so there is nothing to refine yet \u2014 the board refines it on its own once they are answered.` : `a refine would not move #${card.id}`
24320
24459
  };
@@ -24328,7 +24467,7 @@ async function startRefinement(req) {
24328
24467
  function refinementAfter(action, cardId2, flowId) {
24329
24468
  const card = currentCard(cardId2);
24330
24469
  if (!card || card.openBlockers.length > 0) return null;
24331
- if (openOf(card.questions).length > 0 || action === "clarify" || card.deliversIn !== "plan") return null;
24470
+ if (card.questions.length > 0 || action === "clarify" || card.deliversIn !== "plan") return null;
24332
24471
  if (planDeliveryGap(card) === null) return null;
24333
24472
  if (awaitingApproval(card)) return null;
24334
24473
  return { action: "clarify", id: card.id, title: card.title, refineRound: 1, ...flowId ? { flowId } : {} };
@@ -24355,7 +24494,7 @@ function stalledLine(cardId2, next) {
24355
24494
  function planStageEnd(run2) {
24356
24495
  if (run2.cardId === null || stageOfAction(run2.action) !== "plan") return null;
24357
24496
  const card = currentCard(run2.cardId);
24358
- if (!card || card.openBlockers.length > 0 || openOf(card.questions).length > 0) return null;
24497
+ if (!card || card.openBlockers.length > 0 || card.questions.length > 0) return null;
24359
24498
  if (refinementStep(card) !== "done") return null;
24360
24499
  return endOfStage(stageContract("plan"), card);
24361
24500
  }
@@ -24839,7 +24978,7 @@ async function watchRun(sessionId, resume = startResume) {
24839
24978
  const totals = reportsSessionTotal(record.harness);
24840
24979
  const sessionTotal = totals ? reported : void 0;
24841
24980
  const carriedId = record.continues?.resumeId;
24842
- const totalFrom = !totals ? void 0 : record.resumedFrom ? record.sessionCostFrom : carriedId ? lastSessionTotal(carriedId, readRuns()) : void 0;
24981
+ const totalFrom = !totals ? void 0 : record.resumedFrom ? record.sessionCostFrom : carriedId ? record.sessionCostFrom ?? lastSessionTotal(carriedId, readRuns()) : void 0;
24843
24982
  const totalCost = sessionTotal === void 0 ? reported : ownCost(sessionTotal, totalFrom);
24844
24983
  const usage3 = spoken ? spoken.usage : renderer?.usage?.();
24845
24984
  if (spoken) gotContext(spoken.context);
@@ -25304,7 +25443,7 @@ function sayBeforeStart(req, program2) {
25304
25443
  if (blockers.length) {
25305
25444
  say(`#${req.id} is blocked by ${blockers.map((b) => `#${b.id} ${b.title}`).join(", ")} \u2014 starting anyway.`);
25306
25445
  }
25307
- const asked = openOf(card?.questions ?? []).length;
25446
+ const asked = card?.questions.length ?? 0;
25308
25447
  if (req.action === "implement" && asked) {
25309
25448
  say(
25310
25449
  `#${req.id} has ${asked} open question${asked === 1 ? "" : "s"} \u2014 it is built, then holds at landing until ${asked === 1 ? "it is" : "they are"} answered. Answer first with \`${program2} raw card resolve ${req.id}\`.`
@@ -25336,7 +25475,13 @@ function readRequest(action, args, opts) {
25336
25475
  req.notes = words(1);
25337
25476
  if (action === "implement") req.runtime = opts.runtime;
25338
25477
  if (opts.session || opts.transcript) {
25339
- req.carry = { resumeId: opts.session, fork: opts.session ? opts.fork === true : void 0, transcript: opts.transcript };
25478
+ const costFrom = Number(process.env[SESSION_COST_ENV]);
25479
+ req.carry = {
25480
+ resumeId: opts.session,
25481
+ fork: opts.session ? opts.fork === true : void 0,
25482
+ transcript: opts.transcript,
25483
+ ...opts.session && costFrom > 0 ? { costFrom } : {}
25484
+ };
25340
25485
  }
25341
25486
  return { req, follow: follow2, print };
25342
25487
  }
@@ -25690,6 +25835,7 @@ var init_run = __esm({
25690
25835
  init_deliveries();
25691
25836
  init_pause();
25692
25837
  init_flow();
25838
+ init_env();
25693
25839
  init_memory_review();
25694
25840
  init_log();
25695
25841
  init_approve();
@@ -26092,7 +26238,10 @@ List trigger conditions: ${raw} previews --triggers --json`).action(async functi
26092
26238
  useBoard(resolveBoard("components", { board: ctx.board, dir: ctx.dir, cwd: cli.cwd, installHint: cli.installHint }), ctx.dir !== null);
26093
26239
  await boardless(this, cli, () => cmdComponents(this.opts()));
26094
26240
  });
26095
- const workflow = noun("workflow", "rename a workflow draft, or draw a workflow's diagram, inside a run");
26241
+ const workflow = noun("workflow", "check a workflow folder, or rename a draft or draw a diagram inside a run");
26242
+ withShared(workflow.command("validate")).argument("<folder>", "a workflow folder: WORKFLOW.md and agents/").summary("report every problem in a workflow folder; agents it names but lacks are read from the board").action(async function(folder) {
26243
+ await onBoard2(this, cli, () => cmdWorkflowValidate(folder));
26244
+ });
26096
26245
  withShared(workflow.command("rename")).argument("<id>", "the draft, from `workflow list`").argument("<name...>", "what to call it now").summary("rename the Workflow builder draft. Only inside that task's run.").action(async function(id, name) {
26097
26246
  await onBoard2(this, cli, () => cmdWorkflowRename(id, name.join(" ")));
26098
26247
  });
@@ -26102,7 +26251,7 @@ List trigger conditions: ${raw} previews --triggers --json`).action(async functi
26102
26251
  }
26103
26252
  function declareRuns(program2, cli) {
26104
26253
  const ON_WEB = "Reads and writes WildCrane Cloud as the signed-in account; changes show on the web at once.";
26105
- const task = withShared(program2.command("task")).summary("list, create, approve, change and remove WildCrane tasks").description(`${ON_WEB} <task> is WC-12, task_\u2026, or just 12 in a linked folder.`).action(function() {
26254
+ const task = withShared(program2.command("task")).summary("see where WildCrane tasks stand; list, create, approve, stop, resume and remove them").description(`${ON_WEB} <task> is WC-12, task_\u2026, or just 12 in a linked folder.`).action(function() {
26106
26255
  this.help();
26107
26256
  });
26108
26257
  withShared(task.command("list")).summary("list tasks").option("--project <id>", "the project; default: this folder\u2019s linked one").option("--workspace <id>", "every project of a workspace").option("--status <status>", "queued, running, waiting_review, done, failed, cancelled or stopped").action(async function() {
@@ -26117,6 +26266,11 @@ function declareRuns(program2, cli) {
26117
26266
  withShared(task.command("approve")).argument("<task>").summary("approve the current review point").option("--comment <text>", "a note with the approval").action(async function(id) {
26118
26267
  await boardless(this, cli, () => taskApprove(id, this.opts().comment));
26119
26268
  });
26269
+ const questionOps = [];
26270
+ const opInOrder = ordered(questionOps);
26271
+ withShared(task.command("update-questions")).argument("<task>").summary("edit the task's open questions, like `raw update-questions`").description("Positions are 1-based, in the order of the card\u2019s `questions:` (`akb task show`). --option, --recommended-option, --mode and --agent attach to the --append or --update before them.").option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove questions, e.g. 1 or 1,3", opInOrder("drop")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).option("--agent <name>", "the preview agent whose section the op before it is about", opInOrder("agent")).action(async function(id) {
26272
+ await boardless(this, cli, () => taskUpdateQuestions(id, questionOps));
26273
+ });
26120
26274
  withShared(task.command("chat")).argument("<task>").argument("<message...>").summary("send a message in the task chat, e.g. to change its requirement or draft").action(async function(id, message) {
26121
26275
  await boardless(this, cli, () => taskChat(id, message.join(" ")));
26122
26276
  });