@nathanstephenson/flow 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,66 @@
1
+ /**
2
+ * How much of the Conversation Context is spent, as one short chrome label.
3
+ *
4
+ * The two front-ends had drifted on the wording — the TUI said `context 12%` and the web UI said
5
+ * `12% context` for the same numbers. The TUI's wording wins because it reads as a label rather than
6
+ * as a sentence fragment, and because it is the one with tests.
7
+ */
8
+ export function contextUsageLabel(usage) {
9
+ if (!usage)
10
+ return undefined;
11
+ const { used, window } = usage;
12
+ // A window of zero means the backend reports spend but not a budget, so a percentage would lie.
13
+ return window > 0 ? `context ${Math.round((used / window) * 100)}%` : `${used} tokens`;
14
+ }
15
+ export function contextUsageDetail(usage) {
16
+ if (!usage || usage.window <= 0)
17
+ return undefined;
18
+ const { used, window, spend } = usage;
19
+ const rows = [
20
+ {
21
+ label: "Context",
22
+ value: `${Math.round((used / window) * 100)}% · ${compactTokens(used)}/${compactTokens(window)} tokens`,
23
+ },
24
+ ];
25
+ // Absent whenever the backend cannot report it, rather than shown as a zero that reads as "free".
26
+ if (!spend)
27
+ return rows;
28
+ rows.push({ label: "Spent", value: `${compactTokens(spend.tokens)} tokens · ${money(spend.costUSD)}` });
29
+ // Stated as a share of the total, because the bare figure invites reading it as extra spend on top
30
+ // rather than as the majority of what is already counted above.
31
+ rows.push({ label: "Cache reads", value: `${compactTokens(spend.cached)} of ${compactTokens(spend.tokens)}` });
32
+ // One model is what `Spent` already says, so the breakdown earns its space only when it splits.
33
+ // Two or more means a Subagent ran on its own model, which is the case worth seeing.
34
+ if (spend.models.length > 1) {
35
+ for (const model of spend.models) {
36
+ rows.push({ label: model.id, value: `${compactTokens(model.tokens)} · ${money(model.costUSD)}`, model: true });
37
+ }
38
+ }
39
+ return rows;
40
+ }
41
+ /**
42
+ * Enough places to stay honest at both ends: a Subagent on a cheap model can cost a tenth of a
43
+ * cent, and rounding that to `$0.00` would report free work. Anything at or above a cent reads in
44
+ * the two places money is normally written.
45
+ */
46
+ function money(usd) {
47
+ if (usd >= 0.01)
48
+ return `$${usd.toFixed(2)}`;
49
+ if (usd === 0)
50
+ return "$0.00";
51
+ return `$${usd.toFixed(4)}`;
52
+ }
53
+ /**
54
+ * Hand-rolled rather than `Intl`, to match `relativeTime` and to read the same in a terminal.
55
+ *
56
+ * Exported for `reduce.ts`, which writes the same token counts into a compaction marker's label. The
57
+ * import goes that way and not this one at runtime: this module takes only `ViewState`, as a type,
58
+ * so there is no cycle to worry about.
59
+ */
60
+ export function compactTokens(count) {
61
+ if (count >= 1_000_000)
62
+ return `${Math.round(count / 100_000) / 10}M`;
63
+ if (count >= 1_000)
64
+ return `${Math.round(count / 1_000)}k`;
65
+ return `${count}`;
66
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Turning a file-editing tool call into something readable.
3
+ *
4
+ * Shared with the browser the same way the reducer is: types only, so stripping leaves standalone
5
+ * ESM. Kept out of the DOM so it can be tested directly.
6
+ */
7
+ /**
8
+ * Recognises the file-editing tools whose output people actually read. Claude's Edit carries
9
+ * `old_string`/`new_string`; Write carries `content` with nothing removed.
10
+ */
11
+ export function editDiff(input) {
12
+ if (!input || typeof input !== "object")
13
+ return undefined;
14
+ const record = input;
15
+ const before = typeof record["old_string"] === "string" ? record["old_string"] : undefined;
16
+ const after = typeof record["new_string"] === "string"
17
+ ? record["new_string"]
18
+ : typeof record["content"] === "string"
19
+ ? record["content"]
20
+ : undefined;
21
+ if (before === undefined && after === undefined)
22
+ return undefined;
23
+ return {
24
+ ...(typeof record["file_path"] === "string" ? { path: record["file_path"] } : {}),
25
+ removed: lines(before),
26
+ added: lines(after),
27
+ };
28
+ }
29
+ function lines(text) {
30
+ if (!text)
31
+ return [];
32
+ const split = text.split("\n");
33
+ while (split.length > 0 && split[split.length - 1] === "")
34
+ split.pop();
35
+ return split;
36
+ }
@@ -0,0 +1,105 @@
1
+ export function startAnswering(questions) {
2
+ return { index: 0, cursor: 0, chosen: questions.map(() => []) };
3
+ }
4
+ /**
5
+ * The rows for one Question, given whatever is currently typed in the box.
6
+ *
7
+ * The Other row exists only while there is text, and is always last. Appending rather than
8
+ * prepending keeps the digits stable: `1` is the first Option whether or not anyone has started
9
+ * typing, so a number read off the screen a moment ago still means what it meant.
10
+ */
11
+ export function rowsFor(question, other) {
12
+ const rows = question.options.map((option) => ({
13
+ label: option.label,
14
+ ...(option.description === undefined ? {} : { description: option.description }),
15
+ other: false,
16
+ }));
17
+ const typed = other.trim();
18
+ if (typed !== "")
19
+ rows.push({ label: typed, description: "your own answer", other: true });
20
+ return rows;
21
+ }
22
+ /** Where the cursor lands after moving by `delta`, wrapping. Guarded against an empty list. */
23
+ export function cursorAfter(current, delta, rows) {
24
+ if (rows <= 0)
25
+ return 0;
26
+ return (((current + delta) % rows) + rows) % rows;
27
+ }
28
+ /** Where the cursor lands after moving by `delta`, clamped — the TUI's idiom, as every list there clamps. */
29
+ export function cursorClamped(current, delta, rows) {
30
+ if (rows <= 0)
31
+ return 0;
32
+ return Math.min(rows - 1, Math.max(0, current + delta));
33
+ }
34
+ /**
35
+ * Where the cursor goes when the box gains or loses its first character.
36
+ *
37
+ * This exists because of a trap, and the trap is worth stating: type an answer nobody offered, press
38
+ * Enter, and without this the Option the cursor happened to be resting on is what gets sent. The
39
+ * human's own words are discarded in favour of a choice they never made — silently, and into a
40
+ * decision they were asked to make.
41
+ *
42
+ * So the cursor follows the typing onto the Other row, and comes back off it when the text goes
43
+ * away. Once there, an arrow key may move it off again, and it stays where it is put: someone who
44
+ * types a note and *then* picks an Option meant to pick the Option.
45
+ */
46
+ export function cursorAfterTyping(current, hadText, hasText, rows) {
47
+ if (hasText && !hadText)
48
+ return Math.max(0, rows - 1);
49
+ // The Other row has just gone; the cursor was on it and now points past the end.
50
+ if (!hasText && hadText)
51
+ return Math.min(current, Math.max(0, rows - 1));
52
+ return current;
53
+ }
54
+ /** A label added or removed. Order is preserved so answers read in the order they were picked. */
55
+ export function toggled(chosen, label) {
56
+ return chosen.includes(label) ? chosen.filter((seen) => seen !== label) : [...chosen, label];
57
+ }
58
+ /**
59
+ * Whether the current Question can be answered as it stands.
60
+ *
61
+ * False whenever nothing has been selected. Single-select questions normally have a row under the
62
+ * cursor, but an empty options list does not; it must not advance the UI with an answer the host
63
+ * will reject.
64
+ */
65
+ export function canCommit(_question, chosen) {
66
+ return chosen.length > 0;
67
+ }
68
+ /**
69
+ * The Answers for an Enquiry, ready for the `answer_enquiry` command.
70
+ *
71
+ * One entry per Question, always — the backend holds a single promise for the whole tool call, and
72
+ * the host refuses an answer of the wrong arity rather than letting a short one through as consent.
73
+ */
74
+ export function answersOf(state, questions) {
75
+ return questions.map((_, index) => [...(state.chosen[index] ?? [])]);
76
+ }
77
+ /** Whether every Question has been answered and the Enquiry is ready to send. */
78
+ export function isFinished(state, questions) {
79
+ return state.index >= questions.length;
80
+ }
81
+ /**
82
+ * How far through an Enquiry the human is, or undefined for one with a single Question.
83
+ *
84
+ * Undefined rather than `"1 of 1"`, so the caller's decision is *is there a row to show* rather than
85
+ * whether to compare two numbers — the idiom `subagentStripLabel` already uses.
86
+ */
87
+ export function progressLabel(state, questions) {
88
+ return questions.length > 1 ? `${state.index + 1} of ${questions.length}` : undefined;
89
+ }
90
+ /**
91
+ * One line per Question: what was asked, and what was chosen.
92
+ *
93
+ * The whole requirement of the transcript row, in one function. A reader scrolling back to an
94
+ * answered Enquiry wants both halves and gets neither from a JSON well — and cannot get them from
95
+ * the tool result either, which the SDK writes as prose.
96
+ *
97
+ * The header rather than the question, because this is a list and four full sentences with their
98
+ * answers appended is not one anybody reads.
99
+ */
100
+ export function answerLines(questions, answers) {
101
+ return questions.map((question, index) => {
102
+ const chosen = answers?.[index] ?? [];
103
+ return `${question.header} — ${chosen.length === 0 ? "no answer" : chosen.join(", ")}`;
104
+ });
105
+ }
@@ -0,0 +1,192 @@
1
+ import { marked } from "marked";
2
+ export function parseMarkdown(text, options = {}) {
3
+ if (text === "")
4
+ return [];
5
+ try {
6
+ return toBlocks(marked.lexer(text), options);
7
+ }
8
+ catch {
9
+ // A throw here happens during a React render, where it would take down the whole pane rather
10
+ // than one Entry. Half a markdown document is exactly what streaming produces, so the input this
11
+ // runs on is never known-good; showing the source is always better than showing nothing.
12
+ return [{ kind: "paragraph", inlines: [{ kind: "text", text }] }];
13
+ }
14
+ }
15
+ /**
16
+ * The schemes a transcript will turn into an anchor. Everything else — `javascript:`, `data:`, a
17
+ * relative path with no base to resolve against — falls back to rendering the link's own source, so
18
+ * the reader sees where it pointed instead of a label hiding it.
19
+ */
20
+ const SAFE_SCHEMES = new Set(["http:", "https:", "mailto:"]);
21
+ export function safeHref(href) {
22
+ try {
23
+ // The original string is returned rather than `url.href`, so the anchor points at what the model
24
+ // actually wrote instead of the URL parser's normalisation of it.
25
+ return SAFE_SCHEMES.has(new URL(href).protocol) ? href : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ const HEADING_LEVELS = [1, 2, 3, 4, 5, 6];
32
+ function toBlocks(tokens, options) {
33
+ return tokens.flatMap((token) => toBlock(token, options));
34
+ }
35
+ /**
36
+ * marked's `Token` union carries a `Tokens.Generic` member with a string index signature, so
37
+ * narrowing on `.type` leaves every branch as `X | Generic` and neither a cast nor an `in` check can
38
+ * be avoided. The lexer does emit the documented shape for each `type`, so the casts below are where
39
+ * that is asserted once — deliberately at the boundary, so nothing past this module has to.
40
+ */
41
+ function toBlock(token, options) {
42
+ switch (token.type) {
43
+ case "space":
44
+ return [];
45
+ case "heading":
46
+ return [
47
+ { kind: "heading", level: HEADING_LEVELS[token.depth - 1] ?? 6, inlines: toInlines(token.tokens, options) ?? [] },
48
+ ];
49
+ case "paragraph":
50
+ return [{ kind: "paragraph", inlines: toInlines(token.tokens, options) ?? [] }];
51
+ // At block position a `text` token is a paragraph that marked did not wrap — which is what every
52
+ // item of a tight list is made of.
53
+ case "text":
54
+ return [{ kind: "paragraph", inlines: toInlines(token.tokens, options) ?? verbatim(token) }];
55
+ case "code":
56
+ return [{ kind: "code", text: token.text, ...(token.lang ? { lang: token.lang } : {}) }];
57
+ case "blockquote":
58
+ return [{ kind: "quote", blocks: toBlocks(token.tokens ?? [], options) }];
59
+ case "hr":
60
+ return [{ kind: "rule" }];
61
+ case "list":
62
+ return [toList(token, options)];
63
+ case "table":
64
+ return [toTable(token, options)];
65
+ case "html":
66
+ return [{ kind: "paragraph", inlines: htmlImages(token.raw, options) }];
67
+ default:
68
+ return [{ kind: "paragraph", inlines: verbatim(token) }];
69
+ }
70
+ }
71
+ function toList(token, options) {
72
+ // `start` is `""` on an unordered list and `1` on an ordered one that did not ask for anything
73
+ // else; neither is worth carrying, and `exactOptionalPropertyTypes` means the key is spread in
74
+ // rather than set to undefined.
75
+ const start = token.ordered && typeof token.start === "number" && token.start !== 1 ? token.start : undefined;
76
+ return {
77
+ kind: "list",
78
+ ordered: token.ordered,
79
+ items: token.items.map((item) => toListItem(item, options)),
80
+ ...(start === undefined ? {} : { start }),
81
+ };
82
+ }
83
+ /**
84
+ * A task list's checkbox arrives as its own block-level token ahead of the item's text. Rendered as
85
+ * a block it would sit on a line of its own, so the marker is folded into the item's first
86
+ * paragraph — and it is written as the `[x]` the model typed rather than a glyph invented here.
87
+ */
88
+ function toListItem(item, options) {
89
+ const blocks = toBlocks(item.tokens.filter((token) => token.type !== "checkbox"), options);
90
+ if (!item.task)
91
+ return blocks;
92
+ const marker = { kind: "text", text: item.checked ? "[x] " : "[ ] " };
93
+ const [first, ...rest] = blocks;
94
+ return first?.kind === "paragraph"
95
+ ? [{ kind: "paragraph", inlines: [marker, ...first.inlines] }, ...rest]
96
+ : [{ kind: "paragraph", inlines: [marker] }, ...blocks];
97
+ }
98
+ function toTable(token, options) {
99
+ const cells = (row) => row.map((cell) => toInlines(cell.tokens, options) ?? []);
100
+ return {
101
+ kind: "table",
102
+ header: cells(token.header),
103
+ rows: token.rows.map(cells),
104
+ align: token.align.map((align) => align ?? undefined),
105
+ };
106
+ }
107
+ function toInlines(tokens, options) {
108
+ return tokens?.flatMap((token) => toInline(token, options));
109
+ }
110
+ function toInline(token, options) {
111
+ switch (token.type) {
112
+ // A `text` token carrying its own tokens is a nested run, not a leaf — the shape a list item's
113
+ // text and an autolink's label both take.
114
+ case "text":
115
+ return toInlines(token.tokens, options) ?? [{ kind: "text", text: token.text }];
116
+ case "escape":
117
+ return [{ kind: "text", text: token.text }];
118
+ case "strong":
119
+ case "em":
120
+ case "del":
121
+ return [{ kind: token.type, inlines: toInlines(token.tokens, options) ?? [] }];
122
+ case "codespan":
123
+ return [{ kind: "code", text: token.text }];
124
+ case "br":
125
+ return [{ kind: "break" }];
126
+ case "link":
127
+ return [toLink(token, options)];
128
+ case "image":
129
+ return [toImage(token.href, token.text, token.raw, options)];
130
+ // Raw HTML the model emitted, inline or as a block, is text. This is the whole reason the lexer
131
+ // is used without the parser: there is no path here by which `<script>` becomes a script.
132
+ case "html":
133
+ return htmlImages(token.text, options);
134
+ default:
135
+ return verbatim(token);
136
+ }
137
+ }
138
+ function toLink(token, options) {
139
+ const href = resolveHref(token.href, options.linkBase);
140
+ return href === undefined
141
+ ? { kind: "text", text: token.raw }
142
+ : { kind: "link", href, inlines: toInlines(token.tokens, options) ?? [{ kind: "text", text: token.text }] };
143
+ }
144
+ function resolveHref(href, base) {
145
+ if (!base)
146
+ return safeHref(href);
147
+ try {
148
+ return safeHref(new URL(href, base).href);
149
+ }
150
+ catch {
151
+ return undefined;
152
+ }
153
+ }
154
+ function toImage(href, alt, raw, options) {
155
+ const src = options.images && href.trim() ? resolveHref(href, options.imageBase) : undefined;
156
+ if (!src || !/^https?:\/\//i.test(src))
157
+ return { kind: "text", text: raw };
158
+ const url = new URL(src);
159
+ const blob = /^\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(url.pathname);
160
+ if (url.hostname === "github.com" && blob) {
161
+ url.hostname = "raw.githubusercontent.com";
162
+ url.pathname = `/${blob[1]}/${blob[2]}/${blob[3]}`;
163
+ }
164
+ return { kind: "image", src: url.href, alt };
165
+ }
166
+ function htmlImages(text, options) {
167
+ const tags = text.match(/<img\b(?:[^"'<>]|"[^"]*"|'[^']*')*\/?>/gi);
168
+ if (!options.images || !tags || tags.join("").replace(/\s/g, "") !== text.replace(/\s/g, ""))
169
+ return [{ kind: "text", text }];
170
+ return tags.map((tag) => {
171
+ const attrs = new Map();
172
+ for (const match of tag.slice(4, -1).matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
173
+ const name = match[1].toLowerCase();
174
+ if (!attrs.has(name))
175
+ attrs.set(name, decodeAttribute(match[2] ?? match[3] ?? match[4] ?? ""));
176
+ }
177
+ return toImage(attrs.get("src") ?? "", attrs.get("alt") ?? "Screenshot", tag, options);
178
+ });
179
+ }
180
+ function decodeAttribute(value) {
181
+ const named = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">" };
182
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|quot|apos|lt|gt);/gi, (raw, entity) => {
183
+ if (!entity.startsWith("#"))
184
+ return named[entity.toLowerCase()] ?? raw;
185
+ const number = entity[1]?.toLowerCase() === "x" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
186
+ return number > 0 && number <= 0x10ffff ? String.fromCodePoint(number) : raw;
187
+ });
188
+ }
189
+ /** A construct this module does not model, shown as the source the model wrote. */
190
+ function verbatim(token) {
191
+ return [{ kind: "text", text: token.raw }];
192
+ }
@@ -0,0 +1,32 @@
1
+ /** Models grouped by provider. Claude offers one group, pi offers dozens; the list is the same. */
2
+ export function modelChoices(capabilities) {
3
+ return modelChoicesOf(capabilities?.models);
4
+ }
5
+ /**
6
+ * The same grouping, from a bare list.
7
+ *
8
+ * `Capabilities` is how a model list arrives inside an Agent Session, and `GET /api/models` is how
9
+ * it arrives before there is one (ADR 0020) — the New Agent Session view reads the second. Only
10
+ * `.models` was ever used here, so taking the list is the whole of the generalisation, and
11
+ * `modelChoices` keeps its signature so the TUI is untouched.
12
+ */
13
+ export function modelChoicesOf(models) {
14
+ if (!models)
15
+ return [];
16
+ const byProvider = new Map();
17
+ for (const model of models) {
18
+ const provider = model.provider ?? "other";
19
+ byProvider.set(provider, [...(byProvider.get(provider) ?? []), model]);
20
+ }
21
+ return [...byProvider.entries()]
22
+ .sort(([left], [right]) => left.localeCompare(right))
23
+ .flatMap(([provider, models]) => models.map((model) => ({ provider, model })));
24
+ }
25
+ /**
26
+ * The Effort levels on offer, which belong to the model in force rather than to the session — a
27
+ * model without an effort control returns none and the picker has nothing to show.
28
+ */
29
+ export function effortChoices(view) {
30
+ const current = view.capabilities?.models.find((model) => model.id === view.model?.id);
31
+ return (current ?? view.model)?.effortLevels ?? [];
32
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The three choices, in the order both front-ends present them.
3
+ *
4
+ * Allow first because it is the common answer, and Always last for the reason it is not merely the
5
+ * boldest: it is the one with an effect outside this turn, and a list that put it second would invite
6
+ * a reader skimming downwards to take it for a stronger Allow.
7
+ *
8
+ * **"on this machine" is load-bearing in that label, not decoration.** The Settings are machine-wide
9
+ * (src/protocol/settings.ts), and the hazard that file names is precisely this one — a browser window
10
+ * showing one Scope, inviting a decision that is not scoped to it. Someone clicking Always in a
11
+ * window titled with one project will otherwise read it as "in this project".
12
+ */
13
+ export const PERMISSION_CHOICES = [
14
+ {
15
+ decision: "allow",
16
+ label: "Allow once",
17
+ description: "Run it this time, and ask again next time.",
18
+ },
19
+ {
20
+ decision: "deny",
21
+ label: "Deny",
22
+ description: "Refuse it, and stop asking for the rest of this turn.",
23
+ },
24
+ {
25
+ decision: "always",
26
+ label: "Always allow on this machine",
27
+ description: "Run it, and never ask again in any Agent Session. Revocable in Settings.",
28
+ },
29
+ ];
30
+ // Permission controls are rendered and navigated on every TUI key event. Keep the fixed narrowed
31
+ // view beside the source choices rather than allocating and scanning the same list in that hot path.
32
+ const ONE_SHOT_PERMISSION_CHOICES = PERMISSION_CHOICES.slice(0, 2);
33
+ /** The same shared controls, narrowed for requests whose scope can never become standing. */
34
+ export function permissionChoices(allowAlways) {
35
+ return allowAlways === false ? ONE_SHOT_PERMISSION_CHOICES : PERMISSION_CHOICES;
36
+ }
37
+ /**
38
+ * What a tool row says about a decision, or undefined where nobody was asked.
39
+ *
40
+ * Undefined for the absent case rather than an empty string, so the caller's decision is *is there
41
+ * anything to show* — the idiom `progressLabel` uses. Most rows in most transcripts have none, and a
42
+ * front-end that printed something for them would suggest a judgement nobody made.
43
+ *
44
+ * `asked` is phrased as the ongoing state it is. The other three are past tense, because by the time
45
+ * they are on screen the call has been decided and a reader is looking at history.
46
+ */
47
+ export function authorisationLabel(authorisation) {
48
+ switch (authorisation) {
49
+ case undefined:
50
+ return undefined;
51
+ case "asked":
52
+ return "waiting to be authorised";
53
+ case "allowed":
54
+ return "authorised";
55
+ case "always":
56
+ return "always authorised on this machine";
57
+ case "denied":
58
+ return "refused";
59
+ }
60
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The segment of a Scope a reader would call the Project.
3
+ *
4
+ * The leading directories are dropped rather than dimmed: they are the same for every Agent Session
5
+ * on this machine, so they cost a line's width to say nothing. A Scope that leaves no segment (`/`,
6
+ * or a trailing slash) falls back to the Scope verbatim, because an empty header names nothing.
7
+ *
8
+ * **A worktree Scope is the exception, and it is the same rule rather than a new one.** That
9
+ * premise above — that the leading directories say nothing because they are shared — is false for a
10
+ * worktree: it ends `<repo>/<branch>`, so its parent is the repository and is the one segment worth
11
+ * reading, while its basename is the branch the control beside this already names. So the same
12
+ * question is asked one segment higher up. A flag rather than the repository's name over the wire,
13
+ * because the name is already here in the Scope.
14
+ */
15
+ export function projectName(scope, worktree) {
16
+ const path = worktree ? scope.slice(0, Math.max(0, scope.lastIndexOf("/"))) : scope;
17
+ const cut = path.lastIndexOf("/");
18
+ return (cut < 0 ? path : path.slice(cut + 1)) || scope;
19
+ }