@otea/cli 0.0.1 → 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 (243) hide show
  1. package/LICENSE +661 -0
  2. package/README.es.md +151 -0
  3. package/README.md +251 -3
  4. package/THIRD_PARTY_NOTICES.md +114 -0
  5. package/bin/otea.mjs +28 -0
  6. package/dist/app/agent-detail.js +26 -0
  7. package/dist/app/agent-draft.js +429 -0
  8. package/dist/app/agent-prompts.js +52 -0
  9. package/dist/app/agents.js +77 -0
  10. package/dist/app/asking.js +43 -0
  11. package/dist/app/board-archive.js +243 -0
  12. package/dist/app/board-migration.js +272 -0
  13. package/dist/app/boards.js +870 -0
  14. package/dist/app/branch-owner.js +48 -0
  15. package/dist/app/brief.js +53 -0
  16. package/dist/app/choices.js +61 -0
  17. package/dist/app/collections.js +101 -0
  18. package/dist/app/context.js +1 -0
  19. package/dist/app/crop.js +56 -0
  20. package/dist/app/devices.js +62 -0
  21. package/dist/app/draft-request.js +82 -0
  22. package/dist/app/events.js +12 -0
  23. package/dist/app/evidence.js +287 -0
  24. package/dist/app/gates.js +610 -0
  25. package/dist/app/guide.js +37 -0
  26. package/dist/app/home.js +145 -0
  27. package/dist/app/init-boards.js +36 -0
  28. package/dist/app/intake.js +25 -0
  29. package/dist/app/item-search.js +141 -0
  30. package/dist/app/items.js +318 -0
  31. package/dist/app/keep-waiting.js +44 -0
  32. package/dist/app/land-order.js +107 -0
  33. package/dist/app/language.js +52 -0
  34. package/dist/app/launcher.js +56 -0
  35. package/dist/app/lease-take.js +54 -0
  36. package/dist/app/leases.js +86 -0
  37. package/dist/app/machine.js +39 -0
  38. package/dist/app/merged.js +89 -0
  39. package/dist/app/migrate.js +171 -0
  40. package/dist/app/next.js +1637 -0
  41. package/dist/app/notes.js +319 -0
  42. package/dist/app/notify-targets.js +113 -0
  43. package/dist/app/opened.js +25 -0
  44. package/dist/app/owner-only.js +34 -0
  45. package/dist/app/performance.js +28 -0
  46. package/dist/app/phone.js +97 -0
  47. package/dist/app/presence.js +596 -0
  48. package/dist/app/preset-views.js +25 -0
  49. package/dist/app/presets.js +129 -0
  50. package/dist/app/priority.js +156 -0
  51. package/dist/app/profile.js +86 -0
  52. package/dist/app/project.js +247 -0
  53. package/dist/app/proofs.js +179 -0
  54. package/dist/app/questions.js +215 -0
  55. package/dist/app/reader-filter.js +58 -0
  56. package/dist/app/relations.js +164 -0
  57. package/dist/app/relay.js +98 -0
  58. package/dist/app/repos.js +176 -0
  59. package/dist/app/restart.js +92 -0
  60. package/dist/app/set-aside.js +64 -0
  61. package/dist/app/system-locale.js +6 -0
  62. package/dist/app/tailscale-cli.js +77 -0
  63. package/dist/app/tailscale-testing.js +41 -0
  64. package/dist/app/tailscale.js +177 -0
  65. package/dist/app/tips.js +30 -0
  66. package/dist/app/topics-everywhere.js +53 -0
  67. package/dist/app/topics.js +453 -0
  68. package/dist/app/undo.js +52 -0
  69. package/dist/app/validate.js +131 -0
  70. package/dist/app/watch.js +48 -0
  71. package/dist/cli/command.js +44 -0
  72. package/dist/cli/commands.js +3303 -0
  73. package/dist/cli/exit-codes.js +70 -0
  74. package/dist/cli/forge.js +176 -0
  75. package/dist/cli/format.js +340 -0
  76. package/dist/cli/gh.js +17 -0
  77. package/dist/cli/gitrepo.js +489 -0
  78. package/dist/cli/help.js +101 -0
  79. package/dist/cli/hooks.js +232 -0
  80. package/dist/cli/main.js +37 -0
  81. package/dist/cli/merged-outside.js +58 -0
  82. package/dist/cli/names.js +154 -0
  83. package/dist/cli/opener.js +21 -0
  84. package/dist/cli/owner.js +154 -0
  85. package/dist/cli/phone.js +221 -0
  86. package/dist/cli/ports.js +24 -0
  87. package/dist/cli/probe.js +18 -0
  88. package/dist/cli/run.js +246 -0
  89. package/dist/cli/serve-file.js +21 -0
  90. package/dist/cli/stats.js +55 -0
  91. package/dist/cli/version.js +3 -0
  92. package/dist/core/agent-guide.js +31 -0
  93. package/dist/core/agent-prompts.js +139 -0
  94. package/dist/core/authority.js +94 -0
  95. package/dist/core/board/analysis.js +86 -0
  96. package/dist/core/board/choices.js +100 -0
  97. package/dist/core/board/compile.js +362 -0
  98. package/dist/core/board/engine.js +523 -0
  99. package/dist/core/board/hints.js +46 -0
  100. package/dist/core/board/history.js +146 -0
  101. package/dist/core/board/ids.js +87 -0
  102. package/dist/core/board/joins.js +30 -0
  103. package/dist/core/board/mentions.js +68 -0
  104. package/dist/core/board/merged.js +18 -0
  105. package/dist/core/board/model.js +135 -0
  106. package/dist/core/board/next.js +1116 -0
  107. package/dist/core/board/notes.js +298 -0
  108. package/dist/core/board/performance.js +218 -0
  109. package/dist/core/board/plan.js +299 -0
  110. package/dist/core/board/problems.js +232 -0
  111. package/dist/core/board/proofs.js +84 -0
  112. package/dist/core/board/questions.js +114 -0
  113. package/dist/core/board/reading.js +220 -0
  114. package/dist/core/board/readings.js +534 -0
  115. package/dist/core/board/schema.js +335 -0
  116. package/dist/core/board/shape-words.js +179 -0
  117. package/dist/core/board/template-words.js +23 -0
  118. package/dist/core/board/templates-catalogue.js +965 -0
  119. package/dist/core/board/templates-coverage.js +261 -0
  120. package/dist/core/board/templates-flows.js +779 -0
  121. package/dist/core/board/templates.js +586 -0
  122. package/dist/core/brief.js +93 -0
  123. package/dist/core/diagram.js +80 -0
  124. package/dist/core/errors.js +12 -0
  125. package/dist/core/evidence.js +33 -0
  126. package/dist/core/fields.js +129 -0
  127. package/dist/core/hierarchy.js +30 -0
  128. package/dist/core/icons.js +181 -0
  129. package/dist/core/image-crop.js +166 -0
  130. package/dist/core/item.js +49 -0
  131. package/dist/core/lease.js +31 -0
  132. package/dist/core/modules.js +318 -0
  133. package/dist/core/notify/planner.js +117 -0
  134. package/dist/core/notify/signals.js +66 -0
  135. package/dist/core/notify/text.js +60 -0
  136. package/dist/core/path-key.js +22 -0
  137. package/dist/core/placement.js +161 -0
  138. package/dist/core/preset-labels.js +66 -0
  139. package/dist/core/preset-notes.js +109 -0
  140. package/dist/core/preset.js +541 -0
  141. package/dist/core/profile.js +55 -0
  142. package/dist/core/project-id.js +20 -0
  143. package/dist/core/refusal.js +1 -0
  144. package/dist/core/relations.js +208 -0
  145. package/dist/core/repo.js +54 -0
  146. package/dist/core/samples.js +161 -0
  147. package/dist/core/search-words.js +68 -0
  148. package/dist/core/test-report.js +120 -0
  149. package/dist/core/time.js +8 -0
  150. package/dist/core/validation.js +60 -0
  151. package/dist/core/views.js +171 -0
  152. package/dist/core/workflow.js +51 -0
  153. package/dist/mcp/commands.js +101 -0
  154. package/dist/mcp/server.js +239 -0
  155. package/dist/mcp/words.js +95 -0
  156. package/dist/server/boards.js +232 -0
  157. package/dist/server/changes.js +42 -0
  158. package/dist/server/diff-tip.js +83 -0
  159. package/dist/server/drift.js +87 -0
  160. package/dist/server/errors.js +87 -0
  161. package/dist/server/evidence.js +82 -0
  162. package/dist/server/hosts.js +6 -0
  163. package/dist/server/hub.js +98 -0
  164. package/dist/server/lan-access.js +62 -0
  165. package/dist/server/lan.js +164 -0
  166. package/dist/server/listen.js +70 -0
  167. package/dist/server/notifier.js +156 -0
  168. package/dist/server/notify-api.js +151 -0
  169. package/dist/server/pairing.js +124 -0
  170. package/dist/server/projects.js +191 -0
  171. package/dist/server/push.js +199 -0
  172. package/dist/server/server.js +960 -0
  173. package/dist/server/session.js +43 -0
  174. package/dist/server/stream.js +36 -0
  175. package/dist/server/test-push.js +38 -0
  176. package/dist/server/token.js +37 -0
  177. package/dist/server/transports.js +54 -0
  178. package/dist/server/ui.js +44 -0
  179. package/dist/server/writes.js +361 -0
  180. package/dist/server/wrong-address.js +36 -0
  181. package/dist/store/boards.js +111 -0
  182. package/dist/store/database.js +45 -0
  183. package/dist/store/machine.js +77 -0
  184. package/dist/store/migrations.js +493 -0
  185. package/dist/store/queries.js +585 -0
  186. package/dist/store/registry.js +72 -0
  187. package/package.json +72 -4
  188. package/presets/architecture/playbook.md +69 -0
  189. package/presets/architecture/preset.yaml +80 -0
  190. package/presets/architecture/samples.yaml +23 -0
  191. package/presets/bug-triage/playbook.md +129 -0
  192. package/presets/bug-triage/preset.yaml +127 -0
  193. package/presets/bug-triage/samples/wall-slide-after.png +0 -0
  194. package/presets/bug-triage/samples/wall-slide-before.png +0 -0
  195. package/presets/bug-triage/samples.yaml +72 -0
  196. package/presets/change/playbook.md +115 -0
  197. package/presets/change/preset.yaml +141 -0
  198. package/presets/change/samples.yaml +62 -0
  199. package/presets/review/playbook.md +51 -0
  200. package/presets/review/preset.yaml +62 -0
  201. package/presets/review/samples.yaml +27 -0
  202. package/presets/tasks/playbook.md +78 -0
  203. package/presets/tasks/preset.yaml +61 -0
  204. package/presets/tasks/samples.yaml +46 -0
  205. package/schemas/board.schema.json +764 -0
  206. package/ui/dist/THIRD_PARTY_NOTICES.md +114 -0
  207. package/ui/dist/assets/dm-mono-latin-400-normal--0xN8mdc.woff +0 -0
  208. package/ui/dist/assets/dm-mono-latin-400-normal-4GdczIuU.woff2 +0 -0
  209. package/ui/dist/assets/dm-mono-latin-500-normal-CN8Miw6E.woff +0 -0
  210. package/ui/dist/assets/dm-mono-latin-500-normal-DRMDZjhP.woff2 +0 -0
  211. package/ui/dist/assets/dm-mono-latin-ext-400-normal-1aZr6b2b.woff +0 -0
  212. package/ui/dist/assets/dm-mono-latin-ext-400-normal-C2zvOubV.woff2 +0 -0
  213. package/ui/dist/assets/dm-mono-latin-ext-500-normal-BtRyHRi6.woff2 +0 -0
  214. package/ui/dist/assets/dm-mono-latin-ext-500-normal-Dw3M13d8.woff +0 -0
  215. package/ui/dist/assets/index-C3OzJope.js +103 -0
  216. package/ui/dist/assets/index-COdEjckQ.css +1 -0
  217. package/ui/dist/assets/newsreader-latin-ext-opsz-italic-CSPGnFdO.woff2 +0 -0
  218. package/ui/dist/assets/newsreader-latin-ext-opsz-normal-BQn1nviT.woff2 +0 -0
  219. package/ui/dist/assets/newsreader-latin-opsz-italic-kJKFiXvB.woff2 +0 -0
  220. package/ui/dist/assets/newsreader-latin-opsz-normal-s-izfB6B.woff2 +0 -0
  221. package/ui/dist/assets/newsreader-vietnamese-opsz-italic-DTr-ymY4.woff2 +0 -0
  222. package/ui/dist/assets/newsreader-vietnamese-opsz-normal-BjhtXyW2.woff2 +0 -0
  223. package/ui/dist/assets/pdf-YwugTw7Y.js +54 -0
  224. package/ui/dist/assets/pdf-engine-CkBopwck.js +1 -0
  225. package/ui/dist/assets/pdf-rELvHkft.js +56 -0
  226. package/ui/dist/assets/pdf.worker.min-B5Yc7dP4.mjs +27 -0
  227. package/ui/dist/assets/pdf.worker.min-B7U8ptvh.js +1 -0
  228. package/ui/dist/assets/pdf.worker.min-CIqJB0yW.mjs +28 -0
  229. package/ui/dist/assets/pdf.worker.min-UqOn5EDC.js +1 -0
  230. package/ui/dist/assets/schibsted-grotesk-latin-ext-wght-normal-hsMS0n0O.woff2 +0 -0
  231. package/ui/dist/assets/schibsted-grotesk-latin-wght-normal-Bb8VGrTG.woff2 +0 -0
  232. package/ui/dist/icons/apple-touch-icon.png +0 -0
  233. package/ui/dist/icons/otea-192.png +0 -0
  234. package/ui/dist/icons/otea-512.png +0 -0
  235. package/ui/dist/icons/otea-badge.png +0 -0
  236. package/ui/dist/icons/otea-maskable-512.png +0 -0
  237. package/ui/dist/index.html +25 -0
  238. package/ui/dist/manifest.webmanifest +24 -0
  239. package/ui/dist/otea-idle.svg +5 -0
  240. package/ui/dist/otea-working.svg +5 -0
  241. package/ui/dist/otea-yours-working.svg +5 -0
  242. package/ui/dist/otea-yours.svg +5 -0
  243. package/ui/dist/sw.js +1 -0
@@ -0,0 +1,960 @@
1
+ import { Hono } from 'hono';
2
+ import { bodyLimit } from 'hono/body-limit';
3
+ import { getCookie, setCookie } from 'hono/cookie';
4
+ import { z } from 'zod';
5
+ import { agentDetail } from '../app/agent-detail.js';
6
+ import { promptFacts, promptKindOf } from '../app/agent-prompts.js';
7
+ import { askingItems, holderAsksOf } from '../app/asking.js';
8
+ import { syncBoardPresets } from '../app/boards.js';
9
+ import { briefFor } from '../app/brief.js';
10
+ import { listCollectionViews, listShownCollectionViews } from '../app/collections.js';
11
+ import { deviceByToken, listDevices, touchDevice } from '../app/devices.js';
12
+ import { listEvents } from '../app/events.js';
13
+ import { attachFiles, createItemWithEvidence } from '../app/intake.js';
14
+ import { searchItems } from '../app/item-search.js';
15
+ import { createItem, getItem, listItems, moveItem, showItem, updateItem, } from '../app/items.js';
16
+ import { rememberLanguage, resolveLang, storedLanguage } from '../app/language.js';
17
+ import { memoryMachine } from '../app/machine.js';
18
+ import { boardRoundOf, liveBoards, rowFactsOf } from '../app/next.js';
19
+ import { editNote, leaveNote, notesSummary, notesView, withdrawNote } from '../app/notes.js';
20
+ import { listTargets } from '../app/notify-targets.js';
21
+ import { markOpened, openedFiles } from '../app/opened.js';
22
+ import { performanceOf } from '../app/performance.js';
23
+ import { adoptTailscale, choosePhoneTransport, fetchProbe, isTransport, phoneSettings, phoneStatus, RELAY_UNAVAILABLE, setLanOpen, switchToTailscale, } from '../app/phone.js';
24
+ import { listAgents, presenceSignature } from '../app/presence.js';
25
+ import { listPresetViews } from '../app/preset-views.js';
26
+ import { estimatesOfItems, pinItems, priorityOf, setOrder } from '../app/priority.js';
27
+ import { projectView } from '../app/project.js';
28
+ import { answerQuestion } from '../app/questions.js';
29
+ import { linkItems, unlinkItems } from '../app/relations.js';
30
+ import { reassignItem, restartItem, resumeItem, undoRelease } from '../app/restart.js';
31
+ import { setAsideOf } from '../app/set-aside.js';
32
+ import { NO_TAILSCALE, readGuide, serveCommand, } from '../app/tailscale.js';
33
+ import { closeTopic, convertTopic, dismissTopicSuggestion, linkTopic, listTopics, noteTopic, requireTopic, setTopicsOn, topicSuggestions, topicsOfItem, topicsOn, } from '../app/topics.js';
34
+ import { topicsEverywhere } from '../app/topics-everywhere.js';
35
+ import { undoMove } from '../app/undo.js';
36
+ import { mergedOutside } from '../cli/merged-outside.js';
37
+ import { agentPrompt, isPromptKind, PROMPT_KINDS } from '../core/agent-prompts.js';
38
+ import { PERIOD_HINT, parsePeriod } from '../core/board/performance.js';
39
+ import { LANGS } from '../core/board/template-words.js';
40
+ import { OteaError } from '../core/errors.js';
41
+ import { MAX_EVIDENCE_MB } from '../core/evidence.js';
42
+ import { TURNS } from '../core/workflow.js';
43
+ import { itemOfClientKey, selectEvents, selectStateEntries, } from '../store/queries.js';
44
+ import { boardsApi } from './boards.js';
45
+ import { createChangeFeed } from './changes.js';
46
+ import { diffOffTip } from './diff-tip.js';
47
+ import { branchDrift } from './drift.js';
48
+ import { errorBody, ForbiddenHost, InvalidQuery, RejectedRequest, toErrorResponse, } from './errors.js';
49
+ import { serveEvidence } from './evidence.js';
50
+ import { DEFAULT_PORT, isAllowedHost, isApiPath } from './hosts.js';
51
+ import { openProjects } from './hub.js';
52
+ import { AttemptLimiter, isLoopback, PairingCodes, plainAddress } from './lan.js';
53
+ import { lanAccess, openLan } from './lan-access.js';
54
+ import { createNotifier } from './notifier.js';
55
+ import { notifyApi } from './notify-api.js';
56
+ import { assertCanManageDevices, assertPhoneOn, pair, pairingView, peekPairing, qrCode, revoke, viaOf, } from './pairing.js';
57
+ import { addPath, forgetPath, installGitHooks, projectOverviews, projectSettings, relinkPath, } from './projects.js';
58
+ import { generateVapidKeys, webPushSender } from './push.js';
59
+ import { deviceCookie, LOCAL, mountAuth, session, } from './session.js';
60
+ import { liveStreams } from './stream.js';
61
+ import { sendTestPush } from './test-push.js';
62
+ import { proxied, tailscaleTransport } from './transports.js';
63
+ import { BUILT_UI_DIR, mountUi } from './ui.js';
64
+ import { answerRequest, assertConfigurable, assertSameOrigin, assertSignedIn, assertWritable, attachRequest, briefRequest, clientKeyOf, createRequest, HUMAN_IN_UI, linkRequest, MAX_CREATE_BYTES, MAX_INTAKE_FILES, moveRequest, noteRequest, openedRequest, orderRequest, pathRequest, pinRequest, reassignRequest, relinkRequest, undoRequest, updateRequest, } from './writes.js';
65
+ import { wantsPage, wrongAddressPage } from './wrong-address.js';
66
+ function isTurn(value) {
67
+ return TURNS.includes(value);
68
+ }
69
+ // `field=key=value`, repeatable, keeps the items whose field holds exactly that value.
70
+ function fieldsFilter(pairs) {
71
+ const fields = {};
72
+ for (const pair of pairs) {
73
+ const separator = pair.indexOf('=');
74
+ if (separator < 1)
75
+ throw new InvalidQuery(`field expects key=value, got "${pair}"`);
76
+ const key = pair.slice(0, separator);
77
+ if (key in fields)
78
+ throw new InvalidQuery(`field "${key}" given twice`);
79
+ fields[key] = pair.slice(separator + 1);
80
+ }
81
+ return fields;
82
+ }
83
+ function itemsFilter(query, fields = []) {
84
+ const { collection, state, type, turn, parent } = query;
85
+ const filter = {};
86
+ if (collection !== undefined)
87
+ filter.collection = collection;
88
+ if (parent !== undefined)
89
+ filter.parent = parent;
90
+ if (state !== undefined)
91
+ filter.state = state;
92
+ if (type !== undefined)
93
+ filter.type = type;
94
+ if (turn !== undefined) {
95
+ if (!isTurn(turn))
96
+ throw new InvalidQuery(`turn must be one of ${TURNS.join(', ')}`);
97
+ filter.turn = turn;
98
+ }
99
+ if (fields.length > 0)
100
+ filter.fields = fieldsFilter(fields);
101
+ return filter;
102
+ }
103
+ // A cursor (`since`, from 0) or a count (`limit`, `latest`, from 1), as a whole number.
104
+ function wholeNumber(name, text, min) {
105
+ if (text === undefined)
106
+ return undefined;
107
+ const value = Number(text);
108
+ if (!/^[0-9]+$/.test(text) || !Number.isSafeInteger(value) || value < min) {
109
+ throw new InvalidQuery(`${name} must be a whole number of at least ${min}`);
110
+ }
111
+ return value;
112
+ }
113
+ // The same filter `otea events` reads, plus `latest`: the newest events, where a live feed starts.
114
+ function eventsFilter(query) {
115
+ const { item, collection } = query;
116
+ const since = wholeNumber('since', query.since, 0);
117
+ const limit = wholeNumber('limit', query.limit, 1);
118
+ const latest = wholeNumber('latest', query.latest, 1);
119
+ if (limit !== undefined && latest !== undefined) {
120
+ throw new InvalidQuery('limit and latest cannot be combined');
121
+ }
122
+ return {
123
+ ...(item === undefined ? {} : { item }),
124
+ ...(collection === undefined ? {} : { collection }),
125
+ ...(since === undefined ? {} : { since }),
126
+ ...(limit === undefined ? {} : { limit }),
127
+ ...(latest === undefined ? {} : { latest }),
128
+ };
129
+ }
130
+ function tooLarge() {
131
+ throw new RejectedRequest(413, 'evidence_too_large', `Send at most ${MAX_INTAKE_FILES} files of ${MAX_EVIDENCE_MB} MB each`);
132
+ }
133
+ const TransportBody = z.object({ transport: z.string() });
134
+ const LanguageBody = z.object({
135
+ lang: z.enum(LANGS),
136
+ onlyIfUnset: z.boolean().optional(),
137
+ });
138
+ const ServeBody = z.object({ command: z.string() });
139
+ const TopicsSwitchBody = z.object({ on: z.boolean() });
140
+ const TopicNoteBody = z.object({ text: z.string() });
141
+ const TopicConvertBody = z.object({ item: z.string().min(1) });
142
+ // A body the topic routes read, or a 400 saying what they expect.
143
+ async function topicBody(c, schema, expected) {
144
+ const parsed = schema.safeParse(await c.req.json().catch(() => undefined));
145
+ if (!parsed.success)
146
+ throw new RejectedRequest(400, 'invalid_body', `Expected ${expected}`);
147
+ return parsed.data;
148
+ }
149
+ // What is the computer's rather than a project's: the session, the pairing code and the paired
150
+ // devices, and how a phone reaches the server. Answered at /api and in every project's API alike.
151
+ function machineApi(doors) {
152
+ const { auth, phone, port, machine } = doors;
153
+ return (new Hono()
154
+ .get('/session', (c) => c.json({
155
+ canWrite: auth.canWrite(c),
156
+ canManageDevices: auth.canManageDevices(c),
157
+ canConfigure: auth.canConfigure(c),
158
+ }))
159
+ // The language the person's desk is in, kept for what is made without a desk (otea init, otea
160
+ // board add): the desk says it when it opens while none is kept, and on every switch.
161
+ .get('/language', (c) => c.json({ language: storedLanguage(machine) ?? null }))
162
+ .post('/language', async (c) => {
163
+ assertWritable(c, auth);
164
+ const parsed = LanguageBody.safeParse(await c.req.json().catch(() => undefined));
165
+ if (!parsed.success) {
166
+ throw new RejectedRequest(400, 'invalid_body', 'Expected {"lang": "en" | "es", "onlyIfUnset"?: boolean}');
167
+ }
168
+ const { lang, onlyIfUnset } = parsed.data;
169
+ return c.json({ language: rememberLanguage(machine, lang, onlyIfUnset) });
170
+ })
171
+ .get('/lan', (c) => {
172
+ assertCanManageDevices(c, auth);
173
+ return c.json(pairingView(machine, phone, port(), c.req.query('address')));
174
+ })
175
+ .post('/lan/code', (c) => {
176
+ assertCanManageDevices(c, auth);
177
+ assertSameOrigin(c);
178
+ assertPhoneOn(phone).codes.issue();
179
+ return c.json(pairingView(machine, phone, port(), c.req.query('address')), 201);
180
+ })
181
+ // The pairing dialog opened: it shows a code with its whole lifetime ahead, not the one otea
182
+ // serve issued minutes before (P7-R3-5), unless that one may be in someone's hands now.
183
+ .post('/lan/code/fresh', (c) => {
184
+ assertCanManageDevices(c, auth);
185
+ assertSameOrigin(c);
186
+ if (phone.chosen())
187
+ phone.codes.fresh();
188
+ return c.json(pairingView(machine, phone, port(), c.req.query('address')));
189
+ })
190
+ // How a phone reaches the desk: the chosen transport, its URL and whether it answers there.
191
+ .get('/phone', async (c) => {
192
+ assertCanManageDevices(c, auth);
193
+ return c.json(await phoneView(doors));
194
+ })
195
+ // Opens the local network to phones without a restart, and keeps it open for the next otea
196
+ // serve; closing it stops listening there. Paired devices stay paired either way.
197
+ .post('/lan/open', async (c) => {
198
+ assertConfigurable(c, auth);
199
+ await doors.lan.open();
200
+ setLanOpen(machine, true);
201
+ if (phone.chosen())
202
+ phone.codes.issue();
203
+ return c.json(await phoneView(doors));
204
+ })
205
+ .post('/lan/close', async (c) => {
206
+ assertConfigurable(c, auth);
207
+ setLanOpen(machine, false);
208
+ await doors.lan.close();
209
+ return c.json(await phoneView(doors));
210
+ })
211
+ // Chooses the transport. Tailscale is set up first (tailscale serve points at this port) and
212
+ // kept only once it is ready; the Otea relay is not available yet.
213
+ .post('/phone', async (c) => {
214
+ assertConfigurable(c, auth);
215
+ const parsed = TransportBody.safeParse(await c.req.json().catch(() => undefined));
216
+ const transport = parsed.success ? parsed.data.transport : '';
217
+ if (!isTransport(transport)) {
218
+ throw new RejectedRequest(400, 'invalid_body', 'Expected {"transport": "lan" | "tailscale"}');
219
+ }
220
+ if (transport === 'relay') {
221
+ throw new RejectedRequest(409, 'transport_unavailable', RELAY_UNAVAILABLE);
222
+ }
223
+ const check = transport === 'tailscale' ? await adoptTailscale(machine, doors.tailscale, port()) : null;
224
+ if (transport === 'lan')
225
+ choosePhoneTransport(machine, { transport, tailscaleHost: null });
226
+ if (phone.chosen())
227
+ phone.codes.issue();
228
+ const status = await phoneView(doors);
229
+ return c.json({ ...status, ...(check ? { tailscale: check } : {}) });
230
+ })
231
+ // The guided path to Tailscale: each step read from this computer, done or still to do,
232
+ // with the command Otea would run and the store pages as QR codes. It changes nothing.
233
+ .get('/phone/tailscale', async (c) => {
234
+ assertCanManageDevices(c, auth);
235
+ const guide = await readGuide(doors.tailscale, port(), { pairing: pairingOf(machine) });
236
+ const store = (url) => ({ url, qr: qrCode(url) });
237
+ return c.json({
238
+ ...guide,
239
+ stores: { android: store(guide.stores.android), ios: store(guide.stores.ios) },
240
+ });
241
+ })
242
+ // The one change Otea makes to Tailscale: the command the guide shows, word for word, run
243
+ // only once the person confirmed it there; anything else is refused.
244
+ .post('/phone/tailscale/serve', async (c) => {
245
+ assertConfigurable(c, auth);
246
+ const parsed = ServeBody.safeParse(await c.req.json().catch(() => undefined));
247
+ const command = serveCommand(port());
248
+ if (!parsed.success || parsed.data.command !== command) {
249
+ throw new RejectedRequest(400, 'invalid_body', `Expected {"command": "${command}"}`);
250
+ }
251
+ const check = await switchToTailscale(machine, doors.tailscale, port());
252
+ if (phone.chosen())
253
+ phone.codes.issue();
254
+ return c.json({ ...(await phoneView(doors)), tailscale: check });
255
+ })
256
+ // One push to that device now, past the planner, the quiet hours and the spacing, with what
257
+ // its push service answered.
258
+ .post('/devices/:id/test-push', async (c) => {
259
+ assertCanManageDevices(c, auth);
260
+ assertSameOrigin(c);
261
+ const id = c.req.param('id');
262
+ if (!listDevices(machine).some((device) => device.id === id)) {
263
+ throw new RejectedRequest(404, 'not_found', `No paired device ${id}`);
264
+ }
265
+ const answer = await sendTestPush(machine, doors.sender, id, doors.log);
266
+ if (answer.result === 'gone')
267
+ doors.changed();
268
+ return c.json(answer);
269
+ })
270
+ .post('/devices/:id/revoke', (c) => {
271
+ assertCanManageDevices(c, auth);
272
+ assertSameOrigin(c);
273
+ // Its push subscription goes with it.
274
+ const device = revoke(machine, c.req.param('id'));
275
+ doors.changed();
276
+ return c.json(device);
277
+ }));
278
+ }
279
+ function api(project, { feed, streams, notifier }, doors) {
280
+ const { auth, env, machine } = doors;
281
+ return (new Hono()
282
+ // A board published from another process (the CLI, another server) joins the catalog before
283
+ // anything reads items; it costs one query when nothing was published.
284
+ .use(async (_c, next) => {
285
+ syncBoardPresets(project);
286
+ await next();
287
+ })
288
+ .route('/', machineApi(doors))
289
+ .get('/project', (c) => c.json(projectView(project)))
290
+ .get('/projects', (c) => c.json(projectOverviews(doors.source.list(), project.identity.id)))
291
+ .get('/project/settings', (c) => c.json(projectSettings(project, env)))
292
+ .post('/project/paths', async (c) => {
293
+ assertConfigurable(c, auth);
294
+ const { path } = await pathRequest(c);
295
+ return c.json(addPath(project, path, env), 201);
296
+ })
297
+ .post('/project/paths/relink', async (c) => {
298
+ assertConfigurable(c, auth);
299
+ const { from, to, force } = await relinkRequest(c);
300
+ return c.json(relinkPath(project, from, to, force, env));
301
+ })
302
+ .post('/project/paths/forget', async (c) => {
303
+ assertConfigurable(c, auth);
304
+ const { path } = await pathRequest(c);
305
+ return c.json(forgetPath(project, path, env));
306
+ })
307
+ // Publicar's offer on a board that protects a branch: Otea's pre-push hook in every repo of
308
+ // the project that has none, so git refuses the push the board refuses.
309
+ .post('/project/git-hook', (c) => {
310
+ assertConfigurable(c, auth);
311
+ if (!doors.gitHook) {
312
+ throw new RejectedRequest(409, 'not_available', 'This server cannot write a git hook: run otea hook install --git in the repository');
313
+ }
314
+ return c.json(installGitHooks(project, doors.gitHook, env));
315
+ })
316
+ .get('/collections', (c) => c.json(listShownCollectionViews(project)))
317
+ .get('/presets', (c) => c.json(listPresetViews(project)))
318
+ .get('/agents', (c) => c.json({ agents: listAgents(project.db) }))
319
+ // What to paste into an agent's chat (Conectar un agente, the empty project): the first contact,
320
+ // one more agent joining, or one more board; without a kind, the project's moment.
321
+ .get('/agent-prompt', (c) => {
322
+ const { kind, lang: asked } = c.req.query();
323
+ if (kind !== undefined && !isPromptKind(kind))
324
+ throw new InvalidQuery(`kind must be one of ${PROMPT_KINDS.join(', ')}`);
325
+ const lang = asked === 'es' || asked === 'en' ? asked : resolveLang(storedLanguage(machine), env);
326
+ const moment = kind ?? promptKindOf(project);
327
+ const facts = promptFacts(project, moment);
328
+ const first = 'first' in facts && facts.first === true ? { first: true } : {};
329
+ return c.json({ kind: moment, prompt: agentPrompt(moment, lang, facts), ...first });
330
+ })
331
+ // How each model performs (Rendimiento): per model family and effort, for a board and a period.
332
+ .get('/performance', (c) => {
333
+ const { board, since = 'all' } = c.req.query();
334
+ if (!parsePeriod(since, new Date().toISOString())) {
335
+ throw new InvalidQuery(`since takes ${PERIOD_HINT}`);
336
+ }
337
+ return c.json(performanceOf(project, { board, since }));
338
+ })
339
+ .get('/agents/:name', (c) => c.json(agentDetail(project, c.req.param('name'))))
340
+ .get('/items', (c) => {
341
+ const items = listItems(project, itemsFilter(c.req.query(), c.req.queries('field')));
342
+ // On a board, each item's round as the engine counts it, so every list agrees with it.
343
+ const boards = liveBoards(project);
344
+ const priority = priorityOf(project.db);
345
+ // When each item entered its state: the turn it stands on began then (Te toca counts from it).
346
+ const entered = selectStateEntries(project.db);
347
+ // The questions that wait for the person: an item held by an agent that asks elsewhere.
348
+ const asking = askingItems(project.db);
349
+ const at = new Date().toISOString();
350
+ const estimated = estimatesOfItems(project, items, (collection) => boards.find((board) => board.collection === collection)?.def);
351
+ return c.json(items.map((item) => {
352
+ const round = boardRoundOf(project, item, boards);
353
+ // The notes of its round: how many, how many wait, and what the agent answered last.
354
+ const notes = notesSummary(project, item, boards);
355
+ // The person's order (app/priority.ts) and the role values an agent estimated.
356
+ const order = priority.get(item.id);
357
+ const estimates = estimated.get(item.id) ?? {};
358
+ // A closed board item: who did it, and whether its branch was merged.
359
+ const row = rowFactsOf(project, item, boards);
360
+ const enteredAt = entered.get(item.id);
361
+ // Set aside for later by an agent (otea release --later): by whom, so the desk says so.
362
+ const setAside = setAsideOf(selectEvents(project.db, item.id));
363
+ // Held by an agent whose question waits for you on another item (P7-R3-9).
364
+ const holderAsks = holderAsksOf(asking, item, at);
365
+ return {
366
+ ...item,
367
+ ...row,
368
+ ...(setAside === undefined ? {} : { setAside }),
369
+ ...(holderAsks === undefined ? {} : { holderAsks }),
370
+ ...(enteredAt === undefined ? {} : { enteredAt }),
371
+ ...(round === undefined ? {} : { round }),
372
+ ...(notes === undefined ? {} : { notes }),
373
+ ...(order === undefined || Object.keys(order).length === 0
374
+ ? {}
375
+ : { priority: order }),
376
+ ...(Object.keys(estimates).length === 0 ? {} : { estimates }),
377
+ };
378
+ }));
379
+ })
380
+ .post('/order', async (c) => {
381
+ assertWritable(c, auth);
382
+ const { collection, ids } = await orderRequest(c);
383
+ setOrder(project, { collection, ids, ...HUMAN_IN_UI });
384
+ feed.notify();
385
+ return c.json({ ok: true });
386
+ })
387
+ .post('/pin', async (c) => {
388
+ assertWritable(c, auth);
389
+ const { ids, pinned } = await pinRequest(c);
390
+ pinItems(project, { ids, pinned, ...HUMAN_IN_UI });
391
+ feed.notify();
392
+ return c.json({ ok: true });
393
+ })
394
+ .post('/items', bodyLimit({ maxSize: MAX_CREATE_BYTES, onError: tooLarge }), async (c) => {
395
+ assertWritable(c, auth, true);
396
+ const clientKey = clientKeyOf(c);
397
+ const { files, ...request } = await createRequest(c);
398
+ // Sent again (a phone that never heard back): the item the first send made, not a second.
399
+ const made = clientKey === undefined ? undefined : itemOfClientKey(project.db, clientKey);
400
+ if (made !== undefined) {
401
+ const { events: _events, ...item } = getItem(project, made);
402
+ c.header('idempotent-replayed', 'true');
403
+ return c.json(item, 200);
404
+ }
405
+ const input = {
406
+ ...request,
407
+ ...HUMAN_IN_UI,
408
+ ...(clientKey === undefined ? {} : { clientKey }),
409
+ };
410
+ const item = files.length === 0
411
+ ? createItem(project, input)
412
+ : createItemWithEvidence(project, input, files);
413
+ feed.notify();
414
+ return c.json(item, 201);
415
+ })
416
+ // Files the person adds to an item that exists, from its page.
417
+ .post('/items/:id/evidence', bodyLimit({ maxSize: MAX_CREATE_BYTES, onError: tooLarge }), async (c) => {
418
+ assertWritable(c, auth, true);
419
+ const files = await attachRequest(c);
420
+ const evidence = attachFiles(project, { id: c.req.param('id'), ...HUMAN_IN_UI }, files);
421
+ feed.notify();
422
+ return c.json(evidence, 201);
423
+ })
424
+ .get('/items/:id', (c) => {
425
+ const id = c.req.param('id');
426
+ let item;
427
+ try {
428
+ item = showItem(project, id, HUMAN_IN_UI);
429
+ }
430
+ catch (error) {
431
+ // The page asks for null rather than a 404 when there is no such item (it says so
432
+ // itself), so a mistyped link leaves no error in the browser's console.
433
+ const missing = error instanceof OteaError && error.details?.kind === 'item_missing';
434
+ if (missing && c.req.query('missing') === 'null')
435
+ return c.json(null);
436
+ throw error;
437
+ }
438
+ const setAside = setAsideOf(item.events);
439
+ if (setAside)
440
+ item = { ...item, setAside };
441
+ const holderAsks = holderAsksOf(askingItems(project.db), item, new Date().toISOString());
442
+ if (holderAsks)
443
+ item = { ...item, holderAsks };
444
+ if (!item.archived)
445
+ return c.json(item);
446
+ // An archived board's collection is in no list: the page reads the item's words from here.
447
+ const collection = listCollectionViews(project, { archived: true }).find(({ name }) => name === item.collection);
448
+ return c.json({ ...item, archived: { ...item.archived, collection } });
449
+ })
450
+ .post('/items/:id/move', async (c) => {
451
+ assertWritable(c, auth);
452
+ const request = await moveRequest(c);
453
+ const item = moveItem(project, { id: c.req.param('id'), ...request, ...HUMAN_IN_UI });
454
+ feed.notify();
455
+ return c.json(item);
456
+ })
457
+ // Notes from the person to the agent doing the item's step: the thread (all of it, or a step
458
+ // and round), and a new note, from the phone too; neither moves the item.
459
+ .get('/items/:id/notes', (c) => {
460
+ const { step } = c.req.query();
461
+ const round = wholeNumber('round', c.req.query('round'), 1);
462
+ const filter = {
463
+ ...(step === undefined ? {} : { step }),
464
+ ...(round === undefined ? {} : { round }),
465
+ };
466
+ return c.json(notesView(project, c.req.param('id'), filter));
467
+ })
468
+ .post('/items/:id/notes', async (c) => {
469
+ assertWritable(c, auth);
470
+ const request = await noteRequest(c);
471
+ const id = c.req.param('id');
472
+ leaveNote(project, { id, ...request, ...HUMAN_IN_UI });
473
+ feed.notify();
474
+ return c.json(notesView(project, id), 201);
475
+ })
476
+ // A review comment changed or taken back while the review is open (app/notes.ts).
477
+ .post('/items/:id/notes/:note/edit', async (c) => {
478
+ assertWritable(c, auth);
479
+ const { text } = await answerRequest(c);
480
+ const id = c.req.param('id');
481
+ const note = wholeNumber('note', c.req.param('note'), 1) ?? 0;
482
+ editNote(project, { id, note, text, ...HUMAN_IN_UI });
483
+ feed.notify();
484
+ return c.json(notesView(project, id));
485
+ })
486
+ .post('/items/:id/notes/:note/withdraw', (c) => {
487
+ assertWritable(c, auth);
488
+ const id = c.req.param('id');
489
+ const note = wholeNumber('note', c.req.param('note'), 1) ?? 0;
490
+ withdrawNote(project, { id, note, ...HUMAN_IN_UI });
491
+ feed.notify();
492
+ return c.json(notesView(project, id));
493
+ })
494
+ // The files the person opened in the reader (app/opened.ts), on the desk or the phone: what
495
+ // Aprobar counts as left unopened, the same on every device. No event, no feed change.
496
+ // What a clone without Otea's hook pushed to the branch of an item in review since its
497
+ // handoff (P3C-R3-1): the desk says so before the person approves. Asked of the remote, so
498
+ // the page asks for it apart from the item.
499
+ .get('/items/:id/drift', async (c) => c.json({ drift: await branchDrift(project, c.req.param('id')) }))
500
+ // An item in its land step whose branch is in the base already, merged outside Otea (P1-R3-9):
501
+ // the page says so instead of «an agent lands it now». Asked of git here, as the CLI does.
502
+ .get('/items/:id/merged-outside', (c) => {
503
+ const merged = mergedOutside(project, project.root, getItem(project, c.req.param('id')));
504
+ return c.json({ merged: merged?.land ? merged : null });
505
+ })
506
+ // The attached diff of an item in review, when it does not come from the tip its handoff
507
+ // recorded (P1-R3-1): the desk says so before the person approves.
508
+ .get('/items/:id/diff-tip', async (c) => c.json({ off: await diffOffTip(project, c.req.param('id')) }))
509
+ .get('/items/:id/opened', (c) => c.json({ evidence: openedFiles(project, c.req.param('id')) }))
510
+ .post('/items/:id/opened', async (c) => {
511
+ assertWritable(c, auth);
512
+ const { evidence } = await openedRequest(c);
513
+ const id = c.req.param('id');
514
+ markOpened(project, { id, evidence, ...HUMAN_IN_UI });
515
+ return c.json({ evidence: openedFiles(project, id) });
516
+ })
517
+ // Side topics (app/topics.ts): the list, one topic, a note that keeps it going, closing it and
518
+ // turning it into a task, from the phone too; turning them on or off is the desk's.
519
+ // A search looks in the items' threads too (app/item-search.ts), and with projects=all in
520
+ // every project this server serves, each topic and item with its project (P6-R2-4).
521
+ .get('/topics', (c) => {
522
+ const search = c.req.query('search') ?? '';
523
+ const filter = { all: c.req.query('all') === '1', search };
524
+ if (c.req.query('projects') === 'all')
525
+ return c.json({
526
+ on: topicsOn(project),
527
+ ...topicsEverywhere(doors.source.list(), project.identity.id, filter),
528
+ });
529
+ return c.json({
530
+ on: topicsOn(project),
531
+ topics: listTopics(project, filter),
532
+ items: searchItems(project, search),
533
+ });
534
+ })
535
+ .post('/topics/switch', async (c) => {
536
+ assertConfigurable(c, auth);
537
+ const { on } = await topicBody(c, TopicsSwitchBody, '{"on": boolean}');
538
+ setTopicsOn(project, on);
539
+ feed.notify();
540
+ return c.json({ on: topicsOn(project), topics: listTopics(project) });
541
+ })
542
+ .get('/topics/:id', (c) => c.json(requireTopic(project, c.req.param('id'))))
543
+ .post('/topics/:id/notes', async (c) => {
544
+ assertWritable(c, auth);
545
+ const { text } = await topicBody(c, TopicNoteBody, '{"text": string}');
546
+ if (text.trim() === '')
547
+ throw new RejectedRequest(400, 'invalid_body', 'Expected a note with some text');
548
+ const topic = noteTopic(project, { id: c.req.param('id'), text, actor: HUMAN_IN_UI.actor });
549
+ feed.notify();
550
+ return c.json(topic, 201);
551
+ })
552
+ .post('/topics/:id/close', (c) => {
553
+ assertWritable(c, auth);
554
+ const topic = closeTopic(project, { id: c.req.param('id'), actor: HUMAN_IN_UI.actor });
555
+ feed.notify();
556
+ return c.json(topic);
557
+ })
558
+ .post('/topics/:id/convert', async (c) => {
559
+ assertWritable(c, auth);
560
+ const { item } = await topicBody(c, TopicConvertBody, '{"item": string}');
561
+ const topic = convertTopic(project, {
562
+ id: c.req.param('id'),
563
+ item,
564
+ actor: HUMAN_IN_UI.actor,
565
+ });
566
+ feed.notify();
567
+ return c.json(topic);
568
+ })
569
+ // An item's topics: those linked to it, and those it may have come from, for the person to
570
+ // confirm or dismiss.
571
+ .get('/items/:id/topics', (c) => {
572
+ const id = c.req.param('id');
573
+ return c.json({
574
+ linked: topicsOfItem(project, id),
575
+ suggested: topicSuggestions(project, id),
576
+ });
577
+ })
578
+ .post('/items/:id/topics/:topic/confirm', (c) => {
579
+ assertWritable(c, auth);
580
+ linkTopic(project, { id: c.req.param('topic'), item: c.req.param('id'), via: 'confirmed' });
581
+ feed.notify();
582
+ return c.json({ ok: true });
583
+ })
584
+ .post('/items/:id/topics/:topic/dismiss', (c) => {
585
+ assertWritable(c, auth);
586
+ dismissTopicSuggestion(project, { id: c.req.param('topic'), item: c.req.param('id') });
587
+ feed.notify();
588
+ return c.json({ ok: true });
589
+ })
590
+ // The person's answer to an agent's question, from the phone too: the turn goes back to the
591
+ // agent, in the same round.
592
+ .post('/items/:id/answer', async (c) => {
593
+ assertWritable(c, auth);
594
+ const { text } = await answerRequest(c);
595
+ const id = c.req.param('id');
596
+ answerQuestion(project, { id, text, ...HUMAN_IN_UI });
597
+ feed.notify();
598
+ return c.json(showItem(project, id, HUMAN_IN_UI));
599
+ })
600
+ .post('/items/:id/update', async (c) => {
601
+ assertWritable(c, auth);
602
+ const { fields } = await updateRequest(c);
603
+ const item = updateItem(project, {
604
+ id: c.req.param('id'),
605
+ fields,
606
+ actor: HUMAN_IN_UI.actor,
607
+ });
608
+ feed.notify();
609
+ return c.json(item);
610
+ })
611
+ .post('/items/:id/undo', async (c) => {
612
+ assertWritable(c, auth);
613
+ const undo = await undoRequest(c);
614
+ const id = c.req.param('id');
615
+ const item = 'from' in undo
616
+ ? undoMove(project, { id, from: undo.from, ...HUMAN_IN_UI })
617
+ : undoRelease(project, { id, ...HUMAN_IN_UI });
618
+ feed.notify();
619
+ return c.json(item);
620
+ })
621
+ // A stuck item: back in the queue of its step (Retomar), or left for an agent (Reasignar).
622
+ .post('/items/:id/restart', (c) => {
623
+ assertWritable(c, auth);
624
+ const item = restartItem(project, { id: c.req.param('id'), ...HUMAN_IN_UI });
625
+ feed.notify();
626
+ return c.json(item);
627
+ })
628
+ // An item an agent set aside for later: the person takes it up again (Retomar, P7-R3-1).
629
+ .post('/items/:id/resume', (c) => {
630
+ assertWritable(c, auth);
631
+ const item = resumeItem(project, { id: c.req.param('id'), ...HUMAN_IN_UI });
632
+ feed.notify();
633
+ return c.json(item);
634
+ })
635
+ .post('/items/:id/reassign', async (c) => {
636
+ assertWritable(c, auth);
637
+ const { agent } = await reassignRequest(c);
638
+ const item = reassignItem(project, { id: c.req.param('id'), agent, ...HUMAN_IN_UI });
639
+ feed.notify();
640
+ return c.json(item);
641
+ })
642
+ .post('/items/:id/link', async (c) => {
643
+ assertWritable(c, auth);
644
+ const request = await linkRequest(c);
645
+ const relation = linkItems(project, { id: c.req.param('id'), ...request, ...HUMAN_IN_UI });
646
+ feed.notify();
647
+ return c.json(relation, 201);
648
+ })
649
+ .post('/items/:id/unlink', async (c) => {
650
+ assertWritable(c, auth);
651
+ const request = await linkRequest(c);
652
+ const relation = unlinkItems(project, {
653
+ id: c.req.param('id'),
654
+ ...request,
655
+ ...HUMAN_IN_UI,
656
+ });
657
+ feed.notify();
658
+ return c.json(relation);
659
+ })
660
+ .post('/brief', async (c) => c.json(briefFor(project, await briefRequest(c))))
661
+ .get('/evidence/:id/file', (c) => {
662
+ assertSignedIn(c, auth, 'open evidence files');
663
+ return serveEvidence(c, project, c.req.param('id'));
664
+ })
665
+ .route('/', boardsApi(project, feed, auth))
666
+ .route('/', notifyApi(machine, notifier, doors.keys, auth, doors))
667
+ .get('/events', (c) => c.json(listEvents(project, eventsFilter(c.req.query()))))
668
+ .get('/stream', (c) => streams.handle(c))
669
+ .all('*', (c) => c.json(errorBody('not_found', `No route ${c.req.path}`), 404)));
670
+ }
671
+ // What an unpaired device on the LAN may reach: the pairing screen, the files it loads, and the
672
+ // two pairing calls. Everything else waits for a device token.
673
+ function isPairingPath(c) {
674
+ const { method, path } = c.req;
675
+ if (method === 'POST')
676
+ return path === '/api/pair' || path === '/api/pair/peek';
677
+ if (method !== 'GET' && method !== 'HEAD')
678
+ return false;
679
+ // The home-screen manifest and icons too: a phone adds Otea to its home screen before it pairs.
680
+ // The service worker is a static file like them; it caches nothing a request was refused.
681
+ return (path === '/pair' ||
682
+ path === '/manifest.webmanifest' ||
683
+ path === '/sw.js' ||
684
+ path.startsWith('/assets/') ||
685
+ path.startsWith('/icons/') ||
686
+ /^\/otea-[a-z-]+\.svg$/.test(path));
687
+ }
688
+ function statusSources(doors) {
689
+ const port = doors.port();
690
+ return {
691
+ port,
692
+ lanUrls: doors.phone.lan?.urls(port) ?? [],
693
+ tailscale: doors.tailscale,
694
+ probe: doors.probe,
695
+ };
696
+ }
697
+ // The Tailscale guide's last step, from the paired devices. A push subscription counts wherever the
698
+ // device paired: browsers give push only to a secure page, and the only HTTPS Otea has is Tailscale.
699
+ // Paired without one counts only once the device reached Otea through Tailscale (a LAN pairing is
700
+ // another origin, whose token the HTTPS page never sees).
701
+ function pairingOf(machine) {
702
+ if (listTargets(machine).some(({ device }) => device !== null))
703
+ return 'push';
704
+ return listDevices(machine).some(({ via }) => via === 'tailscale') ? 'paired' : 'none';
705
+ }
706
+ // The transport's status, whether the local network is open now, and whether opening it may make
707
+ // Windows ask for a firewall permission (Otea never changes the firewall itself).
708
+ async function phoneView(doors) {
709
+ const status = await phoneStatus(doors.machine, statusSources(doors));
710
+ return { ...status, lanOpen: doors.lan.isOpen(), firewallPrompt: process.platform === 'win32' };
711
+ }
712
+ function remoteAddress(c) {
713
+ const incoming = c.env
714
+ ?.incoming;
715
+ const address = incoming?.socket?.remoteAddress;
716
+ return address === undefined ? undefined : plainAddress(address);
717
+ }
718
+ // Last seen is written at most once a minute per device, not on every request.
719
+ const SEEN_EVERY_MS = 60 * 1000;
720
+ // The project a page is on: `/p/<id>/…`.
721
+ const PROJECT_PATH = /^\/p\/([^/]+)(\/.*)?$/;
722
+ // Browsers cap a cookie's lifetime at 400 days.
723
+ const LAST_COOKIE_MAX_AGE = 400 * 24 * 60 * 60;
724
+ // The project a browser last had open on this server, so `/` (the home-screen shortcut, a plain
725
+ // `otea serve`) opens it again. Named after the port, as the session is.
726
+ const lastCookie = (port) => `otea_project_${port}`;
727
+ function isProject(served) {
728
+ return 'db' in served;
729
+ }
730
+ export function createServer(served, options = {}) {
731
+ const source = isProject(served) ? openProjects(served) : served;
732
+ const machine = options.machine ?? memoryMachine();
733
+ const ownMachine = options.machine === undefined;
734
+ const now = options.now ?? Date.now;
735
+ let port = DEFAULT_PORT;
736
+ const app = new Hono();
737
+ const lan = options.lan
738
+ ? openLan({ addresses: options.lan.addresses, names: options.lan.names ?? [] })
739
+ : lanAccess(app.fetch, () => port, options.network);
740
+ const tailscaleDoor = () => {
741
+ const { transport, tailscaleHost } = phoneSettings(machine);
742
+ return transport === 'tailscale' && tailscaleHost
743
+ ? tailscaleTransport(tailscaleHost)
744
+ : undefined;
745
+ };
746
+ const phone = {
747
+ get lan() {
748
+ return lan.transport();
749
+ },
750
+ codes: new PairingCodes(now),
751
+ attempts: new AttemptLimiter(now),
752
+ settings: () => phoneSettings(machine),
753
+ doors: () => [tailscaleDoor(), lan.transport()].filter((door) => door !== undefined),
754
+ chosen: () => phoneSettings(machine).transport === 'tailscale' ? tailscaleDoor() : lan.transport(),
755
+ };
756
+ // A request one of the open phone doors admits is a device's: from the local network, a private
757
+ // address naming one of this computer's addresses or its own .local name (any other DNS name is
758
+ // how a rebinding page gets in); through Tailscale, what tailscale serve forwards. It carries a
759
+ // device token or reaches only the pairing screen. Any other request must come from this computer
760
+ // and name localhost; one a proxy forwarded (X-Forwarded-For) is never this computer's own.
761
+ const identify = (c) => {
762
+ const host = c.req.header('host');
763
+ const remote = remoteAddress(c);
764
+ const arrival = { host, remote, forwardedFor: c.req.header('x-forwarded-for') };
765
+ const admission = phone
766
+ .doors()
767
+ .map((door) => door.admit(arrival, port))
768
+ .find((admitted) => admitted !== undefined);
769
+ if (!admission) {
770
+ const here = remote === undefined || isLoopback(remote);
771
+ if (!here || proxied(arrival) || !isAllowedHost(host, port)) {
772
+ throw new ForbiddenHost(`Host "${host ?? ''}" is not allowed`);
773
+ }
774
+ return { kind: 'local' };
775
+ }
776
+ const { address, secure } = admission;
777
+ const device = deviceByToken(machine, getCookie(c, deviceCookie(port)) ?? '');
778
+ if (!device)
779
+ return { kind: 'unpaired', address, secure };
780
+ const seen = device.lastSeenAt === null ? 0 : Date.parse(device.lastSeenAt);
781
+ // How it came in now, kept with the time: the Tailscale guide's last step reads it.
782
+ const via = viaOf(secure);
783
+ if (now() - seen >= SEEN_EVERY_MS || device.via !== via) {
784
+ touchDevice(machine, device.id, new Date(now()), via);
785
+ }
786
+ return { kind: 'device', device, address, secure };
787
+ };
788
+ // Each project's API runs as its own app; the client the root identified travels with the request.
789
+ const clients = new WeakMap();
790
+ app.use(async (c, next) => {
791
+ const client = identify(c);
792
+ c.set('client', client);
793
+ clients.set(c.req.raw, client);
794
+ if (client.kind === 'unpaired' && !isPairingPath(c)) {
795
+ if (c.req.method === 'GET' && !isApiPath(c.req.path))
796
+ return c.redirect('/pair', 302);
797
+ throw new RejectedRequest(401, 'unpaired', 'This device is not paired; scan the pairing code shown on the desk');
798
+ }
799
+ await next();
800
+ });
801
+ const boundPort = () => port;
802
+ mountAuth(app, options.token, boundPort);
803
+ const keys = options.notify?.keys ?? generateVapidKeys();
804
+ const sender = options.notify?.sender ?? webPushSender(keys);
805
+ const hosts = new Map();
806
+ const auth = session(options.token, boundPort);
807
+ const computer = options.computer ?? 'Otea';
808
+ const onError = (error, c) => {
809
+ if (error instanceof ForbiddenHost && wantsPage(c)) {
810
+ return c.html(wrongAddressPage(c.req.header('accept-language')), 403);
811
+ }
812
+ const { status, body } = toErrorResponse(error);
813
+ return c.json(body, status);
814
+ };
815
+ const doors = {
816
+ lan,
817
+ machine,
818
+ source,
819
+ changed() {
820
+ for (const host of hosts.values()) {
821
+ host.notifier.refresh();
822
+ host.feed.notify();
823
+ }
824
+ },
825
+ keys,
826
+ auth,
827
+ phone,
828
+ port: boundPort,
829
+ env: options.env ?? process.env,
830
+ tailscale: options.tailscale ?? NO_TAILSCALE,
831
+ probe: options.probe ?? fetchProbe,
832
+ gitHook: options.gitHook,
833
+ sender,
834
+ log: options.notify?.log ?? (() => undefined),
835
+ };
836
+ const open = (project) => {
837
+ const { id } = project.identity;
838
+ const feed = createChangeFeed(project.db, options.pollIntervalMs);
839
+ const streams = liveStreams(feed, () => presenceSignature(project.db));
840
+ const notifier = createNotifier(project, feed, {
841
+ sender,
842
+ targets: machine,
843
+ now,
844
+ log: doors.log,
845
+ ...(options.notify?.tickMs === undefined ? {} : { tickMs: options.notify.tickMs }),
846
+ ...(options.notify?.minuteOfDay === undefined
847
+ ? {}
848
+ : { minuteOfDay: options.notify.minuteOfDay }),
849
+ });
850
+ // Devices subscribed before this start are told from now on.
851
+ notifier.refresh();
852
+ const live = { feed, streams, notifier };
853
+ const projectApp = new Hono().basePath(`/p/${id}`);
854
+ projectApp.use(async (c, next) => {
855
+ c.set('client', clients.get(c.req.raw) ?? LOCAL);
856
+ await next();
857
+ // Whose answer it is, for the installed app's cache and its queue (ui/src/offline).
858
+ c.header('x-otea-project', id);
859
+ });
860
+ // A write made for another project (a capture queued on the phone): never applied to this one.
861
+ projectApp.use('/api/*', async (c, next) => {
862
+ const meant = c.req.header('x-otea-project');
863
+ if (c.req.method !== 'GET' && meant && meant !== id)
864
+ throw new RejectedRequest(409, 'other_project', 'This was made for another project, not the one at this address');
865
+ await next();
866
+ });
867
+ projectApp.route('/api', api(project, live, doors));
868
+ projectApp.onError(onError);
869
+ const host = { ...live, app: projectApp };
870
+ hosts.set(id, host);
871
+ return host;
872
+ };
873
+ const hostOf = (id) => {
874
+ const held = hosts.get(id);
875
+ if (held)
876
+ return held;
877
+ const project = source.get(id);
878
+ return project ? open(project) : undefined;
879
+ };
880
+ const sync = () => {
881
+ for (const each of source.list())
882
+ if (each.project)
883
+ hostOf(each.id);
884
+ };
885
+ // The pairing screen's two calls: a device pairs with the computer, not with one project.
886
+ app.post('/api/pair/peek', async (c) => c.json(await peekPairing(c, computer, phone)));
887
+ app.post('/api/pair', async (c) => {
888
+ const paired = await pair(c, machine, computer, phone, boundPort);
889
+ doors.changed();
890
+ return c.json(paired, 201);
891
+ });
892
+ app.route('/api', machineApi(doors));
893
+ app.all('/api/*', (c) => c.json(errorBody('not_found', `No route ${c.req.path}; a project's API is at /p/<id>/api`), 404));
894
+ // `/`: the project this browser had open last, else the first one served.
895
+ app.get('/', (c) => {
896
+ const last = getCookie(c, lastCookie(port));
897
+ const listed = source.list().filter((each) => each.project);
898
+ const target = listed.find((each) => each.id === last) ?? listed[0];
899
+ if (!target)
900
+ return c.text(NO_PROJECTS, 404);
901
+ return c.redirect(`/p/${target.id}/`, 302);
902
+ });
903
+ app.all('/p/*', async (c, next) => {
904
+ const match = PROJECT_PATH.exec(c.req.path);
905
+ const id = match?.[1] ?? '';
906
+ const rest = match?.[2] ?? '';
907
+ const host = hostOf(id);
908
+ if (isApiPath(rest)) {
909
+ if (!host) {
910
+ throw new RejectedRequest(404, 'no_project', `This server serves no project ${id}`);
911
+ }
912
+ return host.app.fetch(c.req.raw, c.env);
913
+ }
914
+ if (c.req.method !== 'GET' && c.req.method !== 'HEAD')
915
+ return next();
916
+ // A project no longer served (forgotten, its data gone): the home opens another.
917
+ if (!host)
918
+ return c.redirect('/', 302);
919
+ if (rest === '')
920
+ return c.redirect(`/p/${id}/`, 301);
921
+ setCookie(c, lastCookie(port), id, {
922
+ path: '/',
923
+ sameSite: 'Lax',
924
+ maxAge: LAST_COOKIE_MAX_AGE,
925
+ });
926
+ await next();
927
+ });
928
+ mountUi(app, options.uiDir ?? BUILT_UI_DIR);
929
+ app.onError(onError);
930
+ sync();
931
+ let closed = false;
932
+ return {
933
+ app,
934
+ machine,
935
+ phone,
936
+ lan,
937
+ notifierOf: (id) => hosts.get(id)?.notifier,
938
+ routesOf: (id) => (hostOf(id)?.app.routes ?? []).map(({ method, path }) => ({ method, path })),
939
+ sync,
940
+ listeningOn(listened) {
941
+ port = listened;
942
+ },
943
+ close() {
944
+ if (closed)
945
+ return;
946
+ closed = true;
947
+ void lan.close();
948
+ for (const host of hosts.values()) {
949
+ host.notifier.close();
950
+ host.streams.closeAll();
951
+ host.feed.close();
952
+ }
953
+ hosts.clear();
954
+ source.close();
955
+ if (ownMachine)
956
+ machine.close();
957
+ },
958
+ };
959
+ }
960
+ const NO_PROJECTS = 'This Otea server serves no project yet. Run "otea init" in a project folder, then "otea open" there.';