@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,20 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { createHash } from 'node:crypto';
3
+ import { compileJsonSchema } from "../workflows/json-schema.js";
4
+ export function connectionIdentity(connection) {
5
+ // Headers join the hash only when there are some, so every identity recorded before headers
6
+ // existed still matches and no saved MCP step needs reconfiguring.
7
+ const config = connection.transport === 'stdio' ? [connection.id, connection.transport, connection.command, connection.args] : [connection.id, connection.transport, connection.url, connection.oauth, ...(Object.keys(connection.headers).length ? [connection.headers] : [])];
8
+ return createHash('sha256').update(JSON.stringify(config)).digest('hex');
9
+ }
10
+ export function snapshotTool(connection, tool) {
11
+ const inputSchema = tool.definition.inputSchema;
12
+ const outputSchema = tool.definition.outputSchema;
13
+ compileJsonSchema(inputSchema);
14
+ if (outputSchema !== undefined)
15
+ compileJsonSchema(outputSchema);
16
+ return { connectionId: connection.id, connectionName: connection.name, identity: connectionIdentity(connection), serverIdentity: tool.serverIdentity, toolName: tool.definition.name, inputSchema, ...(outputSchema === undefined ? {} : { outputSchema }) };
17
+ }
18
+ export function sameSchema(a, b) {
19
+ return isDeepStrictEqual(a, b);
20
+ }
@@ -0,0 +1,102 @@
1
+ import { validSecretName } from "../protocol/secrets.js";
2
+ import { validateDefinition } from "../workflows/graph.js";
3
+ export function workflowRequestError(error) {
4
+ return error instanceof Error && error.name !== 'ZodError' && error.name !== 'SyntaxError' && error.message ? error.message.split(':')[0] : 'Invalid workflow request';
5
+ }
6
+ export async function workflowRoutes(request, response, pathname, workflows, secrets, executions) {
7
+ const match = /^\/api\/(workflows|secrets)(?:\/(.*))?$/.exec(pathname);
8
+ if (!match)
9
+ return false;
10
+ const reply = (status, value) => {
11
+ response.writeHead(status, { 'content-type': 'application/json' });
12
+ response.end(JSON.stringify(value));
13
+ };
14
+ const secret = match[1] === 'secrets';
15
+ if (secret ? !secrets : !workflows) {
16
+ reply(404, { error: 'Not available' });
17
+ return true;
18
+ }
19
+ let id;
20
+ try {
21
+ id = match[2] === undefined ? undefined : decodeURIComponent(match[2]);
22
+ if (id !== undefined && !(secret ? validSecretName(id) : /^[a-zA-Z0-9_-]{1,128}$/.test(id)))
23
+ throw new Error();
24
+ }
25
+ catch {
26
+ reply(400, { error: 'Invalid resource name' });
27
+ return true;
28
+ }
29
+ try {
30
+ if (request.method === 'GET') {
31
+ if (secret) {
32
+ if (id === undefined)
33
+ reply(200, { names: secrets.list() });
34
+ else if (secrets.has(id))
35
+ reply(200, { name: id });
36
+ else
37
+ reply(404, { error: 'Not found' });
38
+ }
39
+ else
40
+ reply(200, id === undefined ? { workflows: workflows.listDefinitions() } : { workflow: workflows.getDefinition(id) });
41
+ }
42
+ else if (request.method === 'DELETE' && id !== undefined) {
43
+ if (secret)
44
+ secrets.delete(id);
45
+ else
46
+ workflows.deleteDefinition(id);
47
+ reply(200, { deleted: true });
48
+ }
49
+ else if (request.method === 'PUT' && id !== undefined) {
50
+ let body;
51
+ try {
52
+ const chunks = [];
53
+ let size = 0;
54
+ for await (const chunk of request) {
55
+ const buffer = Buffer.from(chunk);
56
+ size += buffer.length;
57
+ if (size > (secret ? 400_000 : 1_000_000)) {
58
+ reply(413, { error: 'Body too large' });
59
+ return true;
60
+ }
61
+ chunks.push(buffer);
62
+ }
63
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
64
+ }
65
+ catch {
66
+ reply(400, { error: 'Invalid JSON body' });
67
+ return true;
68
+ }
69
+ if (secret) {
70
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).join() !== 'value'
71
+ || typeof body.value !== 'string'
72
+ || !body.value.length || Buffer.byteLength(body.value) > 64_000) {
73
+ reply(400, { error: 'Expected a secret value of 1 to 64000 bytes' });
74
+ return true;
75
+ }
76
+ secrets.set(id, body.value);
77
+ reply(200, { name: id });
78
+ }
79
+ else {
80
+ let definition;
81
+ try {
82
+ definition = validateDefinition(body).definition;
83
+ executions?.validateDefinitionCredentials(definition);
84
+ if (definition.id !== id)
85
+ throw new Error();
86
+ }
87
+ catch (error) {
88
+ reply(400, { error: workflowRequestError(error) });
89
+ return true;
90
+ }
91
+ workflows.saveDefinition(definition);
92
+ reply(200, { workflow: definition });
93
+ }
94
+ }
95
+ else
96
+ reply(405, { error: 'Method not allowed' });
97
+ }
98
+ catch (error) {
99
+ reply(error?.code === 'ENOENT' ? 404 : 500, { error: 'Resource unavailable' });
100
+ }
101
+ return true;
102
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Attachments, as they cross the wire.
3
+ *
4
+ * In the protocol rather than beside `src/daemon/store.ts` because every layer needs the same
5
+ * closed set: a composer decides whether a paste is even offerable, the Session Host refuses one it
6
+ * cannot use, the HTTP route names a `content-type`, and each Backend Adapter hands a media type to
7
+ * its SDK. `src/daemon/store.ts` owns where the bytes *live*; this file owns only what they may be.
8
+ *
9
+ * The set is the intersection both SDKs can serve, and it is Claude's `Base64ImageSource.media_type`
10
+ * union verbatim — pi will take any `mimeType` string, so it is the narrower end that fixes this.
11
+ */
12
+ /**
13
+ * The media types an Attachment may have, mapped to the extension its id carries.
14
+ *
15
+ * An id **is** a filename — `<uuid>.png` — so a media type is recoverable from an id and is
16
+ * therefore never sent alongside one. Carrying both would be two records of one fact, able to
17
+ * disagree about a file on disk. `SessionMeta.worktree` writes down what could be derived for the
18
+ * opposite reason: a wrong answer there runs `git worktree remove`, where a wrong answer here costs
19
+ * one wrong header. The extension set is closed and checked on the way in, so it cannot be wrong.
20
+ */
21
+ export const ATTACHMENT_MEDIA_TYPES = {
22
+ "image/png": "png",
23
+ "image/jpeg": "jpg",
24
+ "image/gif": "gif",
25
+ "image/webp": "webp",
26
+ };
27
+ /**
28
+ * The cap on one Attachment, counted in base64 characters rather than in decoded bytes, because that
29
+ * is the unit every provider states its own limit in. 5 MB clears the strictest documented one —
30
+ * Bedrock and Vertex — where the Claude API direct would allow 10 MB, and it is far above any
31
+ * screenshot a person will paste.
32
+ */
33
+ export const MAX_ATTACHMENT_BASE64_BYTES = 5_000_000;
34
+ /**
35
+ * The cap on one message. Above twenty images a *stricter per-image dimension* limit applies to
36
+ * every image in the request, so staying well under twenty means an oversized paste is quietly
37
+ * downsized — which is the friendly failure — rather than rejected by the provider.
38
+ */
39
+ export const MAX_ATTACHMENTS_PER_MESSAGE = 10;
40
+ const MEDIA_TYPE_OF_EXTENSION = new Map(Object.entries(ATTACHMENT_MEDIA_TYPES).map(([mediaType, extension]) => [
41
+ extension,
42
+ mediaType,
43
+ ]));
44
+ export function isAttachmentMediaType(value) {
45
+ return value in ATTACHMENT_MEDIA_TYPES;
46
+ }
47
+ /**
48
+ * The media type an id names, or `undefined` if it names nothing this can serve.
49
+ *
50
+ * Deliberately strict about the whole id and not only its extension: this is also the check that
51
+ * stops `../../token` reaching the filesystem, so a separate traversal guard would be a second
52
+ * rule able to fall out of step with this one.
53
+ */
54
+ export function mediaTypeOf(attachmentId) {
55
+ const match = /^[0-9a-f-]{36}\.([a-z]{3,4})$/.exec(attachmentId);
56
+ if (!match?.[1])
57
+ return undefined;
58
+ return MEDIA_TYPE_OF_EXTENSION.get(match[1]);
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Events the Session Host owns and a Backend Adapter must never emit. The queue lives above the
3
+ * backend (ADR 0002), the host records what the human sent, revival is a host concern, and the
4
+ * branch is moved by the host on the Scope — no SDK is told, and none could report it truthfully.
5
+ *
6
+ * A value rather than only a type, because the conformance suite needs the same list at runtime.
7
+ * It used to hand-copy it and had already fallen a member behind (`session_dormant`), which is a
8
+ * gap that widens silently every time this union grows: the type would refuse an adapter emitting
9
+ * one of these, and the suite would not notice an adapter that did.
10
+ */
11
+ export const HOST_OWNED_EVENT_TYPES = [
12
+ "user_message",
13
+ "queue_changed",
14
+ "revived",
15
+ "session_dormant",
16
+ "session_settled",
17
+ "session_ended",
18
+ "branch_changed",
19
+ "workflow_spend",
20
+ ];
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The two typefaces the clients draw with, and their defaults.
3
+ *
4
+ * In the protocol rather than beside either end because both ends need the same answer: the Session
5
+ * Host parses `fonts` out of config.json and reports it on /api/config, and the web client applies
6
+ * it. Defaults declared once here, so a change cannot be half-made.
7
+ *
8
+ * The stylesheet is the one place that cannot import this — CSS has no imports — so
9
+ * `web/src/index.css` restates both values and `test/fonts.test.ts` holds the two to each other.
10
+ */
11
+ export const DEFAULT_CHROME_FONT = "'Inter Variable', sans-serif";
12
+ /**
13
+ * Nerd Font families first, then the stock stacks.
14
+ *
15
+ * A Powerline or Nerd Font prompt draws its separators from the Private Use Area — U+E0B0 for the
16
+ * arrow, U+E0A0 for the branch — and no stock system font carries those codepoints, so a terminal
17
+ * set to one renders them as tofu. Naming the patched fonts costs nothing when they are absent,
18
+ * because a browser skips a family it cannot resolve, and when one is present the Shell draws the
19
+ * prompt as its owner's real terminal does. These four are what the Powerlevel10k and Starship
20
+ * installers put on disk, which is why they are the ones named.
21
+ */
22
+ export const DEFAULT_MONOSPACE_FONT = "'MesloLGS NF', 'JetBrainsMono Nerd Font', 'FiraCode Nerd Font', 'Hack Nerd Font', " +
23
+ "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
24
+ export function defaultFonts() {
25
+ return { chrome: DEFAULT_CHROME_FONT, monospace: DEFAULT_MONOSPACE_FONT };
26
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Git, as it crosses the wire.
3
+ *
4
+ * In the protocol rather than beside `src/daemon/git.ts` because both ends need the same shape: the
5
+ * Session Host reports a Branch on every SessionSummary and answers `/api/branches` with a
6
+ * BranchList, and both front-ends render them. `src/daemon/git.ts` owns how git is *asked*; this
7
+ * file owns only what the answers look like.
8
+ *
9
+ * Nothing here describes an operation. A switch is a Command and a worktree is a field on `create`,
10
+ * because both are things done to one Agent Session and the command door already carries those.
11
+ */
12
+ export {};
@@ -0,0 +1,51 @@
1
+ import { z } from "zod";
2
+ import { validSecretName } from "./secrets.js";
3
+ const headerName = z
4
+ .string()
5
+ .regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/);
6
+ const headerValue = z.union([
7
+ z
8
+ .object({ value: z.string().min(1).max(8192).regex(/^[\t\x20-\x7e]+$/) })
9
+ .strict(),
10
+ z
11
+ .object({ secret: z.string().refine(validSecretName, "Invalid secret reference") })
12
+ .strict(),
13
+ ]);
14
+ const common = {
15
+ id: z
16
+ .string()
17
+ .regex(/^[A-Za-z0-9_-]{1,40}$/)
18
+ .refine((id) => id !== "workflow", "Reserved connection ID"),
19
+ name: z.string().trim().min(1).max(100),
20
+ enabledByDefault: z.boolean().default(true),
21
+ };
22
+ export const mcpConnectionsSchema = z
23
+ .array(z.discriminatedUnion("transport", [
24
+ z
25
+ .object({
26
+ ...common,
27
+ transport: z.literal("stdio"),
28
+ command: z.string().min(1),
29
+ args: z.array(z.string()).default([]),
30
+ })
31
+ .strict(),
32
+ z
33
+ .object({
34
+ ...common,
35
+ transport: z.literal("http"),
36
+ url: z.url().refine((value) => {
37
+ const url = new URL(value);
38
+ return (["http:", "https:"].includes(url.protocol) &&
39
+ !url.username &&
40
+ !url.password);
41
+ }),
42
+ oauth: z.boolean().default(false),
43
+ headers: z
44
+ .record(headerName, headerValue)
45
+ .refine((entries) => Object.keys(entries).length <= 32)
46
+ .default({}),
47
+ })
48
+ .strict(),
49
+ ]))
50
+ .max(100)
51
+ .refine((entries) => new Set(entries.map((entry) => entry.id)).size === entries.length, "Connection IDs must be unique");
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A Project, as it crosses the wire.
3
+ *
4
+ * A Project is a *candidate* Scope: a directory a new Agent Session can be started from. It is not
5
+ * a Scope. A Scope is the binding one Agent Session holds for its whole life, whereas a Project
6
+ * exists before any Agent Session, outlives all of them, and may have several bound to it at once.
7
+ * Choosing a Project is how a client sets a Scope (CONTEXT.md).
8
+ *
9
+ * **Projects are opted into, not merely found.** `projects.include` in config.json is the list, and
10
+ * it is the whole of it: a repository beneath the Project Root is a *candidate* until it appears
11
+ * there. Discovery still exists, but it now feeds the Settings page's list of things to opt into
12
+ * rather than the dropdown itself — which is what lets the list stay as short as its owner wants
13
+ * (ADR 0011). A Project need not be a repository at all, because an opted-in directory is chosen
14
+ * deliberately and nothing has to guess whether it was meant.
15
+ *
16
+ * In the protocol rather than beside the walk that produces it because both ends need the shape:
17
+ * the Session Host reports these on /api/config, and the web client renders them as a grouped
18
+ * dropdown. `src/daemon/projects.ts` owns how they are found; this file owns only what they look
19
+ * like.
20
+ */
21
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ export function validSecretName(value) {
2
+ return typeof value === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/.test(value)
3
+ && !['__proto__', 'constructor', 'prototype'].includes(value);
4
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The Settings, as they cross the wire.
3
+ *
4
+ * Settings are machine-wide: they live in the Session Host's state root, not in a Scope, so one
5
+ * value governs every Agent Session on the machine. That is the fact most likely to be got wrong by
6
+ * someone editing them from a browser window that is showing one Scope, which is why it is said here
7
+ * and in CONTEXT.md rather than left to be inferred.
8
+ *
9
+ * In the protocol rather than beside the daemon because both ends need the same shape: the Session
10
+ * Host reports `Settings` on /api/config and accepts a `SettingsPatch` on PUT, and the web client
11
+ * renders the first and sends the second. `src/daemon/config.ts` owns how they are parsed and what
12
+ * they mean on disk; this file owns only their shape.
13
+ */
14
+ export const DEFAULT_WORKFLOW_RUNTIME = {
15
+ externalSandbox: true,
16
+ dockerImage: 'flow-workflow-runtime:local',
17
+ };
18
+ /** Explicitly configured backends never silently fall back to a different inference route. */
19
+ export function resolveDefaultBackend(backends, configured) {
20
+ return configured ?? (backends.includes("claude") ? "claude" : backends[0]);
21
+ }
22
+ const UNITS = {
23
+ s: 1000,
24
+ m: 60 * 1000,
25
+ h: 60 * 60 * 1000,
26
+ d: 24 * 60 * 60 * 1000,
27
+ };
28
+ /**
29
+ * `"90m"`, `"36h"`, `"1d"` — a duration in milliseconds, or undefined if it is not one.
30
+ *
31
+ * Here rather than beside the parser that uses it because both ends need it: the Session Host reads
32
+ * the file with it, and the web client uses it to work out what a window the reader has typed would
33
+ * reap before they commit to it. `src/daemon/config.ts` cannot be the home — it reads a file, so a
34
+ * browser cannot import it.
35
+ */
36
+ export function parseDuration(value) {
37
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(s|m|h|d)\s*$/.exec(value);
38
+ const amount = match?.[1];
39
+ const unit = match?.[2];
40
+ if (!amount || !unit)
41
+ return undefined;
42
+ const scale = UNITS[unit];
43
+ if (scale === undefined)
44
+ return undefined;
45
+ return Number(amount) * scale;
46
+ }
47
+ /**
48
+ * The inverse, in the largest unit that divides evenly: 86400000 is `"1d"` and not `"24h"`.
49
+ *
50
+ * Retention is stored as milliseconds because that is what the reaper compares against, but a
51
+ * duration is a thing a person typed and a person has to read it back. Reporting `86400000` on
52
+ * /api/config would make the field in the browser un-editable without arithmetic, so this exists to
53
+ * round-trip through `parseDuration` — and `test/settings.test.ts` holds the two to each other.
54
+ */
55
+ export function formatDuration(ms) {
56
+ for (const unit of ["d", "h", "m", "s"]) {
57
+ const scale = UNITS[unit];
58
+ if (ms >= scale && ms % scale === 0)
59
+ return `${ms / scale}${unit}`;
60
+ }
61
+ // Under a second, or not a whole number of any unit: seconds, fractional if it must be.
62
+ return `${ms / 1000}s`;
63
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The Shell protocol: what a client can ask about a Shell, and the frames that cross its socket.
3
+ *
4
+ * A Shell is addressed by its own id, never by the Agent Session's. It is associated with one for
5
+ * discovery and for lifecycle — Settle, End or Reap the Agent Session and its Shells exit — but it
6
+ * is not identified by one, because an Agent Session may own several.
7
+ */
8
+ export {};
@@ -0,0 +1,16 @@
1
+ export function leadingSkillToken(text) {
2
+ if (!text.startsWith("/"))
3
+ return undefined;
4
+ const match = /^\/([A-Za-z0-9][\w-]*(?::(?:[A-Za-z0-9][\w-]*)?)?)?/.exec(text);
5
+ const name = match?.[1] ?? "";
6
+ return { name, to: name.length + 1 };
7
+ }
8
+ export function leadingSkillInvocation(text) {
9
+ const token = leadingSkillToken(text);
10
+ if (!token || token.name === "" || token.name.endsWith(":"))
11
+ return undefined;
12
+ const next = text[token.to];
13
+ if (next !== undefined && next !== " " && next !== "\n")
14
+ return undefined;
15
+ return { ...token, rest: text.slice(token.to) };
16
+ }
@@ -0,0 +1,41 @@
1
+ /** Normalize display data in the daemon. Never mutates its inputs. */
2
+ export function stackDisplayGraph(status) {
3
+ const { graph, view, candidate } = status;
4
+ let display = graph ? { ...graph, branches: graph.branches.map(branch => ({ ...branch, ...(branch.pr ? { pr: { ...branch.pr } } : {}) })) } : undefined;
5
+ if (!display && view && view.currentBranch !== view.trunk) {
6
+ let parent = view.trunk;
7
+ display = { trunk: view.trunk, currentBranch: view.currentBranch, explicit: true, branches: view.branches.map(member => {
8
+ const branch = { name: member.name, parent, relation: "local", isCurrent: member.isCurrent, availability: "local", ...(member.pr ? { pr: { ...member.pr, state: member.isMerged ? "MERGED" : member.pr.state } } : {}) };
9
+ parent = member.name;
10
+ return branch;
11
+ }) };
12
+ }
13
+ if (!display && candidate)
14
+ display = { trunk: candidate.trunk, currentBranch: candidate.branches.at(-1) ?? "", explicit: false, branches: [] };
15
+ if (!display)
16
+ return;
17
+ const byName = new Map(display.branches.map(branch => [branch.name, branch]));
18
+ let parent = view?.trunk;
19
+ for (const member of view?.branches ?? []) {
20
+ const pr = member.pr ? { ...member.pr, state: member.isMerged ? "MERGED" : member.pr.state } : undefined;
21
+ const branch = byName.get(member.name) ?? { name: member.name, ...(parent ? { parent } : {}), relation: "local", isCurrent: member.isCurrent, availability: "local" };
22
+ Object.assign(branch, { isCurrent: member.isCurrent, ...(pr ? { pr } : {}) });
23
+ if (!byName.has(member.name)) {
24
+ display.branches.push(branch);
25
+ byName.set(member.name, branch);
26
+ }
27
+ parent = member.name;
28
+ }
29
+ parent = candidate?.trunk;
30
+ for (const pr of candidate?.pullRequests ?? []) {
31
+ const name = pr.branch;
32
+ const branch = byName.get(name) ?? { name, ...(parent ? { parent } : {}), relation: "pull-request", isCurrent: name === display.currentBranch, availability: "local" };
33
+ branch.pr = { ...pr };
34
+ if (!byName.has(name)) {
35
+ display.branches.push(branch);
36
+ byName.set(name, branch);
37
+ }
38
+ parent = name;
39
+ }
40
+ return display;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};