@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.
- package/LICENSE +661 -0
- package/README.es.md +151 -0
- package/README.md +251 -3
- package/THIRD_PARTY_NOTICES.md +114 -0
- package/bin/otea.mjs +28 -0
- package/dist/app/agent-detail.js +26 -0
- package/dist/app/agent-draft.js +429 -0
- package/dist/app/agent-prompts.js +52 -0
- package/dist/app/agents.js +77 -0
- package/dist/app/asking.js +43 -0
- package/dist/app/board-archive.js +243 -0
- package/dist/app/board-migration.js +272 -0
- package/dist/app/boards.js +870 -0
- package/dist/app/branch-owner.js +48 -0
- package/dist/app/brief.js +53 -0
- package/dist/app/choices.js +61 -0
- package/dist/app/collections.js +101 -0
- package/dist/app/context.js +1 -0
- package/dist/app/crop.js +56 -0
- package/dist/app/devices.js +62 -0
- package/dist/app/draft-request.js +82 -0
- package/dist/app/events.js +12 -0
- package/dist/app/evidence.js +287 -0
- package/dist/app/gates.js +610 -0
- package/dist/app/guide.js +37 -0
- package/dist/app/home.js +145 -0
- package/dist/app/init-boards.js +36 -0
- package/dist/app/intake.js +25 -0
- package/dist/app/item-search.js +141 -0
- package/dist/app/items.js +318 -0
- package/dist/app/keep-waiting.js +44 -0
- package/dist/app/land-order.js +107 -0
- package/dist/app/language.js +52 -0
- package/dist/app/launcher.js +56 -0
- package/dist/app/lease-take.js +54 -0
- package/dist/app/leases.js +86 -0
- package/dist/app/machine.js +39 -0
- package/dist/app/merged.js +89 -0
- package/dist/app/migrate.js +171 -0
- package/dist/app/next.js +1637 -0
- package/dist/app/notes.js +319 -0
- package/dist/app/notify-targets.js +113 -0
- package/dist/app/opened.js +25 -0
- package/dist/app/owner-only.js +34 -0
- package/dist/app/performance.js +28 -0
- package/dist/app/phone.js +97 -0
- package/dist/app/presence.js +596 -0
- package/dist/app/preset-views.js +25 -0
- package/dist/app/presets.js +129 -0
- package/dist/app/priority.js +156 -0
- package/dist/app/profile.js +86 -0
- package/dist/app/project.js +247 -0
- package/dist/app/proofs.js +179 -0
- package/dist/app/questions.js +215 -0
- package/dist/app/reader-filter.js +58 -0
- package/dist/app/relations.js +164 -0
- package/dist/app/relay.js +98 -0
- package/dist/app/repos.js +176 -0
- package/dist/app/restart.js +92 -0
- package/dist/app/set-aside.js +64 -0
- package/dist/app/system-locale.js +6 -0
- package/dist/app/tailscale-cli.js +77 -0
- package/dist/app/tailscale-testing.js +41 -0
- package/dist/app/tailscale.js +177 -0
- package/dist/app/tips.js +30 -0
- package/dist/app/topics-everywhere.js +53 -0
- package/dist/app/topics.js +453 -0
- package/dist/app/undo.js +52 -0
- package/dist/app/validate.js +131 -0
- package/dist/app/watch.js +48 -0
- package/dist/cli/command.js +44 -0
- package/dist/cli/commands.js +3303 -0
- package/dist/cli/exit-codes.js +70 -0
- package/dist/cli/forge.js +176 -0
- package/dist/cli/format.js +340 -0
- package/dist/cli/gh.js +17 -0
- package/dist/cli/gitrepo.js +489 -0
- package/dist/cli/help.js +101 -0
- package/dist/cli/hooks.js +232 -0
- package/dist/cli/main.js +37 -0
- package/dist/cli/merged-outside.js +58 -0
- package/dist/cli/names.js +154 -0
- package/dist/cli/opener.js +21 -0
- package/dist/cli/owner.js +154 -0
- package/dist/cli/phone.js +221 -0
- package/dist/cli/ports.js +24 -0
- package/dist/cli/probe.js +18 -0
- package/dist/cli/run.js +246 -0
- package/dist/cli/serve-file.js +21 -0
- package/dist/cli/stats.js +55 -0
- package/dist/cli/version.js +3 -0
- package/dist/core/agent-guide.js +31 -0
- package/dist/core/agent-prompts.js +139 -0
- package/dist/core/authority.js +94 -0
- package/dist/core/board/analysis.js +86 -0
- package/dist/core/board/choices.js +100 -0
- package/dist/core/board/compile.js +362 -0
- package/dist/core/board/engine.js +523 -0
- package/dist/core/board/hints.js +46 -0
- package/dist/core/board/history.js +146 -0
- package/dist/core/board/ids.js +87 -0
- package/dist/core/board/joins.js +30 -0
- package/dist/core/board/mentions.js +68 -0
- package/dist/core/board/merged.js +18 -0
- package/dist/core/board/model.js +135 -0
- package/dist/core/board/next.js +1116 -0
- package/dist/core/board/notes.js +298 -0
- package/dist/core/board/performance.js +218 -0
- package/dist/core/board/plan.js +299 -0
- package/dist/core/board/problems.js +232 -0
- package/dist/core/board/proofs.js +84 -0
- package/dist/core/board/questions.js +114 -0
- package/dist/core/board/reading.js +220 -0
- package/dist/core/board/readings.js +534 -0
- package/dist/core/board/schema.js +335 -0
- package/dist/core/board/shape-words.js +179 -0
- package/dist/core/board/template-words.js +23 -0
- package/dist/core/board/templates-catalogue.js +965 -0
- package/dist/core/board/templates-coverage.js +261 -0
- package/dist/core/board/templates-flows.js +779 -0
- package/dist/core/board/templates.js +586 -0
- package/dist/core/brief.js +93 -0
- package/dist/core/diagram.js +80 -0
- package/dist/core/errors.js +12 -0
- package/dist/core/evidence.js +33 -0
- package/dist/core/fields.js +129 -0
- package/dist/core/hierarchy.js +30 -0
- package/dist/core/icons.js +181 -0
- package/dist/core/image-crop.js +166 -0
- package/dist/core/item.js +49 -0
- package/dist/core/lease.js +31 -0
- package/dist/core/modules.js +318 -0
- package/dist/core/notify/planner.js +117 -0
- package/dist/core/notify/signals.js +66 -0
- package/dist/core/notify/text.js +60 -0
- package/dist/core/path-key.js +22 -0
- package/dist/core/placement.js +161 -0
- package/dist/core/preset-labels.js +66 -0
- package/dist/core/preset-notes.js +109 -0
- package/dist/core/preset.js +541 -0
- package/dist/core/profile.js +55 -0
- package/dist/core/project-id.js +20 -0
- package/dist/core/refusal.js +1 -0
- package/dist/core/relations.js +208 -0
- package/dist/core/repo.js +54 -0
- package/dist/core/samples.js +161 -0
- package/dist/core/search-words.js +68 -0
- package/dist/core/test-report.js +120 -0
- package/dist/core/time.js +8 -0
- package/dist/core/validation.js +60 -0
- package/dist/core/views.js +171 -0
- package/dist/core/workflow.js +51 -0
- package/dist/mcp/commands.js +101 -0
- package/dist/mcp/server.js +239 -0
- package/dist/mcp/words.js +95 -0
- package/dist/server/boards.js +232 -0
- package/dist/server/changes.js +42 -0
- package/dist/server/diff-tip.js +83 -0
- package/dist/server/drift.js +87 -0
- package/dist/server/errors.js +87 -0
- package/dist/server/evidence.js +82 -0
- package/dist/server/hosts.js +6 -0
- package/dist/server/hub.js +98 -0
- package/dist/server/lan-access.js +62 -0
- package/dist/server/lan.js +164 -0
- package/dist/server/listen.js +70 -0
- package/dist/server/notifier.js +156 -0
- package/dist/server/notify-api.js +151 -0
- package/dist/server/pairing.js +124 -0
- package/dist/server/projects.js +191 -0
- package/dist/server/push.js +199 -0
- package/dist/server/server.js +960 -0
- package/dist/server/session.js +43 -0
- package/dist/server/stream.js +36 -0
- package/dist/server/test-push.js +38 -0
- package/dist/server/token.js +37 -0
- package/dist/server/transports.js +54 -0
- package/dist/server/ui.js +44 -0
- package/dist/server/writes.js +361 -0
- package/dist/server/wrong-address.js +36 -0
- package/dist/store/boards.js +111 -0
- package/dist/store/database.js +45 -0
- package/dist/store/machine.js +77 -0
- package/dist/store/migrations.js +493 -0
- package/dist/store/queries.js +585 -0
- package/dist/store/registry.js +72 -0
- package/package.json +72 -4
- package/presets/architecture/playbook.md +69 -0
- package/presets/architecture/preset.yaml +80 -0
- package/presets/architecture/samples.yaml +23 -0
- package/presets/bug-triage/playbook.md +129 -0
- package/presets/bug-triage/preset.yaml +127 -0
- package/presets/bug-triage/samples/wall-slide-after.png +0 -0
- package/presets/bug-triage/samples/wall-slide-before.png +0 -0
- package/presets/bug-triage/samples.yaml +72 -0
- package/presets/change/playbook.md +115 -0
- package/presets/change/preset.yaml +141 -0
- package/presets/change/samples.yaml +62 -0
- package/presets/review/playbook.md +51 -0
- package/presets/review/preset.yaml +62 -0
- package/presets/review/samples.yaml +27 -0
- package/presets/tasks/playbook.md +78 -0
- package/presets/tasks/preset.yaml +61 -0
- package/presets/tasks/samples.yaml +46 -0
- package/schemas/board.schema.json +764 -0
- package/ui/dist/THIRD_PARTY_NOTICES.md +114 -0
- package/ui/dist/assets/dm-mono-latin-400-normal--0xN8mdc.woff +0 -0
- package/ui/dist/assets/dm-mono-latin-400-normal-4GdczIuU.woff2 +0 -0
- package/ui/dist/assets/dm-mono-latin-500-normal-CN8Miw6E.woff +0 -0
- package/ui/dist/assets/dm-mono-latin-500-normal-DRMDZjhP.woff2 +0 -0
- package/ui/dist/assets/dm-mono-latin-ext-400-normal-1aZr6b2b.woff +0 -0
- package/ui/dist/assets/dm-mono-latin-ext-400-normal-C2zvOubV.woff2 +0 -0
- package/ui/dist/assets/dm-mono-latin-ext-500-normal-BtRyHRi6.woff2 +0 -0
- package/ui/dist/assets/dm-mono-latin-ext-500-normal-Dw3M13d8.woff +0 -0
- package/ui/dist/assets/index-C3OzJope.js +103 -0
- package/ui/dist/assets/index-COdEjckQ.css +1 -0
- package/ui/dist/assets/newsreader-latin-ext-opsz-italic-CSPGnFdO.woff2 +0 -0
- package/ui/dist/assets/newsreader-latin-ext-opsz-normal-BQn1nviT.woff2 +0 -0
- package/ui/dist/assets/newsreader-latin-opsz-italic-kJKFiXvB.woff2 +0 -0
- package/ui/dist/assets/newsreader-latin-opsz-normal-s-izfB6B.woff2 +0 -0
- package/ui/dist/assets/newsreader-vietnamese-opsz-italic-DTr-ymY4.woff2 +0 -0
- package/ui/dist/assets/newsreader-vietnamese-opsz-normal-BjhtXyW2.woff2 +0 -0
- package/ui/dist/assets/pdf-YwugTw7Y.js +54 -0
- package/ui/dist/assets/pdf-engine-CkBopwck.js +1 -0
- package/ui/dist/assets/pdf-rELvHkft.js +56 -0
- package/ui/dist/assets/pdf.worker.min-B5Yc7dP4.mjs +27 -0
- package/ui/dist/assets/pdf.worker.min-B7U8ptvh.js +1 -0
- package/ui/dist/assets/pdf.worker.min-CIqJB0yW.mjs +28 -0
- package/ui/dist/assets/pdf.worker.min-UqOn5EDC.js +1 -0
- package/ui/dist/assets/schibsted-grotesk-latin-ext-wght-normal-hsMS0n0O.woff2 +0 -0
- package/ui/dist/assets/schibsted-grotesk-latin-wght-normal-Bb8VGrTG.woff2 +0 -0
- package/ui/dist/icons/apple-touch-icon.png +0 -0
- package/ui/dist/icons/otea-192.png +0 -0
- package/ui/dist/icons/otea-512.png +0 -0
- package/ui/dist/icons/otea-badge.png +0 -0
- package/ui/dist/icons/otea-maskable-512.png +0 -0
- package/ui/dist/index.html +25 -0
- package/ui/dist/manifest.webmanifest +24 -0
- package/ui/dist/otea-idle.svg +5 -0
- package/ui/dist/otea-working.svg +5 -0
- package/ui/dist/otea-yours-working.svg +5 -0
- package/ui/dist/otea-yours.svg +5 -0
- package/ui/dist/sw.js +1 -0
|
@@ -0,0 +1,3303 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { hostname } from 'node:os';
|
|
3
|
+
import { extname, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { renderUnicodeCompact } from 'uqr';
|
|
6
|
+
import { draftToStartFrom, proposeAgentDraft, proposeBoardChange, submitAgentDraft, } from '../app/agent-draft.js';
|
|
7
|
+
import { promptFacts, promptKindOf } from '../app/agent-prompts.js';
|
|
8
|
+
import { assertPinned, MCP_SERVER, mcpEntry, oldMcpEntry, writeAgentsMd, } from '../app/agents.js';
|
|
9
|
+
import { addBoard, addBoardSet, syncBoardPresets } from '../app/boards.js';
|
|
10
|
+
import { branchNamedFirst } from '../app/branch-owner.js';
|
|
11
|
+
import { briefFor } from '../app/brief.js';
|
|
12
|
+
import { collectionIcon, getCollection, presetOf, setCollectionIcon, typeOfItem, } from '../app/collections.js';
|
|
13
|
+
import { cropNote } from '../app/crop.js';
|
|
14
|
+
import { listDevices, revokeDevice } from '../app/devices.js';
|
|
15
|
+
import { handInText, openDraftsOf } from '../app/draft-request.js';
|
|
16
|
+
import { listEvents } from '../app/events.js';
|
|
17
|
+
import { attachEvidence, detachEvidence, evidenceReadPath } from '../app/evidence.js';
|
|
18
|
+
import { checkGate, protectedBases } from '../app/gates.js';
|
|
19
|
+
import { boardGuide, guideIndex, hintFor } from '../app/guide.js';
|
|
20
|
+
import { forgetProjectPath, listProjects, oteaHome, relinkProjectPath, withRegistry, } from '../app/home.js';
|
|
21
|
+
import { hasOwnBoards, initBoards, NO_BOARDS } from '../app/init-boards.js';
|
|
22
|
+
import { itemHitsText, searchItems } from '../app/item-search.js';
|
|
23
|
+
import { createItem, getItem, listItems, moveItem, oldestWaiting, showItem, systemClock, updateItem, } from '../app/items.js';
|
|
24
|
+
import { keepWaitingCommand, keepWaitingLine, waitAgainLine } from '../app/keep-waiting.js';
|
|
25
|
+
import { defaultLang } from '../app/language.js';
|
|
26
|
+
import { oteaLauncher, withHome } from '../app/launcher.js';
|
|
27
|
+
import { claimItem, heartbeatItem, releaseItem } from '../app/leases.js';
|
|
28
|
+
import { openMachine, rememberLocalProject, withMachine } from '../app/machine.js';
|
|
29
|
+
import { markMerged, reopenItem } from '../app/merged.js';
|
|
30
|
+
import { migrateToCommon } from '../app/migrate.js';
|
|
31
|
+
import { approveItem, createdTextOf, dropItem, handoffItem, laterLine, liveBoardOf, liveBoards, mergeFirstFor, nextFor, offerableTo, rowFactsOf, sendBackItem, wokeLines, } from '../app/next.js';
|
|
32
|
+
import { agentNotes, noteWaiting, replyNote, roundNotesOf } from '../app/notes.js';
|
|
33
|
+
import { performanceOf } from '../app/performance.js';
|
|
34
|
+
import { lanOpen } from '../app/phone.js';
|
|
35
|
+
import { beatProcess, claimName, endListening, endProcess, endWaiter, endWaiting, harnessKey, hearAgent, LISTEN_BEAT_MS, listAgents, mcpLoaded, nameFor, noteCall, offerName, quietVoices, renewLeases, seeAgent, startProcess, waitBeat, } from '../app/presence.js';
|
|
36
|
+
import { priorityOf } from '../app/priority.js';
|
|
37
|
+
import { declareProfile, presetProfile, profileCommand, profileReminder, requireProfile, } from '../app/profile.js';
|
|
38
|
+
import { addPathToProject, initProject, openProject, projectView, setProjectIcon, } from '../app/project.js';
|
|
39
|
+
import { tickPoint } from '../app/proofs.js';
|
|
40
|
+
import { answerWaiting, askedByAgent, askQuestion, noteChatAnswer, wakesWhileAsking, } from '../app/questions.js';
|
|
41
|
+
import { readerFilter } from '../app/reader-filter.js';
|
|
42
|
+
import { linkItems, unlinkItems } from '../app/relations.js';
|
|
43
|
+
import { relayDecision } from '../app/relay.js';
|
|
44
|
+
import { addRepo, listRepos, readReposAtFolder, removeRepo, repoNameAt, UnknownRepo, } from '../app/repos.js';
|
|
45
|
+
import { approvedTipOf } from '../app/tips.js';
|
|
46
|
+
import { addTopic, answerTopic, closeTopic, linkTopic, listTopics, noteTopic, requireTopic, requireTopicsOn, setTopicsOn, topicsAwaiting, topicsAwaitingText, topicsListText, topicsOn, topicText, topicWaiting, } from '../app/topics.js';
|
|
47
|
+
import { topicsEverywhere, topicsEverywhereText } from '../app/topics-everywhere.js';
|
|
48
|
+
import { validateProject } from '../app/validate.js';
|
|
49
|
+
import { watch } from '../app/watch.js';
|
|
50
|
+
import { agentGuideFor, TOPICS_REMINDER, TOPICS_RULE } from '../core/agent-guide.js';
|
|
51
|
+
import { agentPrompt, isPromptKind, PROMPT_KINDS } from '../core/agent-prompts.js';
|
|
52
|
+
import { isClosed, isLandStep, positionOf, waysOf } from '../core/board/engine.js';
|
|
53
|
+
import { DONE, guardedBranch, isEvidence, stepById } from '../core/board/model.js';
|
|
54
|
+
import { DROPPED_NAME } from '../core/board/next.js';
|
|
55
|
+
import { attachedPart, fieldsByName, partByName, stateName } from '../core/board/reading.js';
|
|
56
|
+
import { isSetKey, LANGS, LISTED_KEYS, TEMPLATE_SETS, TEMPLATES } from '../core/board/templates.js';
|
|
57
|
+
import { parseDiagram } from '../core/diagram.js';
|
|
58
|
+
import { OteaError } from '../core/errors.js';
|
|
59
|
+
import { EVIDENCE_ROLES, MAX_EVIDENCE_MB } from '../core/evidence.js';
|
|
60
|
+
import { assertIconName } from '../core/icons.js';
|
|
61
|
+
import { assertAgentName } from '../core/item.js';
|
|
62
|
+
import { parseDuration } from '../core/lease.js';
|
|
63
|
+
import { profileLine } from '../core/profile.js';
|
|
64
|
+
import { describeRelation, RELATION_KINDS } from '../core/relations.js';
|
|
65
|
+
import { timeText } from '../core/time.js';
|
|
66
|
+
import { TURNS } from '../core/workflow.js';
|
|
67
|
+
import { DEFAULT_PORT } from '../server/hosts.js';
|
|
68
|
+
import { machineProjects } from '../server/hub.js';
|
|
69
|
+
import { formatCode } from '../server/lan.js';
|
|
70
|
+
import { ensureVapidKeys } from '../server/push.js';
|
|
71
|
+
import { ensureUiToken, readUiToken } from '../server/token.js';
|
|
72
|
+
import { findAgent, findProfile, forgetAgent, markMcpAsked, profileView, selectMcpLoads, } from '../store/queries.js';
|
|
73
|
+
import { CommandFailure, failureCode, UsageError, } from './command.js';
|
|
74
|
+
import { installForge, removeForge } from './forge.js';
|
|
75
|
+
import { columns, formatEvent, formatEvidence, formatItem, formatItems, formatItemWithEvents, formatReport, indent, } from './format.js';
|
|
76
|
+
import { prState } from './gh.js';
|
|
77
|
+
import { branchesBrought, checkedOutBranch, checkoutRoot, commitsOver, currentBranch, hasCommit, inMainCheckout, landedIn, mergeTake, pushState, remoteOf, rewritesRemote, tipOf, } from './gitrepo.js';
|
|
78
|
+
import { gitHookOf, installGitHook, outdatedGitHookLine, removeClaudeHook, removeGitHook, } from './hooks.js';
|
|
79
|
+
import { mergedOutside, mergedOutsideLine } from './merged-outside.js';
|
|
80
|
+
import { boardsOf, eventData, itemCollections, itemData, readableEvent } from './names.js';
|
|
81
|
+
import { watchOwner } from './owner.js';
|
|
82
|
+
import { PHONE_COMMANDS } from './phone.js';
|
|
83
|
+
import { portFrom, portToOpen, projectPage } from './ports.js';
|
|
84
|
+
import { probeSignIn } from './probe.js';
|
|
85
|
+
import { readServeFile, removeServeFile, writeServeFile } from './serve-file.js';
|
|
86
|
+
import { statsText } from './stats.js';
|
|
87
|
+
// The text names an item's type only when its collection's preset has several.
|
|
88
|
+
function typesShown(project) {
|
|
89
|
+
const several = new Map();
|
|
90
|
+
return ({ collection }) => {
|
|
91
|
+
const known = several.get(collection);
|
|
92
|
+
if (known !== undefined)
|
|
93
|
+
return known;
|
|
94
|
+
const shown = presetOf(project, getCollection(project.db, collection)).types.length > 1;
|
|
95
|
+
several.set(collection, shown);
|
|
96
|
+
return shown;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function itemResult(project, item) {
|
|
100
|
+
return {
|
|
101
|
+
data: itemData(project, item),
|
|
102
|
+
text: formatItem(readable(project, item), typesShown(project)),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
// An item on a board as its reader says it: its step by name, its fields and choices by name, its
|
|
106
|
+
// moves and events by step names. Hidden ids stay in --json, as the keys a program reads.
|
|
107
|
+
function readable(project, raw) {
|
|
108
|
+
// Each related item's step by name, on its own board.
|
|
109
|
+
const related = raw.relations;
|
|
110
|
+
const item = (related
|
|
111
|
+
? {
|
|
112
|
+
...raw,
|
|
113
|
+
relations: related.map((r) => {
|
|
114
|
+
// A list's relations are bare refs (no collection or state): nothing to name.
|
|
115
|
+
const { collection, state } = r;
|
|
116
|
+
if (typeof collection !== 'string' || typeof state !== 'string')
|
|
117
|
+
return r;
|
|
118
|
+
const on = liveBoardOf(project, collection);
|
|
119
|
+
return on ? { ...r, state: stateName(on.def, state) } : r;
|
|
120
|
+
}),
|
|
121
|
+
}
|
|
122
|
+
: raw);
|
|
123
|
+
const board = liveBoardOf(project, item.collection);
|
|
124
|
+
if (!board)
|
|
125
|
+
return item;
|
|
126
|
+
const { def } = board;
|
|
127
|
+
const named = (state) => stateName(def, String(state));
|
|
128
|
+
const out = {
|
|
129
|
+
...item,
|
|
130
|
+
state: named(item.state),
|
|
131
|
+
fields: fieldsByName(def, item.fields),
|
|
132
|
+
};
|
|
133
|
+
const view = item;
|
|
134
|
+
// A drop with each motive is a state of its own, all named Dropped: said once, with the motives.
|
|
135
|
+
const motives = def.drop.motives.map(({ name }) => name);
|
|
136
|
+
const moves = (list) => {
|
|
137
|
+
const said = new Map();
|
|
138
|
+
for (const move of list) {
|
|
139
|
+
const to = named(move.to);
|
|
140
|
+
if (said.has(to))
|
|
141
|
+
continue;
|
|
142
|
+
const drop = to === DROPPED_NAME && motives.length > 0;
|
|
143
|
+
said.set(to, { ...move, to, ...(drop ? { motives } : {}) });
|
|
144
|
+
}
|
|
145
|
+
return [...said.values()];
|
|
146
|
+
};
|
|
147
|
+
const partName = (ref) => def.parts[String(ref)]?.name ?? String(ref);
|
|
148
|
+
if (view.transitions)
|
|
149
|
+
out.transitions = moves(view.transitions);
|
|
150
|
+
if (view.relayable)
|
|
151
|
+
out.relayable = moves(view.relayable);
|
|
152
|
+
if (view.missing)
|
|
153
|
+
out.missing = view.missing.map(partName);
|
|
154
|
+
if (view.evidence)
|
|
155
|
+
out.evidence = view.evidence.map((entry) => entry.module === null ? entry : { ...entry, module: partName(entry.module) });
|
|
156
|
+
if (view.events)
|
|
157
|
+
out.events = view.events.map((event) => readableEvent(def, event));
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
function withProject(cwd, use) {
|
|
161
|
+
const project = openProject(cwd);
|
|
162
|
+
try {
|
|
163
|
+
return use(project);
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
project.db.close();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function withProjectWhile(cwd, use) {
|
|
170
|
+
const project = openProject(cwd);
|
|
171
|
+
try {
|
|
172
|
+
return await use(project);
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
project.db.close();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// Notes that the agent running the command was seen, so the UI can show who is at work.
|
|
179
|
+
function seen(project, input, actor = input.actor) {
|
|
180
|
+
const { channel, harness, newSession } = input;
|
|
181
|
+
if (actor.kind !== 'agent')
|
|
182
|
+
return;
|
|
183
|
+
// Through an MCP server the agent is connected: the open server is listening for it.
|
|
184
|
+
const note = channel === 'mcp' ? hearAgent : seeAgent;
|
|
185
|
+
note(project.db, {
|
|
186
|
+
agent: actor.name,
|
|
187
|
+
channel,
|
|
188
|
+
harness,
|
|
189
|
+
folder: input.cwd,
|
|
190
|
+
...(newSession ? { newSession } : {}),
|
|
191
|
+
call: true,
|
|
192
|
+
});
|
|
193
|
+
// Any call of it keeps what it holds (P1-R3-6).
|
|
194
|
+
renewLeases(project.db, actor.name);
|
|
195
|
+
}
|
|
196
|
+
// Runs a command seen as `actor`: noted first, so the command finds it, and forgotten again when it
|
|
197
|
+
// was never seen before and the command fails (P2S-R2-3): a failed command is no agent at work, the
|
|
198
|
+
// desk would list it «sin perfil», and whoami would hand its name out.
|
|
199
|
+
function seenWhile(project, input, actor, run) {
|
|
200
|
+
const fresh = actor.kind === 'agent' && !findAgent(project.db, actor.name);
|
|
201
|
+
seen(project, input, actor);
|
|
202
|
+
if (!fresh)
|
|
203
|
+
return run();
|
|
204
|
+
const forget = (error) => {
|
|
205
|
+
forgetAgent(project.db, actor.name);
|
|
206
|
+
throw error;
|
|
207
|
+
};
|
|
208
|
+
try {
|
|
209
|
+
const result = run();
|
|
210
|
+
return (result instanceof Promise ? result.catch(forget) : result);
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
return forget(error);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// Opens the project for a command an agent runs, noting the agent as seen first.
|
|
217
|
+
// An agent's write: refused when the agent is pinned to another project (otea connect).
|
|
218
|
+
function withAgent(input, use) {
|
|
219
|
+
return withProject(input.cwd, (project) => {
|
|
220
|
+
assertPinned(input.pin, project.identity);
|
|
221
|
+
return seenWhile(project, input, input.actor, () => use(project));
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
// Opens the project for a command that only reads: an agent that gave its name is seen; the person
|
|
225
|
+
// reading without one is not.
|
|
226
|
+
function withReader(input, use) {
|
|
227
|
+
return withProject(input.cwd, (project) => seenWhile(project, input, input.reader, () => use(project)));
|
|
228
|
+
}
|
|
229
|
+
async function withReaderWhile(input, use) {
|
|
230
|
+
return withProjectWhile(input.cwd, (project) => seenWhile(project, input, input.reader, () => use(project)));
|
|
231
|
+
}
|
|
232
|
+
async function withAgentWhile(input, use) {
|
|
233
|
+
return withProjectWhile(input.cwd, (project) => {
|
|
234
|
+
assertPinned(input.pin, project.identity);
|
|
235
|
+
return seenWhile(project, input, input.actor, () => use(project));
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
const AGENTS_MD_TEXT = {
|
|
239
|
+
created: (path) => `Added the Otea block to ${path}`,
|
|
240
|
+
added: (path) => `Added the Otea block to ${path}`,
|
|
241
|
+
updated: (path) => `Updated the Otea block in ${path}`,
|
|
242
|
+
unchanged: (path) => `The Otea block in ${path} is up to date`,
|
|
243
|
+
};
|
|
244
|
+
function boardsText(boards) {
|
|
245
|
+
return `Made the boards ${boards.map(({ name }) => name).join(', ')}`;
|
|
246
|
+
}
|
|
247
|
+
// The templates the CLI takes, the same Studio's home offers, as its help lists them.
|
|
248
|
+
const TEMPLATE_KEYS = LISTED_KEYS.join(', ');
|
|
249
|
+
const firstSentence = (text) => text.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? text;
|
|
250
|
+
// Each template key with what it makes, for the help of the commands that take one.
|
|
251
|
+
const TEMPLATE_LIST = (() => {
|
|
252
|
+
const width = Math.max(...LISTED_KEYS.map((key) => key.length)) + 2;
|
|
253
|
+
const lines = LISTED_KEYS.map((key) => {
|
|
254
|
+
const set = TEMPLATE_SETS.find((candidate) => candidate.key === key);
|
|
255
|
+
const template = set ?? TEMPLATES.find((candidate) => candidate.key === key);
|
|
256
|
+
if (!template)
|
|
257
|
+
return ` ${key}`;
|
|
258
|
+
const name = set ? `${template.name.en} (a set): ` : '';
|
|
259
|
+
return ` ${key.padEnd(width)}${name}${firstSentence(template.description.en)}`;
|
|
260
|
+
});
|
|
261
|
+
return ['Templates (--template <key>):', ...lines].join('\n');
|
|
262
|
+
})();
|
|
263
|
+
// What init says to do next: the person opens the desk, in a terminal of their own or the desktop
|
|
264
|
+
// app, which hands them the text for their agent's chat; an agent setting the project up connects
|
|
265
|
+
// itself and never starts the desk, which would close with its session (P4-R3-9).
|
|
266
|
+
export const INIT_NEXT = [
|
|
267
|
+
"Next: run otea serve in a terminal of your own, or open the Otea desktop app: the desk gives you the text to paste into your agent's chat (otea prompt prints it here).",
|
|
268
|
+
'An agent setting itself up runs otea connect --as <name> --model <id> --effort <level>; it never starts the desk for the person (if it must, otea serve --no-open).',
|
|
269
|
+
];
|
|
270
|
+
const init = {
|
|
271
|
+
name: 'init',
|
|
272
|
+
summary: `Create or reuse the project at the repository root: in the Otea home ($OTEA_HOME, default ~/.otea), or with --local in .otea at the root; --join <project> links the repo to a registered project instead (refused when a project in a folder above covers it, unless --here); it makes no board unless --template <key> names one, and only on a project with no boards of its own yet: the boards of that template (${TEMPLATE_KEYS}; a set such as ideas or repos makes all of its boards); you can also pick them later in Studio or with otea board add <name> --template <key>; its boards and its Pedidos board are made in the language you use (the desk's, else this computer's, else English) and keep it; --icon gives the project an icon (without one the UI draws a monogram of its name); --agents-md also adds (or refreshes) a block in AGENTS.md telling agents to run "otea next" and "otea board"`,
|
|
273
|
+
details: TEMPLATE_LIST,
|
|
274
|
+
args: [],
|
|
275
|
+
options: {
|
|
276
|
+
'agents-md': { flag: true },
|
|
277
|
+
here: { flag: true },
|
|
278
|
+
local: { flag: true },
|
|
279
|
+
join: { placeholder: 'project' },
|
|
280
|
+
template: { placeholder: 'key' },
|
|
281
|
+
icon: { placeholder: 'icon' },
|
|
282
|
+
},
|
|
283
|
+
execute: ({ cwd, flag, option }) => {
|
|
284
|
+
const target = option('join');
|
|
285
|
+
const template = option('template');
|
|
286
|
+
const icon = option('icon');
|
|
287
|
+
if (icon !== undefined)
|
|
288
|
+
assertIconName(icon);
|
|
289
|
+
if (target !== undefined && (flag('local') || flag('here') || template !== undefined)) {
|
|
290
|
+
throw new UsageError('--join links to an existing project; it takes no --local, --here or --template');
|
|
291
|
+
}
|
|
292
|
+
const options = {
|
|
293
|
+
here: flag('here'),
|
|
294
|
+
local: flag('local'),
|
|
295
|
+
...(target === undefined ? {} : { join: target }),
|
|
296
|
+
};
|
|
297
|
+
const project = initProject(cwd, options);
|
|
298
|
+
const { root, dataDir: path, storage } = project;
|
|
299
|
+
let made = [];
|
|
300
|
+
let shown;
|
|
301
|
+
let kept = false;
|
|
302
|
+
try {
|
|
303
|
+
shown = icon === undefined ? projectView(project) : setProjectIcon(project, icon);
|
|
304
|
+
// The repos at the project's folders are added now, before any clone of them is linked.
|
|
305
|
+
if (target === undefined) {
|
|
306
|
+
kept = template !== undefined && template !== NO_BOARDS && hasOwnBoards(project);
|
|
307
|
+
made = initBoards(project, template, defaultLang());
|
|
308
|
+
listRepos(project);
|
|
309
|
+
}
|
|
310
|
+
else
|
|
311
|
+
readReposAtFolder(project, root);
|
|
312
|
+
}
|
|
313
|
+
finally {
|
|
314
|
+
project.db.close();
|
|
315
|
+
}
|
|
316
|
+
const data = { root, path, ...shown, storage, boards: made };
|
|
317
|
+
const lines = [
|
|
318
|
+
...(target === undefined
|
|
319
|
+
? []
|
|
320
|
+
: [`Linked ${root} to the project ${shown.name} (${shown.id})`]),
|
|
321
|
+
`Project data in ${path}`,
|
|
322
|
+
...(made.length > 0 ? [boardsText(made)] : []),
|
|
323
|
+
...(kept
|
|
324
|
+
? [
|
|
325
|
+
`The project already has boards; add one with otea board add <name> --template ${template}`,
|
|
326
|
+
]
|
|
327
|
+
: []),
|
|
328
|
+
];
|
|
329
|
+
if (!flag('agents-md'))
|
|
330
|
+
return { data, text: [...lines, ...INIT_NEXT].join('\n') };
|
|
331
|
+
const agentsMd = writeAgentsMd(root);
|
|
332
|
+
const text = [...lines, AGENTS_MD_TEXT[agentsMd.action](agentsMd.path), ...INIT_NEXT];
|
|
333
|
+
return { data: { ...data, agentsMd }, text: text.join('\n') };
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
const projectsList = {
|
|
337
|
+
name: 'projects list',
|
|
338
|
+
summary: 'List the registered projects (common storage) with the folders linked to each',
|
|
339
|
+
args: [],
|
|
340
|
+
options: {},
|
|
341
|
+
execute: () => {
|
|
342
|
+
const projects = withRegistry(process.env, listProjects) ?? [];
|
|
343
|
+
const text = projects
|
|
344
|
+
.map(({ id, name, storage, paths }) => [
|
|
345
|
+
`${id} ${name} ${storage}`,
|
|
346
|
+
...paths.map(({ path, kind, missing }) => ` ${path} ${kind}${missing ? ' (missing)' : ''}`),
|
|
347
|
+
].join('\n'))
|
|
348
|
+
.join('\n');
|
|
349
|
+
return { data: projects, text: text || 'No registered projects' };
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
const projectsCurrent = {
|
|
353
|
+
name: 'projects current',
|
|
354
|
+
summary: 'Show the project this folder resolves to: id, name, storage, folder, data folder and the Otea home whose server serves it',
|
|
355
|
+
args: [],
|
|
356
|
+
options: {},
|
|
357
|
+
execute: ({ cwd }) => {
|
|
358
|
+
const data = withProject(cwd, ({ identity, storage, root, dataDir }) => ({
|
|
359
|
+
...identity,
|
|
360
|
+
storage,
|
|
361
|
+
root,
|
|
362
|
+
dataDir,
|
|
363
|
+
home: oteaHome(),
|
|
364
|
+
}));
|
|
365
|
+
return {
|
|
366
|
+
data,
|
|
367
|
+
text: `${data.id} ${data.name} ${data.storage}\n${data.root}\n${data.dataDir}`,
|
|
368
|
+
};
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
const projectsAdd = {
|
|
372
|
+
name: 'projects add',
|
|
373
|
+
summary: 'Link a folder (another repo, say) to a registered project, so commands run in it use that project',
|
|
374
|
+
args: ['path'],
|
|
375
|
+
options: { to: { required: true, placeholder: 'project' } },
|
|
376
|
+
execute: ({ cwd, required, args: [path = ''] }) => {
|
|
377
|
+
const linked = addPathToProject(resolve(cwd, path), required('to'));
|
|
378
|
+
const repos = withProject(linked.path, (project) => readReposAtFolder(project, linked.path));
|
|
379
|
+
const text = [`Linked ${linked.path} to ${linked.projectId}`, ...reposAddedText(repos)];
|
|
380
|
+
return { data: { ...linked, repos }, text: text.join('\n') };
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
function reposAddedText(repos) {
|
|
384
|
+
if (repos.length === 0)
|
|
385
|
+
return [];
|
|
386
|
+
return [
|
|
387
|
+
`Added the repo${repos.length === 1 ? '' : 's'} ${repos.map(({ name }) => name).join(', ')}`,
|
|
388
|
+
];
|
|
389
|
+
}
|
|
390
|
+
const reposList = {
|
|
391
|
+
name: 'repos list',
|
|
392
|
+
summary: "List the project's repos: the name its items give each one (a repo task's repo field) and what tells it apart wherever it is cloned (its origin URL, or its root commit without one)",
|
|
393
|
+
args: [],
|
|
394
|
+
options: {},
|
|
395
|
+
execute: ({ cwd }) => {
|
|
396
|
+
const repos = withProject(cwd, (project) => listRepos(project));
|
|
397
|
+
const text = repos.map(({ name, identity }) => `${name} ${identity}`).join('\n');
|
|
398
|
+
return { data: repos, text: text || 'No repos' };
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
const reposAdd = {
|
|
402
|
+
name: 'repos add',
|
|
403
|
+
summary: 'Add the repo at a folder (default: here) to the project, under --name or its folder name; a repo already added is renamed by --name. Every clone of it, in any folder, goes by that name in gate checks',
|
|
404
|
+
args: ['path?'],
|
|
405
|
+
options: { name: { placeholder: 'name' } },
|
|
406
|
+
execute: ({ cwd, option, args: [path = '.'] }) => {
|
|
407
|
+
const repo = withProject(cwd, (project) => addRepo(project, resolve(cwd, path), option('name')));
|
|
408
|
+
return { data: repo, text: `${repo.name} ${repo.identity}` };
|
|
409
|
+
},
|
|
410
|
+
};
|
|
411
|
+
const reposRemove = {
|
|
412
|
+
name: 'repos remove',
|
|
413
|
+
summary: 'Remove a repo from the project by name; its items keep their values, and gate checks refuse in it until it is added again',
|
|
414
|
+
args: ['name'],
|
|
415
|
+
options: {},
|
|
416
|
+
execute: ({ cwd, args: [name = ''] }) => {
|
|
417
|
+
const repo = withProject(cwd, (project) => removeRepo(project, name));
|
|
418
|
+
return { data: repo, text: `Removed ${repo.name}` };
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
function inRegistry(use) {
|
|
422
|
+
const result = withRegistry(process.env, use);
|
|
423
|
+
if (result === undefined)
|
|
424
|
+
throw new OteaError('not_found', 'No project is registered yet');
|
|
425
|
+
return result;
|
|
426
|
+
}
|
|
427
|
+
const projectsRelink = {
|
|
428
|
+
name: 'projects relink',
|
|
429
|
+
summary: 'Point a linked folder at where its repo moved; refused unless the new folder has the same remote URL or root commit (--force links it anyway)',
|
|
430
|
+
args: ['old', 'new'],
|
|
431
|
+
options: { force: { flag: true } },
|
|
432
|
+
execute: ({ cwd, flag, warn, args: [from = '', to = ''] }) => {
|
|
433
|
+
const relinked = inRegistry((registry) => relinkProjectPath(registry, resolve(cwd, from), resolve(cwd, to), flag('force')));
|
|
434
|
+
if (relinked.match === 'unknown') {
|
|
435
|
+
warn(`Could not check that ${relinked.link.path} is the same repo (no remote URL or commit)`);
|
|
436
|
+
}
|
|
437
|
+
const text = `Relinked ${relinked.from} to ${relinked.link.path} (${relinked.link.projectId})`;
|
|
438
|
+
return { data: relinked, text };
|
|
439
|
+
},
|
|
440
|
+
};
|
|
441
|
+
const projectsForget = {
|
|
442
|
+
name: 'projects forget',
|
|
443
|
+
summary: 'Unlink a folder from its project; the project and its items stay, and with no folder left nothing resolves to it',
|
|
444
|
+
args: ['path'],
|
|
445
|
+
options: {},
|
|
446
|
+
execute: ({ cwd, args: [path = ''] }) => {
|
|
447
|
+
const forgotten = inRegistry((registry) => forgetProjectPath(registry, resolve(cwd, path)));
|
|
448
|
+
const { link, remaining } = forgotten;
|
|
449
|
+
const left = remaining === 0
|
|
450
|
+
? `${link.projectId} has no linked folder left; its data stays, link one with otea projects add`
|
|
451
|
+
: `${link.projectId} keeps ${remaining} linked folder${remaining === 1 ? '' : 's'}`;
|
|
452
|
+
return { data: forgotten, text: `Forgot ${link.path}\n${left}` };
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
function processAlive(pid) {
|
|
456
|
+
try {
|
|
457
|
+
process.kill(pid, 0);
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
catch (error) {
|
|
461
|
+
return error.code === 'EPERM';
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
function migrationText(report) {
|
|
465
|
+
const { status, id, root, to, from, backup, tables, files, undo } = report;
|
|
466
|
+
if (status === 'already')
|
|
467
|
+
return `${id} is already in common storage at ${to}; nothing to do`;
|
|
468
|
+
const rows = Object.entries(tables)
|
|
469
|
+
.map(([table, { rows }]) => `${table} ${rows}`)
|
|
470
|
+
.join(', ');
|
|
471
|
+
const lines = status === 'migrated'
|
|
472
|
+
? [
|
|
473
|
+
`Copied and verified the database into ${to} (${rows})`,
|
|
474
|
+
`Copied ${files} evidence and preset file${files === 1 ? '' : 's'}`,
|
|
475
|
+
`Registered ${id} and linked ${root}`,
|
|
476
|
+
]
|
|
477
|
+
: [`${id} was already copied to ${to} and registered`];
|
|
478
|
+
return [
|
|
479
|
+
...lines,
|
|
480
|
+
`Moved ${from} to ${backup} (a backup: Otea never deletes it)`,
|
|
481
|
+
'To undo:',
|
|
482
|
+
...undo.map((step) => ` ${step}`),
|
|
483
|
+
].join('\n');
|
|
484
|
+
}
|
|
485
|
+
const migrateCommand = {
|
|
486
|
+
name: 'migrate',
|
|
487
|
+
summary: 'Move the local project (.otea/) into common storage in the Otea home, verified, keeping the old folder as a backup; refused while otea serve runs on this computer',
|
|
488
|
+
args: [],
|
|
489
|
+
options: { to: { required: true, choices: ['common'] } },
|
|
490
|
+
execute: ({ cwd, required }) => {
|
|
491
|
+
required('to');
|
|
492
|
+
withProject(cwd, () => undefined);
|
|
493
|
+
const server = readServeFile(oteaHome());
|
|
494
|
+
if (server && processAlive(server.pid)) {
|
|
495
|
+
throw new OteaError('in_use', `otea serve (pid ${server.pid}, port ${server.port}) holds the project's database; stop it first`);
|
|
496
|
+
}
|
|
497
|
+
const report = migrateToCommon(cwd);
|
|
498
|
+
return { data: report, text: migrationText(report) };
|
|
499
|
+
},
|
|
500
|
+
};
|
|
501
|
+
// How what Otea writes (hooks, the MCP server connect prints) runs this Otea again: Node on
|
|
502
|
+
// main.ts in a checkout, main.js in the published package; the desktop app on its own
|
|
503
|
+
// Electron. connect prefers the otea command on $PATH.
|
|
504
|
+
const OTEA = oteaLauncher(fileURLToPath(new URL(`./main${extname(import.meta.url)}`, import.meta.url)), {
|
|
505
|
+
execPath: process.execPath,
|
|
506
|
+
electron: process.versions.electron,
|
|
507
|
+
});
|
|
508
|
+
// The MCP server as an agent adds it to its own harness's config: every harness keeps that config
|
|
509
|
+
// its own way, so Otea gives one instruction and writes none of them.
|
|
510
|
+
function mcpInstructionText(entry) {
|
|
511
|
+
const env = Object.entries(entry.env ?? {}).map(([name, value]) => `${name}=${value}`);
|
|
512
|
+
const json = JSON.stringify({ [MCP_SERVER]: entry });
|
|
513
|
+
return [
|
|
514
|
+
"To use Otea's MCP tools, add this MCP server to your harness's MCP config yourself, for this project only: in the project's own config file or your harness's project scope. Never edit your user or global config: the server is pinned to this project. It is a local stdio server; Otea writes no harness config:",
|
|
515
|
+
indent(columns([
|
|
516
|
+
['name', MCP_SERVER],
|
|
517
|
+
['command', entry.command],
|
|
518
|
+
['args', entry.args.map((arg) => (/\s/.test(arg) ? `"${arg}"` : arg)).join(' ')],
|
|
519
|
+
...(env.length > 0 ? [['env', env.join(' ')]] : []),
|
|
520
|
+
])),
|
|
521
|
+
`As JSON: ${json}`,
|
|
522
|
+
"That JSON is one shape; every harness has its own, and may skip a server in another shape without a word: translate it to your harness's schema, or add the server with your harness's own mcp add command, at project scope. The usual project files, as examples: Claude Code: .mcp.json (under mcpServers); OpenCode: opencode.json (under mcp, with command as one array of the command and its args, and env as environment).",
|
|
523
|
+
"It names no agent: each session names itself (--as; MCP tools: as). If your harness already has a server named otea that runs anything else (an older Otea, or mcp --as <name>), replace it for this project with this one. If your harness must restart or reload to load the server, ask the person for it now, before you go on, and to reopen this same conversation with your harness's resume option, if it has one, so you keep what was said; Otea keeps every item and board draft either way. Approve it if your harness asks, then call any Otea tool. Until then, and whenever MCP is off, the otea command does the same.",
|
|
524
|
+
'Run otea connect --check now (with --as <name>), and again after that call: only it tells whether the server loaded, and the desk warns until it does.',
|
|
525
|
+
];
|
|
526
|
+
}
|
|
527
|
+
// What an agent's harness must let it run for Otea's flow, said the same for every harness: Otea
|
|
528
|
+
// writes no harness config, and the docs give an example per harness.
|
|
529
|
+
const HARNESS_PERMISSIONS = "Have your harness allow, for this project: otea (its commands and its MCP tools), git push to the items' branches (Otea's pre-push hook still checks each push) and git worktree add. Otea writes no harness config: docs/working-with-agents.md, «What your harness must allow», has examples.";
|
|
530
|
+
// What otea connect --check says: whether the agent named (or any agent) was heard through Otea's
|
|
531
|
+
// MCP server in this project.
|
|
532
|
+
function mcpCheck(project, agent, now = systemClock) {
|
|
533
|
+
const agents = listAgents(project.db, now);
|
|
534
|
+
const heard = agents
|
|
535
|
+
.filter(({ name, mcpAt }) => mcpAt !== null && (agent === undefined || name === agent))
|
|
536
|
+
.sort((a, b) => Date.parse(b.mcpAt ?? '') - Date.parse(a.mcpAt ?? ''));
|
|
537
|
+
// The harnesses that loaded the server: the agent's own (as its client or its profile names
|
|
538
|
+
// it), or any without --as.
|
|
539
|
+
const mine = agents.find(({ name }) => name === agent);
|
|
540
|
+
const named = [mine?.harness, mine?.profile?.harness].filter((each) => Boolean(each) && each?.toLowerCase() !== 'cli');
|
|
541
|
+
const loads = selectMcpLoads(project.db).filter(({ harness }) => agent === undefined || named.some((each) => harnessKey(each) === harness));
|
|
542
|
+
const data = {
|
|
543
|
+
connected: heard.length > 0 || loads.length > 0,
|
|
544
|
+
agents: heard.map(({ name, harness, mcpAt }) => ({ name, harness, mcpAt })),
|
|
545
|
+
loaded: loads.map(({ name, at }) => ({ harness: name, at })),
|
|
546
|
+
};
|
|
547
|
+
if (heard.length > 0) {
|
|
548
|
+
const lines = heard.map(({ name, harness, mcpAt }) => `MCP works: ${name} was heard through Otea's MCP server ${timeText(mcpAt ?? '')}${harness ? ` (${harness})` : ''}`);
|
|
549
|
+
return { data, text: lines.join('\n') };
|
|
550
|
+
}
|
|
551
|
+
// Loaded, and no tool called through it yet: the agent may keep to the otea command, which does
|
|
552
|
+
// the same (P4-R2-10).
|
|
553
|
+
if (loads.length > 0) {
|
|
554
|
+
const lines = loads.map(({ name, at }) => `MCP works: ${name} loaded Otea's MCP server ${timeText(at)}; no agent has called its tools yet. The otea command does the same, so the agent may use either.`);
|
|
555
|
+
return { data, text: lines.join('\n') };
|
|
556
|
+
}
|
|
557
|
+
const who = agent ? `${agent} has not reached` : 'No agent has reached';
|
|
558
|
+
return {
|
|
559
|
+
data,
|
|
560
|
+
text: `${who} Otea through its MCP server in this project yet. If you added the server, restart or reload the session and approve it when your harness asks (declining turns it off for the project), then call any Otea tool, such as next. If Otea tools answer you but this still says so, your harness runs another otea server (an older one, or one started with --as): replace it for this project with the one otea connect prints. Meanwhile the otea command works the same.`,
|
|
561
|
+
failure: 'not_connected',
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
const connect = {
|
|
565
|
+
name: 'connect',
|
|
566
|
+
summary: "Connect agents to Otea, the same for every harness: add (or refresh) Otea's block in AGENTS.md and print the MCP server an agent adds to its own harness's config (otea mcp --project <id>: Otea writes no harness config). --as with --model and --effort also declares the profile that agent runs as, and notes it asked for MCP, so the desk warns while its harness never loads the server. --check says whether the agent (--as) or any agent was heard through the MCP server",
|
|
567
|
+
args: [],
|
|
568
|
+
// --as is a global option; it is named here so the usage line shows it.
|
|
569
|
+
options: {
|
|
570
|
+
as: { placeholder: 'name' },
|
|
571
|
+
model: { placeholder: 'id' },
|
|
572
|
+
effort: { placeholder: 'level' },
|
|
573
|
+
harness: { placeholder: 'name' },
|
|
574
|
+
check: { flag: true },
|
|
575
|
+
},
|
|
576
|
+
execute: async (input) => {
|
|
577
|
+
const { cwd, option, flag } = input;
|
|
578
|
+
const name = input.agent;
|
|
579
|
+
if (name !== undefined)
|
|
580
|
+
assertAgentName(name);
|
|
581
|
+
if (flag('check')) {
|
|
582
|
+
const checked = withProject(cwd, (project) => mcpCheck(project, name));
|
|
583
|
+
const outdated = outdatedGitHookLine(cwd);
|
|
584
|
+
if (outdated === undefined)
|
|
585
|
+
return checked;
|
|
586
|
+
return {
|
|
587
|
+
...checked,
|
|
588
|
+
data: { ...checked.data, outdatedGitHook: outdated },
|
|
589
|
+
text: `${checked.text}\n${outdated}`,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
const model = option('model');
|
|
593
|
+
const effort = option('effort');
|
|
594
|
+
const { root, id } = withProject(cwd, (project) => {
|
|
595
|
+
if (name !== undefined) {
|
|
596
|
+
if (model !== undefined && effort !== undefined) {
|
|
597
|
+
presetProfile(project.db, {
|
|
598
|
+
agent: name,
|
|
599
|
+
model,
|
|
600
|
+
effort,
|
|
601
|
+
given: option('harness'),
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
else if (!findProfile(project.db, name)) {
|
|
605
|
+
throw new UsageError(`Give the profile ${name} runs as: --model <id> --effort <level>, exactly as its harness names them (such as claude-opus-5-5 and high)`);
|
|
606
|
+
}
|
|
607
|
+
markMcpAsked(project.db, name, systemClock());
|
|
608
|
+
}
|
|
609
|
+
return { root: project.root, id: project.identity.id };
|
|
610
|
+
});
|
|
611
|
+
// AGENTS.md goes in the checkout the agent works in: a linked worktree's own, so its agents
|
|
612
|
+
// read it there.
|
|
613
|
+
const here = checkoutRoot(cwd) ?? root;
|
|
614
|
+
const agentsMd = writeAgentsMd(here);
|
|
615
|
+
const entry = mcpEntry(withHome(input.oteaOnPath?.() ?? OTEA, input.home), id);
|
|
616
|
+
const mcp = { name: MCP_SERVER, ...entry };
|
|
617
|
+
const old = oldMcpEntry(here);
|
|
618
|
+
const text = [
|
|
619
|
+
`${AGENTS_MD_TEXT[agentsMd.action](agentsMd.path)}: every agent that reads AGENTS.md finds Otea there (if your harness doesn't read AGENTS.md, import it from the file it reads)`,
|
|
620
|
+
// A harness's permission mode blocked git push and git worktree add mid-flow (p6).
|
|
621
|
+
HARNESS_PERMISSIONS,
|
|
622
|
+
...mcpInstructionText(entry),
|
|
623
|
+
...(old
|
|
624
|
+
? [
|
|
625
|
+
`${old} still has the otea entry an older otea connect wrote, which gives every session there one agent name: remove that entry and add the server as above.`,
|
|
626
|
+
]
|
|
627
|
+
: []),
|
|
628
|
+
];
|
|
629
|
+
return {
|
|
630
|
+
data: { agentsMd, mcp, ...(name === undefined ? {} : { agent: name }) },
|
|
631
|
+
text: text.join('\n'),
|
|
632
|
+
};
|
|
633
|
+
},
|
|
634
|
+
};
|
|
635
|
+
// `default` is no icon name, so it can stand for going back to the preset's icon.
|
|
636
|
+
const DEFAULT_ICON = 'default';
|
|
637
|
+
const collectionIconCommand = {
|
|
638
|
+
name: 'collection icon',
|
|
639
|
+
summary: `Give a collection its own icon, or "${DEFAULT_ICON}" to go back to the icon it came with`,
|
|
640
|
+
args: ['name', 'icon'],
|
|
641
|
+
options: {},
|
|
642
|
+
execute: ({ cwd, args: [name = '', icon = ''] }) => {
|
|
643
|
+
const collection = withProject(cwd, (project) => {
|
|
644
|
+
const changed = setCollectionIcon(project, name, icon === DEFAULT_ICON ? null : icon);
|
|
645
|
+
return { ...changed, icon: collectionIcon(project, changed) };
|
|
646
|
+
});
|
|
647
|
+
const own = icon === DEFAULT_ICON ? ` (its preset's)` : '';
|
|
648
|
+
return {
|
|
649
|
+
data: collection,
|
|
650
|
+
text: `Collection "${collection.name}" shows icon ${collection.icon ?? 'none'}${own}`,
|
|
651
|
+
};
|
|
652
|
+
},
|
|
653
|
+
};
|
|
654
|
+
// A value from a file (--field-file key=path, or key=- for stdin), as an editor or a shell leaves
|
|
655
|
+
// it: without a BOM (PowerShell 5's utf8) and without the line break that ends the file.
|
|
656
|
+
async function fieldFileValue(input, path) {
|
|
657
|
+
let text;
|
|
658
|
+
if (path === '-') {
|
|
659
|
+
text = await input.stdin();
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
const file = resolve(input.cwd, path);
|
|
663
|
+
try {
|
|
664
|
+
text = readFileSync(file, 'utf8');
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
throw new OteaError('file_not_found', `No file at ${file}`);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return text.replace(/^\uFEFF/, '').replace(/\r?\n$/, '');
|
|
671
|
+
}
|
|
672
|
+
async function fieldsFrom(input) {
|
|
673
|
+
const { option, options } = input;
|
|
674
|
+
const fields = {};
|
|
675
|
+
const set = (key, value) => {
|
|
676
|
+
if (key === 'title')
|
|
677
|
+
throw new UsageError('Use --title for the title');
|
|
678
|
+
if (key in fields)
|
|
679
|
+
throw new UsageError(`Field "${key}" given twice`);
|
|
680
|
+
fields[key] = value;
|
|
681
|
+
};
|
|
682
|
+
const description = option('description');
|
|
683
|
+
if (description !== undefined)
|
|
684
|
+
set('description', description);
|
|
685
|
+
for (const pair of options('field'))
|
|
686
|
+
set(...fieldPair(pair, FILE_HINT));
|
|
687
|
+
for (const pair of options('field-file')) {
|
|
688
|
+
const [key, path] = fieldPair(pair, '', 'field-file', '<file>');
|
|
689
|
+
set(key, await fieldFileValue(input, path));
|
|
690
|
+
}
|
|
691
|
+
return fields;
|
|
692
|
+
}
|
|
693
|
+
// What a field's usage error adds where --field-file is taken.
|
|
694
|
+
const FILE_HINT = '; a long or multi-line value from a file: --field-file "<key>=<file>" (or <key>=- to read stdin)';
|
|
695
|
+
// key=value, or a usage error with an example, then `hint` (<key> in it named as the field given).
|
|
696
|
+
function fieldPair(pair, hint = '', option = 'field', value = '<value>') {
|
|
697
|
+
const separator = pair.indexOf('=');
|
|
698
|
+
if (separator < 1) {
|
|
699
|
+
const key = pair || '<name>';
|
|
700
|
+
const more = hint.replaceAll('<key>', key);
|
|
701
|
+
throw new UsageError(`--${option} expects key=value, got "${pair}": such as --${option} "${key}=${value}"${more}`);
|
|
702
|
+
}
|
|
703
|
+
return [pair.slice(0, separator), pair.slice(separator + 1)];
|
|
704
|
+
}
|
|
705
|
+
// Long values over the CLI: the MCP tools take them as they are, so they have no --field-file.
|
|
706
|
+
const FIELD_FILE = { multiple: true, placeholder: 'key=file' };
|
|
707
|
+
// What create and update --help add on the fields they take.
|
|
708
|
+
const FIELD_DETAILS = [
|
|
709
|
+
`--description fills the board's description field, where it has one (Descripción on Errores); a board without one refuses it: give its fields by name with --field "<name>=<value>" (otea board <name> says what each takes).`,
|
|
710
|
+
'--field-file "<name>=<file>" takes a long or multi-line value from a file, or from stdin with <name>=-.',
|
|
711
|
+
].join('\n');
|
|
712
|
+
const create = {
|
|
713
|
+
name: 'create',
|
|
714
|
+
summary: 'Create an item and say where it starts: on a board whose first step is skipped for an item that has everything it asks, at the next step; an item of a board that is always part of another needs --parent',
|
|
715
|
+
details: FIELD_DETAILS,
|
|
716
|
+
args: [],
|
|
717
|
+
options: {
|
|
718
|
+
collection: { required: true },
|
|
719
|
+
type: { placeholder: 'type' },
|
|
720
|
+
title: { required: true },
|
|
721
|
+
description: {},
|
|
722
|
+
field: { multiple: true, placeholder: 'key=value' },
|
|
723
|
+
'field-file': FIELD_FILE,
|
|
724
|
+
parent: { placeholder: 'id' },
|
|
725
|
+
from: { placeholder: 'topic' },
|
|
726
|
+
},
|
|
727
|
+
execute: async (input) => {
|
|
728
|
+
const collection = input.required('collection');
|
|
729
|
+
const type = input.option('type');
|
|
730
|
+
const title = input.required('title');
|
|
731
|
+
const parent = input.option('parent');
|
|
732
|
+
const from = input.option('from');
|
|
733
|
+
const fields = await fieldsFrom(input);
|
|
734
|
+
const { actor, channel } = input;
|
|
735
|
+
return withAgent(input, (project) => {
|
|
736
|
+
// The topic the item comes from, checked before anything is made.
|
|
737
|
+
const topic = from === undefined ? undefined : requireTopic(project, from);
|
|
738
|
+
const item = createItem(project, {
|
|
739
|
+
collection,
|
|
740
|
+
...(type === undefined ? {} : { type }),
|
|
741
|
+
title,
|
|
742
|
+
fields,
|
|
743
|
+
...(parent === undefined ? {} : { parent }),
|
|
744
|
+
actor,
|
|
745
|
+
channel,
|
|
746
|
+
});
|
|
747
|
+
if (topic)
|
|
748
|
+
linkTopic(project, { id: topic.id, item: item.id, via: 'from' });
|
|
749
|
+
// On a board: where it starts, and why when its first step was skipped or lacks something.
|
|
750
|
+
return { data: itemData(project, item), text: createdTextOf(project, item) ?? item.id };
|
|
751
|
+
});
|
|
752
|
+
},
|
|
753
|
+
};
|
|
754
|
+
function listFilter({ option, options, flag, reader }) {
|
|
755
|
+
const filter = {};
|
|
756
|
+
const collection = option('collection');
|
|
757
|
+
const state = option('state');
|
|
758
|
+
const type = option('type');
|
|
759
|
+
const turn = option('turn');
|
|
760
|
+
const parent = option('parent');
|
|
761
|
+
if (collection !== undefined)
|
|
762
|
+
filter.collection = collection;
|
|
763
|
+
if (parent !== undefined)
|
|
764
|
+
filter.parent = parent;
|
|
765
|
+
if (state !== undefined)
|
|
766
|
+
filter.state = state;
|
|
767
|
+
if (type !== undefined)
|
|
768
|
+
filter.type = type;
|
|
769
|
+
if (turn !== undefined)
|
|
770
|
+
filter.turn = turn;
|
|
771
|
+
if (flag('unclaimed'))
|
|
772
|
+
filter.availableTo = reader.name;
|
|
773
|
+
for (const [key, value] of options('field').map((pair) => fieldPair(pair))) {
|
|
774
|
+
filter.fields ??= {};
|
|
775
|
+
if (key in filter.fields)
|
|
776
|
+
throw new UsageError(`Field "${key}" given twice`);
|
|
777
|
+
filter.fields[key] = value;
|
|
778
|
+
}
|
|
779
|
+
return filter;
|
|
780
|
+
}
|
|
781
|
+
// What the person put on top first, then the order they fixed on the Matrix, as otea next takes
|
|
782
|
+
// them; then the other open items, and the closed ones last (P1-R3-11), each in creation order
|
|
783
|
+
// (the sort is stable).
|
|
784
|
+
function byPersonOrder(items, order) {
|
|
785
|
+
const key = (item) => {
|
|
786
|
+
const placed = order.get(item.id);
|
|
787
|
+
return [
|
|
788
|
+
Number(item.turn === 'none'),
|
|
789
|
+
placed?.pin ?? Number.POSITIVE_INFINITY,
|
|
790
|
+
placed?.rank ?? Number.POSITIVE_INFINITY,
|
|
791
|
+
];
|
|
792
|
+
};
|
|
793
|
+
return [...items].sort((a, b) => {
|
|
794
|
+
const [ka, kb] = [key(a), key(b)];
|
|
795
|
+
const at = ka.findIndex((value, index) => value !== kb[index]);
|
|
796
|
+
return at < 0 ? 0 : (ka[at] ?? 0) < (kb[at] ?? 0) ? -1 : 1;
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
const list = {
|
|
800
|
+
name: 'list',
|
|
801
|
+
summary: 'List items in creation order, with the order the person set beside those it places (on top 1, order 2: what they put on top and fixed on the Matrix, as otea next takes them), optionally filtered; --unclaimed hides items others hold, --parent keeps the children of an item, --field key=value (repeatable) keeps items whose field holds exactly that value; --state and --field take the board names (any case) or ids; --sort order puts what the person ordered first',
|
|
802
|
+
args: [],
|
|
803
|
+
options: {
|
|
804
|
+
collection: {},
|
|
805
|
+
type: {},
|
|
806
|
+
state: {},
|
|
807
|
+
turn: { choices: TURNS },
|
|
808
|
+
parent: { placeholder: 'id' },
|
|
809
|
+
field: { multiple: true, placeholder: 'key=value' },
|
|
810
|
+
unclaimed: { flag: true },
|
|
811
|
+
sort: { choices: ['created', 'order'] },
|
|
812
|
+
},
|
|
813
|
+
execute: (input) => {
|
|
814
|
+
return withReader(input, (project) => {
|
|
815
|
+
// A step and fields named as the board names them, or by id: each item on its own board.
|
|
816
|
+
const filter = listFilter(input);
|
|
817
|
+
const { state: _state, fields: _fields, ...stored } = filter;
|
|
818
|
+
// The person's order beside each item it places, as otea next takes them.
|
|
819
|
+
const order = priorityOf(project.db);
|
|
820
|
+
const listed = listItems(project, stored).filter(readerFilter(project, filter));
|
|
821
|
+
const items = input.option('sort') === 'order' ? byPersonOrder(listed, order) : listed;
|
|
822
|
+
// Done with its branch not merged yet reads as the desk says it, never as merged (P6-R2-11).
|
|
823
|
+
const boards = liveBoards(project);
|
|
824
|
+
const shown = items.map((item) => {
|
|
825
|
+
const named = readable(project, item);
|
|
826
|
+
return rowFactsOf(project, item, boards).merge === 'waiting'
|
|
827
|
+
? { ...named, state: `${named.state}, not merged` }
|
|
828
|
+
: named;
|
|
829
|
+
});
|
|
830
|
+
const boardOf = boardsOf(project);
|
|
831
|
+
return {
|
|
832
|
+
data: items.map((item) => {
|
|
833
|
+
const placed = order.get(item.id);
|
|
834
|
+
const data = itemData(project, item, boardOf);
|
|
835
|
+
return placed && Object.keys(placed).length > 0 ? { ...data, priority: placed } : data;
|
|
836
|
+
}),
|
|
837
|
+
text: formatItems(shown, typesShown(project), order),
|
|
838
|
+
};
|
|
839
|
+
});
|
|
840
|
+
},
|
|
841
|
+
};
|
|
842
|
+
const show = {
|
|
843
|
+
name: 'show',
|
|
844
|
+
summary: 'Show an item, what to do with it now, its fields, the moves available to the agent and its events timeline',
|
|
845
|
+
args: ['id'],
|
|
846
|
+
options: {},
|
|
847
|
+
execute: (input) => {
|
|
848
|
+
const [id = ''] = input.args;
|
|
849
|
+
const { reader: actor, channel } = input;
|
|
850
|
+
const performer = { actor, channel };
|
|
851
|
+
return withReader(input, (project) => {
|
|
852
|
+
const shown = showItem(project, id, performer);
|
|
853
|
+
const gitHook = gitHookOf(project, shown);
|
|
854
|
+
// Each event's profile is left to otea events: show stays within its token budget.
|
|
855
|
+
const item = {
|
|
856
|
+
...shown,
|
|
857
|
+
// Each file with a path an agent can open, under its own name (P5-R2-4).
|
|
858
|
+
evidence: shown.evidence.map((entry) => {
|
|
859
|
+
const path = evidenceReadPath(project.dataDir, entry);
|
|
860
|
+
return path === undefined ? entry : { ...entry, path };
|
|
861
|
+
}),
|
|
862
|
+
events: shown.events.map(({ profile: _profile, ...event }) => event),
|
|
863
|
+
hint: hintFor(project, shown, actor.name),
|
|
864
|
+
...(gitHook === undefined ? {} : { gitHook }),
|
|
865
|
+
};
|
|
866
|
+
const { layout } = typeOfItem(project, shown);
|
|
867
|
+
const named = liveBoardOf(project, item.collection) !== undefined;
|
|
868
|
+
// Evidence is grouped by the module id it went to: its part name would match no module.
|
|
869
|
+
const text = formatItemWithEvents({ ...readable(project, item), evidence: item.evidence }, layout, typesShown(project), named);
|
|
870
|
+
// The person's notes of this round, as data too: the text has them in its Next: block.
|
|
871
|
+
const notes = roundNotesOf(project, item.id);
|
|
872
|
+
const data = itemData(project, item);
|
|
873
|
+
const outside = mergedOutsideLine(project, input.cwd, shown);
|
|
874
|
+
const said = outside === undefined
|
|
875
|
+
? text
|
|
876
|
+
: `${outside}
|
|
877
|
+
|
|
878
|
+
${text}`;
|
|
879
|
+
return { data: notes.length === 0 ? data : { ...data, notes }, text: said };
|
|
880
|
+
});
|
|
881
|
+
},
|
|
882
|
+
};
|
|
883
|
+
// otea board's index opens with Otea's agent guide, where AGENTS.md sends a CLI agent (and an MCP
|
|
884
|
+
// one whose client shows no instructions) to read it once; one board gives it no second time.
|
|
885
|
+
// --json keeps the data alone.
|
|
886
|
+
const withAgentGuide = (project, text) => `${agentGuideFor(topicsOn(project))}\n\n${text}`;
|
|
887
|
+
const boardName = (record) => (record.live ?? record.draft)?.definition.name ?? '';
|
|
888
|
+
const boardAdd = {
|
|
889
|
+
name: 'board add',
|
|
890
|
+
summary: `For the person, with no agent name: make a board and publish it, from a template (${TEMPLATE_KEYS}) or blank, in the language you use (the desk's, else this computer's, else English) or the one --lang gives, once; --item names what each item is; a set such as ideas or repos makes all of its boards, the name and --item naming the first; --prefix chooses how its item ids start (2 to 6 letters or digits; one board only)`,
|
|
891
|
+
details: TEMPLATE_LIST,
|
|
892
|
+
args: ['name'],
|
|
893
|
+
options: {
|
|
894
|
+
template: { placeholder: 'key' },
|
|
895
|
+
item: {},
|
|
896
|
+
lang: { choices: LANGS },
|
|
897
|
+
prefix: { placeholder: 'letters' },
|
|
898
|
+
},
|
|
899
|
+
execute: ({ cwd, args: [name = ''], option, agent }) => {
|
|
900
|
+
// --lang (checked against LANGS as the option's choices); the language the person uses without it.
|
|
901
|
+
const lang = option('lang') ?? defaultLang();
|
|
902
|
+
// Publishing is the person's: an agent that names itself proposes the board instead.
|
|
903
|
+
if (agent !== undefined) {
|
|
904
|
+
throw new OteaError('forbidden', `otea board add publishes a board as the person. An agent proposes one for the person to publish in Studio: otea board draft --new "${name.trim()}" --why "<what it is for>" --as ${agent}`);
|
|
905
|
+
}
|
|
906
|
+
const template = option('template');
|
|
907
|
+
const item = option('item');
|
|
908
|
+
const prefix = option('prefix');
|
|
909
|
+
if (template !== undefined && isSetKey(template)) {
|
|
910
|
+
if (prefix !== undefined)
|
|
911
|
+
throw new UsageError(`--prefix names the ids of one board, and ${template} makes several: add it without --prefix`);
|
|
912
|
+
const boards = withProject(cwd, (project) => addBoardSet(project, {
|
|
913
|
+
set: template,
|
|
914
|
+
lang,
|
|
915
|
+
by: { kind: 'human', name: 'human' },
|
|
916
|
+
boards: [{ name, ...(item === undefined ? {} : { item }) }],
|
|
917
|
+
}));
|
|
918
|
+
const names = boards.map(({ record }) => `"${boardName(record)}"`).join(', ');
|
|
919
|
+
return { data: boards, text: `Published boards ${names} from template ${template}` };
|
|
920
|
+
}
|
|
921
|
+
const added = withProject(cwd, (project) => addBoard(project, {
|
|
922
|
+
name,
|
|
923
|
+
lang,
|
|
924
|
+
by: { kind: 'human', name: 'human' },
|
|
925
|
+
...(template === undefined ? {} : { template }),
|
|
926
|
+
...(item === undefined ? {} : { item }),
|
|
927
|
+
...(prefix === undefined ? {} : { prefix }),
|
|
928
|
+
}));
|
|
929
|
+
const ids = added.record.collection
|
|
930
|
+
? withProject(cwd, (project) => getCollection(project.db, added.record.collection ?? '').prefix)
|
|
931
|
+
: '';
|
|
932
|
+
const from = template === undefined ? 'blank' : `from template ${template}`;
|
|
933
|
+
return {
|
|
934
|
+
data: added,
|
|
935
|
+
text: `Published board "${name.trim()}" v${added.version} ${from} (ids ${ids}-<n>)`,
|
|
936
|
+
};
|
|
937
|
+
},
|
|
938
|
+
};
|
|
939
|
+
// The board.json an agent hands in: the file it names, or, with --file -, what it pipes in, so it
|
|
940
|
+
// needs no file outside the project (P1-R3-10). `piped`: stdin, read before the command opens the
|
|
941
|
+
// project.
|
|
942
|
+
function draftFile(cwd, file, piped) {
|
|
943
|
+
if (file === '-') {
|
|
944
|
+
if (piped?.trim())
|
|
945
|
+
return piped;
|
|
946
|
+
throw new OteaError('missing_fields', 'Nothing came on stdin: pipe the board JSON into otea board draft --file - (a here-document of your shell), or give --file a path');
|
|
947
|
+
}
|
|
948
|
+
const path = resolve(cwd, file);
|
|
949
|
+
try {
|
|
950
|
+
return readFileSync(path, 'utf8');
|
|
951
|
+
}
|
|
952
|
+
catch {
|
|
953
|
+
throw new OteaError('file_not_found', `No file at ${path}`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function handedInLines(id, submitted) {
|
|
957
|
+
return [
|
|
958
|
+
`Handed in the board draft on ${id} (evidence ${submitted.evidence.id}); it is in Studio now, for the person to try and publish.`,
|
|
959
|
+
...(submitted.notes.length === 0
|
|
960
|
+
? []
|
|
961
|
+
: ["Read as today's board:", ...submitted.notes.map((n) => ` ${n}`)]),
|
|
962
|
+
...(submitted.problems.length === 0
|
|
963
|
+
? []
|
|
964
|
+
: ['Still to fix, for it to be published:', ...submitted.problems.map((p) => ` ${p}`)]),
|
|
965
|
+
];
|
|
966
|
+
}
|
|
967
|
+
// The board's page in Studio, on the port otea serve runs on (or would).
|
|
968
|
+
function studioLink(project, board) {
|
|
969
|
+
const page = projectPage(portToOpen(undefined), project.identity.id);
|
|
970
|
+
return `${page}#/studio/board/${encodeURIComponent(board)}`;
|
|
971
|
+
}
|
|
972
|
+
// otea board draft --new: the agent the person asked for a board starts it; the person publishes.
|
|
973
|
+
function proposeBoard(input, name, piped) {
|
|
974
|
+
const why = input.option('why')?.trim() ?? '';
|
|
975
|
+
const file = input.option('file');
|
|
976
|
+
const template = input.option('template');
|
|
977
|
+
return withAgent(input, (project) => {
|
|
978
|
+
if (why === '')
|
|
979
|
+
throw new OteaError('missing_fields', 'Say what the board is for: --why "<what it is for>"');
|
|
980
|
+
const text = file === undefined ? undefined : draftFile(input.cwd, file, piped);
|
|
981
|
+
const { actor, channel } = input;
|
|
982
|
+
const made = proposeAgentDraft(project, {
|
|
983
|
+
name,
|
|
984
|
+
need: why,
|
|
985
|
+
lang: defaultLang(),
|
|
986
|
+
actor,
|
|
987
|
+
channel,
|
|
988
|
+
...(text === undefined ? {} : { text }),
|
|
989
|
+
...(template === undefined ? {} : { template }),
|
|
990
|
+
});
|
|
991
|
+
const studio = studioLink(project, made.board.id);
|
|
992
|
+
const lines = [
|
|
993
|
+
...(made.submitted ? handedInLines(made.item, made.submitted) : []),
|
|
994
|
+
`The board "${name.trim()}" waits in Studio for the person to try and publish, on the Pedido ${made.item} you hold: ${studio}`,
|
|
995
|
+
...(made.others.length === 0
|
|
996
|
+
? []
|
|
997
|
+
: [
|
|
998
|
+
`Made with it, from the same template, as drafts the person publishes together with it: ${made.others.map((record) => `"${boardName(record)}"`).join(', ')}`,
|
|
999
|
+
]),
|
|
1000
|
+
...(made.submitted ? [] : [handInText(made.item, actor.name)]),
|
|
1001
|
+
];
|
|
1002
|
+
return { data: { ...made, studio }, text: lines.join('\n') };
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
// otea board draft --change: the agent the person asked to change a published board opens the
|
|
1006
|
+
// change on a Pedido it holds; the live board works on, and the person publishes it in Studio.
|
|
1007
|
+
function proposeChange(input, board, piped) {
|
|
1008
|
+
const why = input.option('why')?.trim() ?? '';
|
|
1009
|
+
const file = input.option('file');
|
|
1010
|
+
return withAgent(input, (project) => {
|
|
1011
|
+
if (why === '')
|
|
1012
|
+
throw new OteaError('missing_fields', 'Say what to change: --why "<what to change>"');
|
|
1013
|
+
const text = file === undefined ? undefined : draftFile(input.cwd, file, piped);
|
|
1014
|
+
const { actor, channel } = input;
|
|
1015
|
+
const made = proposeBoardChange(project, {
|
|
1016
|
+
board,
|
|
1017
|
+
need: why,
|
|
1018
|
+
lang: defaultLang(),
|
|
1019
|
+
actor,
|
|
1020
|
+
channel,
|
|
1021
|
+
...(text === undefined ? {} : { text }),
|
|
1022
|
+
});
|
|
1023
|
+
const name = made.board.draft?.definition.name ?? board;
|
|
1024
|
+
const studio = studioLink(project, made.board.id);
|
|
1025
|
+
const lines = [
|
|
1026
|
+
...(made.submitted ? handedInLines(made.item, made.submitted) : []),
|
|
1027
|
+
`The change to the board "${name}" waits in Studio for the person to try and publish, on the Pedido ${made.item} you hold; the board works as it is until then: ${studio}`,
|
|
1028
|
+
...(made.submitted ? [] : [handInText(made.item, actor.name)]),
|
|
1029
|
+
];
|
|
1030
|
+
return { data: { ...made, studio }, text: lines.join('\n') };
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
const boardDraft = {
|
|
1034
|
+
name: 'board draft',
|
|
1035
|
+
summary: 'Draft the board a Pedido asks for: without --file, print the draft to start from (JSON); with --file, check it as a board and hand it in on the Pedido as board.json, saying what is still wrong (the board keeps the name it was asked for; the name in the file is not used). To propose a new board the person asked you for, --new <name> --why "<what it is for>" (--template <key> to start from a catalogue board or a set such as ideas or repos, which makes its other boards with it; --file to hand it in at once) makes it and its Pedido, which you hold; --change <board> does the same for a change to a published board (a field, a step); the person publishes it in Studio',
|
|
1036
|
+
details: TEMPLATE_LIST,
|
|
1037
|
+
args: ['id?'],
|
|
1038
|
+
options: {
|
|
1039
|
+
file: { placeholder: 'board.json' },
|
|
1040
|
+
new: { placeholder: 'name' },
|
|
1041
|
+
why: { placeholder: 'what it is for' },
|
|
1042
|
+
template: { placeholder: 'key' },
|
|
1043
|
+
change: { placeholder: 'board' },
|
|
1044
|
+
},
|
|
1045
|
+
execute: async (input) => {
|
|
1046
|
+
const [id] = input.args;
|
|
1047
|
+
const name = input.option('new');
|
|
1048
|
+
const change = input.option('change');
|
|
1049
|
+
if ([id, name, change].filter((given) => given !== undefined).length > 1)
|
|
1050
|
+
throw new UsageError('Give the Pedido, --new <name> or --change <board>, only one');
|
|
1051
|
+
// --file - takes the board JSON from stdin (P1-R3-10).
|
|
1052
|
+
const piped = input.option('file') === '-' ? await input.stdin() : undefined;
|
|
1053
|
+
if (name !== undefined)
|
|
1054
|
+
return proposeBoard(input, name, piped);
|
|
1055
|
+
if (change !== undefined) {
|
|
1056
|
+
if (input.option('template') !== undefined)
|
|
1057
|
+
throw new UsageError('--template goes with --new <name>');
|
|
1058
|
+
return proposeChange(input, change, piped);
|
|
1059
|
+
}
|
|
1060
|
+
if (id === undefined)
|
|
1061
|
+
throw new UsageError('Give the Pedido, or --new <name> for a new board');
|
|
1062
|
+
if (input.option('why') !== undefined)
|
|
1063
|
+
throw new UsageError('--why goes with --new <name> or --change <board>');
|
|
1064
|
+
if (input.option('template') !== undefined)
|
|
1065
|
+
throw new UsageError('--template goes with --new <name>');
|
|
1066
|
+
const file = input.option('file');
|
|
1067
|
+
return withAgent(input, (project) => {
|
|
1068
|
+
if (file === undefined) {
|
|
1069
|
+
const definition = draftToStartFrom(project, id);
|
|
1070
|
+
return { data: definition, text: JSON.stringify(definition, null, 2) };
|
|
1071
|
+
}
|
|
1072
|
+
const text = draftFile(input.cwd, file, piped);
|
|
1073
|
+
const { actor, channel } = input;
|
|
1074
|
+
const submitted = submitAgentDraft(project, { id, text, actor, channel });
|
|
1075
|
+
return { data: submitted, text: handedInLines(id, submitted).join('\n') };
|
|
1076
|
+
});
|
|
1077
|
+
},
|
|
1078
|
+
};
|
|
1079
|
+
// otea prompt: what the person pastes into an agent's chat, as the UI copies it. With no moment it
|
|
1080
|
+
// picks the project's: the first contact where there is no project or no board of its own, the
|
|
1081
|
+
// join prompt (written from the project as it is now) once there are boards.
|
|
1082
|
+
function projectPrompt(cwd, kind, asked) {
|
|
1083
|
+
const empty = { boards: [], working: [] };
|
|
1084
|
+
let project;
|
|
1085
|
+
try {
|
|
1086
|
+
project = openProject(cwd);
|
|
1087
|
+
}
|
|
1088
|
+
catch (error) {
|
|
1089
|
+
if (error instanceof OteaError && error.code === 'not_found' && kind !== 'join')
|
|
1090
|
+
return agentPrompt(kind ?? 'start', asked ?? defaultLang(), empty);
|
|
1091
|
+
throw error;
|
|
1092
|
+
}
|
|
1093
|
+
try {
|
|
1094
|
+
const moment = kind ?? promptKindOf(project);
|
|
1095
|
+
return agentPrompt(moment, asked ?? defaultLang(), promptFacts(project, moment));
|
|
1096
|
+
}
|
|
1097
|
+
finally {
|
|
1098
|
+
project.db.close();
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
const promptCommand = {
|
|
1102
|
+
name: 'prompt',
|
|
1103
|
+
summary: "Print what to paste into an agent's chat: start (a new project: set up, connect, read the project, interview you one question at a time and draft its boards), join (one more agent working the boards there are, named from the project now) or design (one more board); without one, start until the project has boards of its own, then join. --lang en|es (default: the language you use: the desk's, else this computer's, else English)",
|
|
1104
|
+
args: ['moment?'],
|
|
1105
|
+
options: { lang: { placeholder: 'en|es' } },
|
|
1106
|
+
execute: (input) => {
|
|
1107
|
+
const [moment] = input.args;
|
|
1108
|
+
if (moment !== undefined && !isPromptKind(moment))
|
|
1109
|
+
throw new UsageError(`The moment is one of ${PROMPT_KINDS.join(', ')}`);
|
|
1110
|
+
const lang = input.option('lang');
|
|
1111
|
+
if (lang !== undefined && lang !== 'en' && lang !== 'es')
|
|
1112
|
+
throw new UsageError('--lang is en or es');
|
|
1113
|
+
const text = projectPrompt(input.cwd, moment, lang);
|
|
1114
|
+
return { data: { prompt: text }, text };
|
|
1115
|
+
},
|
|
1116
|
+
};
|
|
1117
|
+
const board = {
|
|
1118
|
+
name: 'board',
|
|
1119
|
+
summary: 'Print what agents read about a board before acting: its own words for them and each step\'s instructions; without a name, the project\'s boards and how to read each. To propose a new board, otea board draft --new "<name>" --why "<what it is for>"; the person publishes it in Studio',
|
|
1120
|
+
args: ['name?'],
|
|
1121
|
+
options: {},
|
|
1122
|
+
execute: (input) => {
|
|
1123
|
+
const [name = ''] = input.args;
|
|
1124
|
+
return withReader(input, (project) => {
|
|
1125
|
+
if (name !== '') {
|
|
1126
|
+
const guide = boardGuide(project, name);
|
|
1127
|
+
return { data: guide, text: guide.text };
|
|
1128
|
+
}
|
|
1129
|
+
const boards = guideIndex(project);
|
|
1130
|
+
const index = boards.length === 0
|
|
1131
|
+
? 'No boards yet; a human makes one in Studio or with "otea board add <name>".'
|
|
1132
|
+
: [
|
|
1133
|
+
'Read the board you work in before acting:',
|
|
1134
|
+
indent(columns(boards.map(({ name: each, board: id, command }) => [
|
|
1135
|
+
each,
|
|
1136
|
+
id === null ? 'draft' : 'board',
|
|
1137
|
+
command,
|
|
1138
|
+
]))),
|
|
1139
|
+
].join('\n');
|
|
1140
|
+
return { data: { boards }, text: withAgentGuide(project, index) };
|
|
1141
|
+
});
|
|
1142
|
+
},
|
|
1143
|
+
};
|
|
1144
|
+
const move = {
|
|
1145
|
+
name: 'move',
|
|
1146
|
+
summary: 'Move an item to another state its workflow allows the agent to reach',
|
|
1147
|
+
args: ['id', 'state'],
|
|
1148
|
+
options: { reason: {} },
|
|
1149
|
+
execute: (input) => {
|
|
1150
|
+
const [id = '', to = ''] = input.args;
|
|
1151
|
+
const { actor, channel, option } = input;
|
|
1152
|
+
const reason = option('reason');
|
|
1153
|
+
const moving = { id, to, actor, channel, ...(reason ? { reason } : {}) };
|
|
1154
|
+
return withAgent(input, (project) => itemResult(project, moveItem(project, moving)));
|
|
1155
|
+
},
|
|
1156
|
+
};
|
|
1157
|
+
// The guide's topics rule without its number, nor its opening (next and wait say it their way).
|
|
1158
|
+
const TOPICS_TEXT = TOPICS_RULE.replace(/^\d+\. Topics are on\. /, '');
|
|
1159
|
+
// What otea wait woke an agent for, with the topics reminder while topics are on: an agent in a
|
|
1160
|
+
// chat reads it between the person's messages, where side questions come.
|
|
1161
|
+
function withTopicsReminder(project, actor, output) {
|
|
1162
|
+
if (actor.kind !== 'agent' || !topicsOn(project))
|
|
1163
|
+
return output;
|
|
1164
|
+
const data = output.data !== null && typeof output.data === 'object'
|
|
1165
|
+
? { ...output.data, reminder: TOPICS_REMINDER }
|
|
1166
|
+
: output.data;
|
|
1167
|
+
return { ...output, data, text: `${output.text}\n\n${TOPICS_REMINDER}` };
|
|
1168
|
+
}
|
|
1169
|
+
// While topics are on, next names the topics waiting for the agent's answer (a note otea wait woke
|
|
1170
|
+
// it for is still there once it runs next) and the topics rule, which an agent whose session began
|
|
1171
|
+
// before the person turned topics on never read in its guide.
|
|
1172
|
+
function topicLines(project, agent) {
|
|
1173
|
+
if (!topicsOn(project))
|
|
1174
|
+
return [];
|
|
1175
|
+
const awaiting = topicsAwaitingText(topicsAwaiting(project, agent));
|
|
1176
|
+
const rule = `Topics are on. ${TOPICS_TEXT}`;
|
|
1177
|
+
return awaiting === undefined ? [rule] : [awaiting, rule];
|
|
1178
|
+
}
|
|
1179
|
+
const next = {
|
|
1180
|
+
name: 'next',
|
|
1181
|
+
summary: 'Say which item to take now on the published boards (or in --collection), oldest first, and what its step asks: what it starts with, the instructions, the handoff and where it goes next; when there is none, what to do meanwhile. Never offers an item another agent holds or was just offered; --claim also claims it in the same call',
|
|
1182
|
+
args: [],
|
|
1183
|
+
options: { collection: {}, claim: { flag: true } },
|
|
1184
|
+
execute: (input) => {
|
|
1185
|
+
const collection = input.option('collection');
|
|
1186
|
+
const claim = input.flag('claim');
|
|
1187
|
+
const { actor, channel } = input;
|
|
1188
|
+
return withAgent(input, (project) => {
|
|
1189
|
+
const profile = requireProfile(project.db, actor.name, { channel, confirmed: true });
|
|
1190
|
+
const answer = nextFor(project, actor.name, {
|
|
1191
|
+
...(collection === undefined ? {} : { collection }),
|
|
1192
|
+
...(claim ? { claim } : {}),
|
|
1193
|
+
});
|
|
1194
|
+
const offered = answer.item === null ? undefined : getItem(project, answer.item);
|
|
1195
|
+
const outside = offered && mergedOutsideLine(project, input.cwd, offered);
|
|
1196
|
+
// Offered work in the shared main checkout says so before the agent starts (P6-R2-3).
|
|
1197
|
+
const shared = offered && sharedCheckoutLine(project, input, offered.id);
|
|
1198
|
+
// It always ends with the exact command to keep waiting: told only to wait, agents ended
|
|
1199
|
+
// their turn, and the person's answer on the desk went unheard.
|
|
1200
|
+
const text = [
|
|
1201
|
+
...(outside ? [outside] : []),
|
|
1202
|
+
answer.text,
|
|
1203
|
+
...(shared ? [shared] : []),
|
|
1204
|
+
...topicLines(project, actor.name),
|
|
1205
|
+
profileReminder(profile, actor.name, channel),
|
|
1206
|
+
keepWaitingLine(actor.name, channel, { idle: answer.idle === true, collection }),
|
|
1207
|
+
].join('\n\n');
|
|
1208
|
+
return { data: { ...answer, text, profile: profileView(profile) }, text };
|
|
1209
|
+
});
|
|
1210
|
+
},
|
|
1211
|
+
};
|
|
1212
|
+
// A move on a board: the engine checks it, the item lands where it says, and the agent reads where
|
|
1213
|
+
// it stands now.
|
|
1214
|
+
function boardMove(input, run) {
|
|
1215
|
+
const [id = ''] = input.args;
|
|
1216
|
+
const { actor, channel, option } = input;
|
|
1217
|
+
const way = option('way');
|
|
1218
|
+
const reason = option('reason');
|
|
1219
|
+
const note = option('note');
|
|
1220
|
+
const move = {
|
|
1221
|
+
id,
|
|
1222
|
+
actor,
|
|
1223
|
+
channel,
|
|
1224
|
+
...(way === undefined ? {} : { way }),
|
|
1225
|
+
...(reason ? { reason } : {}),
|
|
1226
|
+
...(note ? { note } : {}),
|
|
1227
|
+
};
|
|
1228
|
+
return withAgent(input, (project) => {
|
|
1229
|
+
const { item, text } = run(project, move);
|
|
1230
|
+
return { data: { item: itemData(project, item), text }, text };
|
|
1231
|
+
});
|
|
1232
|
+
}
|
|
1233
|
+
// A step that hands a branch hands the work on it: an agent's handoff of one with no commits over
|
|
1234
|
+
// its base (the board's protected base, else origin's default branch, main or master) leaves the
|
|
1235
|
+
// review nothing to see. Only a branch this checkout has, here or on origin, is checked. The base
|
|
1236
|
+
// itself, on a board that works straight on it, is handed off with no commit as no code change
|
|
1237
|
+
// (P2S-R3-3, handedBranch).
|
|
1238
|
+
function refuseEmptyBranch(project, cwd, move) {
|
|
1239
|
+
if (move.actor.kind !== 'agent' || move.way !== undefined)
|
|
1240
|
+
return;
|
|
1241
|
+
const item = getItem(project, move.id);
|
|
1242
|
+
const board = liveBoardOf(project, item.collection);
|
|
1243
|
+
const position = positionOf(item.state);
|
|
1244
|
+
if (!board || isClosed(position) || position.phase !== 'doing')
|
|
1245
|
+
return;
|
|
1246
|
+
const step = stepById(board.def, position.step);
|
|
1247
|
+
for (const hand of step?.hand ?? []) {
|
|
1248
|
+
const part = board.def.parts[hand.ref];
|
|
1249
|
+
const branch = part?.kind === 'branch' ? item.fields[part.id] : undefined;
|
|
1250
|
+
if (!part || hand.req === 'no' || typeof branch !== 'string' || branch.trim() === '')
|
|
1251
|
+
continue;
|
|
1252
|
+
const base = part.guard?.base;
|
|
1253
|
+
if (branch.trim() === base)
|
|
1254
|
+
continue;
|
|
1255
|
+
const bases = [...(base ? [base, `origin/${base}`] : []), 'origin/HEAD', 'main', 'master'];
|
|
1256
|
+
const over = commitsOver(cwd, branch.trim(), bases);
|
|
1257
|
+
if (over?.count !== 0)
|
|
1258
|
+
continue;
|
|
1259
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${part.name} ${branch.trim()} has no commits over ${over.base}, so the review would find nothing in it. Commit your work on ${branch.trim()}, then hand it off again.`);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
// The protected branch as git has it here when a step that pushes or hands it is handed off: kept
|
|
1263
|
+
// with a handoff into a review, it is what the person approves, and all the push gate lets land
|
|
1264
|
+
// once it is approved (P3C-R2-1). Before the branch freezes in review, an agent's handoff is
|
|
1265
|
+
// refused when the branch it names is not here at all (P1-R2-2), or when it holds commits the
|
|
1266
|
+
// remote branch of its name never got, on a step that pushes it (P3C-R2-2), or when it is not the
|
|
1267
|
+
// work handed off: another open item's branch, or not the one checked out (P1-R3-1,
|
|
1268
|
+
// refuseOthersBranch). One never pushed though the repo has a remote is refused into a review, where
|
|
1269
|
+
// it would freeze (P6-R3-3); on a step nobody reviews it goes with a warning (P7-8). The base itself, on a board that works straight on it, is never pushed before
|
|
1270
|
+
// the approval; when it holds nothing the remote lacks, the item made no code change (a setting, a
|
|
1271
|
+
// question): it goes to review as such, said, and the push gate never waits on it (P2S-R3-3).
|
|
1272
|
+
function handedBranch(project, cwd, move) {
|
|
1273
|
+
const item = getItem(project, move.id);
|
|
1274
|
+
const board = liveBoardOf(project, item.collection);
|
|
1275
|
+
const position = positionOf(item.state);
|
|
1276
|
+
const guard = board && guardedBranch(board.def);
|
|
1277
|
+
if (!guard || isClosed(position) || position.phase !== 'doing')
|
|
1278
|
+
return {};
|
|
1279
|
+
// A step that pushes the branch, or that hands it in (on main, the work is committed, not pushed,
|
|
1280
|
+
// before the approval).
|
|
1281
|
+
const pushes = guard.guard.push.includes(position.step);
|
|
1282
|
+
const hands = stepById(board.def, position.step)?.hand.some(({ ref }) => ref === guard.id);
|
|
1283
|
+
if (!pushes && !hands)
|
|
1284
|
+
return {};
|
|
1285
|
+
const branch = String(item.fields[guard.id] ?? '').trim();
|
|
1286
|
+
if (branch === '')
|
|
1287
|
+
return {};
|
|
1288
|
+
const base = branch === guard.guard.base;
|
|
1289
|
+
const checked = move.actor.kind === 'agent' && move.way === undefined && !base;
|
|
1290
|
+
const state = checked ? pushState(cwd, branch) : undefined;
|
|
1291
|
+
const frozen = `once handed off, ${guard.name} is frozen while it is reviewed`;
|
|
1292
|
+
if (state?.kind === 'missing') {
|
|
1293
|
+
const on = state.on && state.on !== guard.guard.base ? state.on : '<branch>';
|
|
1294
|
+
const where = state.on ? ` (you are on ${state.on})` : '';
|
|
1295
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${guard.name} names ${branch}, a branch this checkout has neither here nor on the remote${where}. Set ${guard.name} to the branch that holds the work, otea update ${item.id} --field "${guard.name}=${on}", then hand it off again: ${frozen}.`);
|
|
1296
|
+
}
|
|
1297
|
+
// On the land step, a branch only the local base holds is not landed yet: the handoff that closes
|
|
1298
|
+
// the item waits for the push of the base (P6-R3-2).
|
|
1299
|
+
const local = checked && isLandStep(board.def, position.step)
|
|
1300
|
+
? mergedOutside(project, cwd, item)?.local
|
|
1301
|
+
: undefined;
|
|
1302
|
+
if (local) {
|
|
1303
|
+
const into = guard.guard.base ?? '';
|
|
1304
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${branch} is in your local ${into}, not yet in ${local.remote}, so closing it would leave it Done with ${into} unpushed. Push it first (git push ${local.push} ${into}), then hand it off again.`);
|
|
1305
|
+
}
|
|
1306
|
+
if (checked && hands && !isLandStep(board.def, position.step))
|
|
1307
|
+
refuseOthersBranch(project, cwd, move, item, guard.name, branch, guard.guard.base, frozen);
|
|
1308
|
+
// On the land step, once what the person approved is in the base as the remote has it (a forge
|
|
1309
|
+
// squash-merged the branch as it was pushed), commits here the remote never got (a rebase made
|
|
1310
|
+
// before the merge) need no push (P3C-R3-10).
|
|
1311
|
+
const landed = state?.kind === 'ahead' && isLandStep(board.def, position.step) && guard.guard.base
|
|
1312
|
+
? landedBase(project, cwd, item.id, branch, guard.guard.base)
|
|
1313
|
+
: undefined;
|
|
1314
|
+
if (state?.kind === 'ahead' && pushes && landed === undefined) {
|
|
1315
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${branch} holds commits ${state.remote} never got. Push it first (git push ${state.push} ${branch}), then hand it off again: ${frozen}, so the review would never see them.`);
|
|
1316
|
+
}
|
|
1317
|
+
if (state?.kind === 'ahead' && landed !== undefined)
|
|
1318
|
+
return {
|
|
1319
|
+
said: `${branch} holds commits ${state.remote} never got, but what the person approved is in ${landed} already, so they need no push: never push a merged branch to pass a check.`,
|
|
1320
|
+
};
|
|
1321
|
+
const tip = tipOf(cwd, branch, base);
|
|
1322
|
+
const unpushed = state?.kind === 'unpushed' && pushes;
|
|
1323
|
+
// No board lets an approval close an item whose code lives only on a branch never pushed (P7-8):
|
|
1324
|
+
// where its Rama is meant for a base and the review's approval closes the item (no land step
|
|
1325
|
+
// after it), the push comes first. With a land step, the approval leads there instead.
|
|
1326
|
+
const step = stepById(board.def, position.step);
|
|
1327
|
+
const closes = step?.reviewer !== 'none' && waysOf(board.def, position.step, item)[0] === DONE;
|
|
1328
|
+
if (state?.kind === 'unpushed' && pushes && guard.guard.base && closes) {
|
|
1329
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${branch} was never pushed to ${state.push}, and the approval of ${step?.name ?? position.step} closes ${item.id}, so it would be Done with its code only on this machine. Push it first (git push -u ${state.push} ${branch}), then hand it off again: ${frozen}.`);
|
|
1330
|
+
}
|
|
1331
|
+
// Into a review the branch freezes, so a push after the handoff is refused (P6-R3-3): the push
|
|
1332
|
+
// comes first. A step nobody reviews (a land step) keeps the note.
|
|
1333
|
+
if (state?.kind === 'unpushed' && pushes && step?.reviewer !== 'none') {
|
|
1334
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${branch} was never pushed to ${state.push}. Push it first (git push -u ${state.push} ${branch}), then hand it off again: ${frozen}, so no push of it gets through until the review ends.`);
|
|
1335
|
+
}
|
|
1336
|
+
const warning = unpushed
|
|
1337
|
+
? `Note: ${branch} was never pushed to ${state.push}. If the person reviews it on the forge (a pull request), they cannot see it there: ${frozen}.`
|
|
1338
|
+
: undefined;
|
|
1339
|
+
const unchanged = base &&
|
|
1340
|
+
hands &&
|
|
1341
|
+
move.actor.kind === 'agent' &&
|
|
1342
|
+
move.way === undefined &&
|
|
1343
|
+
pushState(cwd, branch)?.kind === 'pushed';
|
|
1344
|
+
const said = unchanged
|
|
1345
|
+
? `${item.id} goes to review with no commit: ${branch} holds nothing the remote lacks, so the person reviews no code change and the push gate does not wait on it.`
|
|
1346
|
+
: undefined;
|
|
1347
|
+
const kept = tip && unpushed ? { ...tip, pushed: false } : tip;
|
|
1348
|
+
return {
|
|
1349
|
+
...(kept ? { tip: unchanged ? { ...kept, unchanged: true } : kept } : {}),
|
|
1350
|
+
...(warning ? { warning } : {}),
|
|
1351
|
+
...(said ? { said } : {}),
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
// A handoff into review hands the work on the branch Rama names, and its approval keeps that
|
|
1355
|
+
// branch's tip (P1-R3-1): an agent's handoff is refused when another open item named that branch
|
|
1356
|
+
// first, and, at the CLI, when the checkout it runs in is on another branch. Over MCP the server
|
|
1357
|
+
// runs in the checkout its session started in, which a subagent in a worktree of its own shares,
|
|
1358
|
+
// so the branch checked out there tells nothing; so does a detached HEAD (a rebase under way).
|
|
1359
|
+
function refuseOthersBranch(project, cwd, move, item, name, branch, base, frozen) {
|
|
1360
|
+
const first = branchNamedFirst(project, item, branch);
|
|
1361
|
+
if (first)
|
|
1362
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${name} names ${branch}, the branch ${first.id} (${first.title}, open) named first, so the review would read ${first.id}'s work and an approval would keep its tip. Each item works on its own branch: set ${name} to the branch that holds ${item.id}'s work, otea update ${item.id} --field "${name}=<branch>", then hand it off again: ${frozen}.`);
|
|
1363
|
+
if (move.channel === 'mcp')
|
|
1364
|
+
return;
|
|
1365
|
+
const on = checkedOutBranch(cwd);
|
|
1366
|
+
if (on === undefined || on === branch)
|
|
1367
|
+
return;
|
|
1368
|
+
const set = on === base
|
|
1369
|
+
? ''
|
|
1370
|
+
: `, or set ${name} to the branch that holds the work, otea update ${item.id} --field "${name}=${on}"`;
|
|
1371
|
+
throw new OteaError('missing_fields', `${item.id} not handed off: ${name} names ${branch}, but this checkout is on ${on}, so the review would read a branch other than the one you worked on. Hand off from the checkout of ${branch} (git switch ${branch})${set}, then hand it off again: ${frozen}.`);
|
|
1372
|
+
}
|
|
1373
|
+
// The base as the remote has it (origin/main), when what the person approved of the item's branch
|
|
1374
|
+
// is in it already; undefined otherwise, or with no approved tip to tell.
|
|
1375
|
+
function landedBase(project, cwd, id, branch, base) {
|
|
1376
|
+
const approved = approvedTipOf(project, id, branch);
|
|
1377
|
+
const onto = remoteOf(cwd, base);
|
|
1378
|
+
return approved && landedIn(cwd, approved.commit, onto) ? onto : undefined;
|
|
1379
|
+
}
|
|
1380
|
+
const handoffCommand = {
|
|
1381
|
+
name: 'handoff',
|
|
1382
|
+
summary: 'Hand off the step you did on an item: refused, saying what is missing, until its handoff is complete; then to its review, or along --way (a step name or Done) with --reason when the step has several. --note is the note of the handoff, kept with the round (required where the step asks for one, and after a send-back); --way an earlier step, with --reason, takes the item back to it for its next round; again in review, --note amends it',
|
|
1383
|
+
args: ['id'],
|
|
1384
|
+
options: { way: { placeholder: 'step' }, reason: {}, note: {} },
|
|
1385
|
+
execute: (input) => {
|
|
1386
|
+
let warning;
|
|
1387
|
+
let said;
|
|
1388
|
+
const moved = boardMove(input, (project, move) => {
|
|
1389
|
+
refuseEmptyBranch(project, input.cwd, move);
|
|
1390
|
+
const handed = handedBranch(project, input.cwd, move);
|
|
1391
|
+
warning = handed.warning;
|
|
1392
|
+
said = handed.said;
|
|
1393
|
+
return handoffItem(project, { ...move, ...(handed.tip ? { tip: handed.tip } : {}) });
|
|
1394
|
+
});
|
|
1395
|
+
// An agent goes on to the next item, and waits when there is none: the reply ends with the
|
|
1396
|
+
// exact commands, so it neither stops after one nor says it waits with no wait running
|
|
1397
|
+
// (P3C-R3-9).
|
|
1398
|
+
const next = waitAgainLine(input.actor.name, input.channel);
|
|
1399
|
+
return {
|
|
1400
|
+
data: {
|
|
1401
|
+
...moved.data,
|
|
1402
|
+
next,
|
|
1403
|
+
...(warning ? { warning } : {}),
|
|
1404
|
+
...(said ? { unchanged: said } : {}),
|
|
1405
|
+
},
|
|
1406
|
+
text: [moved.text, ...(said ? [said] : []), ...(warning ? [warning] : []), next].join('\n'),
|
|
1407
|
+
};
|
|
1408
|
+
},
|
|
1409
|
+
};
|
|
1410
|
+
const dropCommand = {
|
|
1411
|
+
name: 'drop',
|
|
1412
|
+
summary: 'Drop an item that is not worth doing, saying why with --reason, and, on a board with motives, which one with --motive (its name); an agent drops only while doing a step that lets it',
|
|
1413
|
+
args: ['id'],
|
|
1414
|
+
options: { reason: {}, motive: {} },
|
|
1415
|
+
execute: (input) => {
|
|
1416
|
+
const [id = ''] = input.args;
|
|
1417
|
+
const { actor, channel, option } = input;
|
|
1418
|
+
const reason = option('reason');
|
|
1419
|
+
const motive = option('motive');
|
|
1420
|
+
const dropping = {
|
|
1421
|
+
id,
|
|
1422
|
+
actor,
|
|
1423
|
+
channel,
|
|
1424
|
+
...(reason ? { reason } : {}),
|
|
1425
|
+
...(motive ? { motive } : {}),
|
|
1426
|
+
};
|
|
1427
|
+
return withAgent(input, (project) => {
|
|
1428
|
+
const { item, text } = dropItem(project, dropping);
|
|
1429
|
+
return { data: { item: itemData(project, item), text }, text };
|
|
1430
|
+
});
|
|
1431
|
+
},
|
|
1432
|
+
};
|
|
1433
|
+
// Approving and sending back a step the person reviews is theirs, in the desk; the person who runs
|
|
1434
|
+
// approve at a terminal, told to by an agent, gets «Name yourself first» otherwise (P2S-R3-7).
|
|
1435
|
+
function personReviews(input, what) {
|
|
1436
|
+
if (input.agent !== undefined || input.channel === 'mcp')
|
|
1437
|
+
return;
|
|
1438
|
+
const [id = '<id>'] = input.args;
|
|
1439
|
+
const doing = what === 'approve' ? `Approving ${id} is` : `Sending ${id} back is`;
|
|
1440
|
+
throw new OteaError('unnamed_agent', `${doing} the person's, in the desk: open ${id} there (otea serve gives its address) and approve it or send it back. An agent never approves a step the person reviews. An agent reviewing a step agents review names itself: otea ${what} ${id} --as <name>.`);
|
|
1441
|
+
}
|
|
1442
|
+
const approveCommand = {
|
|
1443
|
+
name: 'approve',
|
|
1444
|
+
summary: 'Approve the step you review, along --way when it has several; --note for the next step',
|
|
1445
|
+
args: ['id'],
|
|
1446
|
+
options: { way: { placeholder: 'step' }, note: {} },
|
|
1447
|
+
execute: (input) => {
|
|
1448
|
+
personReviews(input, 'approve');
|
|
1449
|
+
return boardMove(input, approveItem);
|
|
1450
|
+
},
|
|
1451
|
+
};
|
|
1452
|
+
const sendBack = {
|
|
1453
|
+
name: 'send-back',
|
|
1454
|
+
summary: 'Send the step you review on an item back for another round, saying what to change with --reason',
|
|
1455
|
+
args: ['id'],
|
|
1456
|
+
options: { reason: { required: true } },
|
|
1457
|
+
execute: (input) => {
|
|
1458
|
+
personReviews(input, 'send-back');
|
|
1459
|
+
input.required('reason');
|
|
1460
|
+
return boardMove(input, sendBackItem);
|
|
1461
|
+
},
|
|
1462
|
+
};
|
|
1463
|
+
const KINDS = RELATION_KINDS.join(', ');
|
|
1464
|
+
const link = {
|
|
1465
|
+
name: 'link',
|
|
1466
|
+
summary: `Link an item to another, in this project, with a typed relation (${KINDS}): "<id> blocks <other>" reads as it says, "<id> parent <other>" makes <other> the parent of <id>`,
|
|
1467
|
+
args: ['id', 'kind', 'other'],
|
|
1468
|
+
options: {},
|
|
1469
|
+
execute: (input) => {
|
|
1470
|
+
const [id = '', kind = '', other = ''] = input.args;
|
|
1471
|
+
const { actor, channel } = input;
|
|
1472
|
+
const relation = withAgent(input, (project) => linkItems(project, { id, kind, other, actor, channel }));
|
|
1473
|
+
return { data: relation, text: describeRelation(relation) };
|
|
1474
|
+
},
|
|
1475
|
+
};
|
|
1476
|
+
const unlink = {
|
|
1477
|
+
name: 'unlink',
|
|
1478
|
+
summary: 'Remove a relation made with "otea link", named the same way',
|
|
1479
|
+
args: ['id', 'kind', 'other'],
|
|
1480
|
+
options: {},
|
|
1481
|
+
execute: (input) => {
|
|
1482
|
+
const [id = '', kind = '', other = ''] = input.args;
|
|
1483
|
+
const { actor, channel } = input;
|
|
1484
|
+
const relation = withAgent(input, (project) => unlinkItems(project, { id, kind, other, actor, channel }));
|
|
1485
|
+
return { data: relation, text: `Removed: ${describeRelation(relation)}` };
|
|
1486
|
+
},
|
|
1487
|
+
};
|
|
1488
|
+
// Kept apart from every other write so a harness can ask the human to confirm each relay.
|
|
1489
|
+
const relay = {
|
|
1490
|
+
name: 'relay',
|
|
1491
|
+
summary: 'Record a decision the human made in conversation: move the item as the human, via you (human transitions only; human-ui ones stay in the web UI)',
|
|
1492
|
+
args: ['id', 'state'],
|
|
1493
|
+
options: {
|
|
1494
|
+
quote: { required: true, placeholder: 'what the human said' },
|
|
1495
|
+
reason: {},
|
|
1496
|
+
motive: { placeholder: 'name' },
|
|
1497
|
+
},
|
|
1498
|
+
execute: (input) => {
|
|
1499
|
+
const [id = '', to = ''] = input.args;
|
|
1500
|
+
const quote = input.required('quote');
|
|
1501
|
+
const reason = input.option('reason');
|
|
1502
|
+
const motive = input.option('motive');
|
|
1503
|
+
const via = input.actor.name;
|
|
1504
|
+
const { channel } = input;
|
|
1505
|
+
const relayed = {
|
|
1506
|
+
id,
|
|
1507
|
+
to,
|
|
1508
|
+
via,
|
|
1509
|
+
channel,
|
|
1510
|
+
quote,
|
|
1511
|
+
...(reason ? { reason } : {}),
|
|
1512
|
+
...(motive ? { motive } : {}),
|
|
1513
|
+
};
|
|
1514
|
+
return withAgent(input, (project) => itemResult(project, relayDecision(project, relayed)));
|
|
1515
|
+
},
|
|
1516
|
+
};
|
|
1517
|
+
const COUNT_PATTERN = /^\d+$/;
|
|
1518
|
+
function countFrom(name, value, min) {
|
|
1519
|
+
if (value === undefined)
|
|
1520
|
+
return undefined;
|
|
1521
|
+
const count = Number(value);
|
|
1522
|
+
if (!COUNT_PATTERN.test(value) || count < min) {
|
|
1523
|
+
throw new UsageError(`--${name} must be an integer of at least ${min}`);
|
|
1524
|
+
}
|
|
1525
|
+
return count;
|
|
1526
|
+
}
|
|
1527
|
+
function eventFilter({ option }) {
|
|
1528
|
+
const filter = {};
|
|
1529
|
+
const item = option('item');
|
|
1530
|
+
const collection = option('collection');
|
|
1531
|
+
const since = countFrom('since', option('since'), 0);
|
|
1532
|
+
const limit = countFrom('limit', option('limit'), 1);
|
|
1533
|
+
if (item !== undefined)
|
|
1534
|
+
filter.item = item;
|
|
1535
|
+
if (collection !== undefined)
|
|
1536
|
+
filter.collection = collection;
|
|
1537
|
+
if (since !== undefined)
|
|
1538
|
+
filter.since = since;
|
|
1539
|
+
// After a cursor, --limit pages forward from it; alone, it reads the latest events.
|
|
1540
|
+
if (limit !== undefined && since !== undefined)
|
|
1541
|
+
filter.limit = limit;
|
|
1542
|
+
if (limit !== undefined && since === undefined)
|
|
1543
|
+
filter.latest = limit;
|
|
1544
|
+
return filter;
|
|
1545
|
+
}
|
|
1546
|
+
const brief = {
|
|
1547
|
+
name: 'brief',
|
|
1548
|
+
summary: 'Print a Markdown brief for the items given, in the order their blocks allow, with its limits (--constraint, repeatable) and success criteria (--success, repeatable), which replace the default lines',
|
|
1549
|
+
args: ['ids...'],
|
|
1550
|
+
options: {
|
|
1551
|
+
constraint: { multiple: true, placeholder: 'text' },
|
|
1552
|
+
success: { multiple: true, placeholder: 'text' },
|
|
1553
|
+
},
|
|
1554
|
+
execute: ({ cwd, args, options }) => {
|
|
1555
|
+
const limits = options('constraint');
|
|
1556
|
+
const success = options('success');
|
|
1557
|
+
const written = withProject(cwd, (project) => briefFor(project, {
|
|
1558
|
+
ids: args,
|
|
1559
|
+
...(limits.length > 0 ? { limits } : {}),
|
|
1560
|
+
...(success.length > 0 ? { success } : {}),
|
|
1561
|
+
}));
|
|
1562
|
+
return { data: written, text: written.markdown.trimEnd() };
|
|
1563
|
+
},
|
|
1564
|
+
};
|
|
1565
|
+
const events = {
|
|
1566
|
+
name: 'events',
|
|
1567
|
+
summary: 'Print the event log in commit order, after the event id given to --since; --limit alone prints the latest n, after --since the first n; --follow keeps printing new events until Ctrl+C',
|
|
1568
|
+
args: [],
|
|
1569
|
+
options: {
|
|
1570
|
+
item: { placeholder: 'id' },
|
|
1571
|
+
collection: {},
|
|
1572
|
+
since: { placeholder: 'event id' },
|
|
1573
|
+
limit: { placeholder: 'n' },
|
|
1574
|
+
follow: { flag: true },
|
|
1575
|
+
},
|
|
1576
|
+
execute: async (input) => {
|
|
1577
|
+
const filter = eventFilter(input);
|
|
1578
|
+
const follow = input.flag('follow');
|
|
1579
|
+
if (follow && (filter.limit ?? filter.latest) !== undefined) {
|
|
1580
|
+
throw new UsageError('--limit cannot be combined with --follow');
|
|
1581
|
+
}
|
|
1582
|
+
await withReaderWhile(input, async (project) => {
|
|
1583
|
+
let since = filter.since ?? 0;
|
|
1584
|
+
const collectionOf = itemCollections(project);
|
|
1585
|
+
const printNew = () => {
|
|
1586
|
+
// Read afresh each time: a board published while following names its steps anew.
|
|
1587
|
+
const boardOf = boardsOf(project);
|
|
1588
|
+
for (const event of listEvents(project, { ...filter, since })) {
|
|
1589
|
+
const def = boardOf(collectionOf(event.itemId));
|
|
1590
|
+
input.print(eventData(def, event), formatEvent(readableEvent(def, event)));
|
|
1591
|
+
since = event.id;
|
|
1592
|
+
}
|
|
1593
|
+
return undefined;
|
|
1594
|
+
};
|
|
1595
|
+
printNew();
|
|
1596
|
+
if (follow)
|
|
1597
|
+
await watch(project.db, printNew, { signal: input.signal });
|
|
1598
|
+
});
|
|
1599
|
+
return undefined;
|
|
1600
|
+
},
|
|
1601
|
+
};
|
|
1602
|
+
// How each model performs: per model family and effort, from the profile on each handoff.
|
|
1603
|
+
const stats = {
|
|
1604
|
+
name: 'stats',
|
|
1605
|
+
summary: 'Print how each model performs on the boards, per model family and effort (and per exact model and step): handoffs, how many came back, rounds per finished step, items done, discards and the median time from claim to handoff; --since 7d, 30d or all (the default), --board keeps one board. Profiles are as the agents declare them',
|
|
1606
|
+
args: [],
|
|
1607
|
+
options: { board: {}, since: { placeholder: 'period' } },
|
|
1608
|
+
execute: ({ cwd, option }) => {
|
|
1609
|
+
const board = option('board');
|
|
1610
|
+
const since = option('since') ?? 'all';
|
|
1611
|
+
const view = withProject(cwd, (project) => performanceOf(project, { board, since }));
|
|
1612
|
+
return { data: view, text: statsText(view, since) };
|
|
1613
|
+
},
|
|
1614
|
+
};
|
|
1615
|
+
function durationFrom(name, value) {
|
|
1616
|
+
if (value === undefined)
|
|
1617
|
+
return undefined;
|
|
1618
|
+
const duration = parseDuration(value);
|
|
1619
|
+
if (duration === undefined) {
|
|
1620
|
+
throw new UsageError(`--${name} must be a positive duration such as 90s, 15m or 1h`);
|
|
1621
|
+
}
|
|
1622
|
+
return duration;
|
|
1623
|
+
}
|
|
1624
|
+
const ttlFrom = (value) => durationFrom('ttl', value);
|
|
1625
|
+
const TTL = { ttl: { placeholder: 'duration' } };
|
|
1626
|
+
// Lease expiry writes nothing, so a wait for unclaimed items also checks again on this timer.
|
|
1627
|
+
const LEASE_RECHECK_MS = 1000;
|
|
1628
|
+
const wait = {
|
|
1629
|
+
name: 'wait',
|
|
1630
|
+
summary: 'Wait until an item is on the turn and print it as a list row, at once if one already is; the one waiting longest in its state comes first. A note from the person on an item you hold, or their answer to your question, wakes it too, saying which',
|
|
1631
|
+
args: [],
|
|
1632
|
+
options: {
|
|
1633
|
+
turn: { required: true, choices: ['agent', 'human'] },
|
|
1634
|
+
collection: {},
|
|
1635
|
+
unclaimed: { flag: true },
|
|
1636
|
+
timeout: { placeholder: 'duration' },
|
|
1637
|
+
},
|
|
1638
|
+
execute: async (input) => {
|
|
1639
|
+
const turn = input.required('turn');
|
|
1640
|
+
const timeout = input.option('timeout');
|
|
1641
|
+
const timeoutMs = durationFrom('timeout', timeout);
|
|
1642
|
+
const filter = listFilter(input);
|
|
1643
|
+
// A wait whose starter is gone (its agent's session ended) stops: left running it would keep
|
|
1644
|
+
// the agent shown as listening until its timeout.
|
|
1645
|
+
const owner = watchOwner(input.signal);
|
|
1646
|
+
const options = {
|
|
1647
|
+
signal: owner.signal,
|
|
1648
|
+
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
1649
|
+
...(filter.availableTo === undefined ? {} : { recheckMs: LEASE_RECHECK_MS }),
|
|
1650
|
+
};
|
|
1651
|
+
const result = await withAgentWhile(input, async (project) => {
|
|
1652
|
+
// A note from the person on an item this agent holds wakes it too: it answers it first. So
|
|
1653
|
+
// does the person's answer to its question.
|
|
1654
|
+
const me = input.actor.name;
|
|
1655
|
+
// An agent waiting for unclaimed agent work wakes only for an item next would offer it: one left for
|
|
1656
|
+
// or just offered to another agent would wake it to "nothing to do" again and again.
|
|
1657
|
+
const forMe = input.actor.kind === 'agent' && turn === 'agent' && filter.availableTo !== undefined;
|
|
1658
|
+
// A board the person publishes while it waits joins the catalog before the check reads its
|
|
1659
|
+
// items, as the server does on each request; it costs one query when nothing was published.
|
|
1660
|
+
const check = () => {
|
|
1661
|
+
syncBoardPresets(project);
|
|
1662
|
+
return lookFor();
|
|
1663
|
+
};
|
|
1664
|
+
// Topics the person turns on while an agent waits wake it once with their rule: its session
|
|
1665
|
+
// began without it, and an agent at work reads it in next.
|
|
1666
|
+
const topicsBefore = topicsOn(project);
|
|
1667
|
+
const topicsTurnedOn = () => input.actor.kind === 'agent' && !topicsBefore && topicsOn(project)
|
|
1668
|
+
? { topics: 'on', text: `The person turned topics on. ${TOPICS_TEXT}` }
|
|
1669
|
+
: undefined;
|
|
1670
|
+
// An agent waiting on the agent turn while its own question waits for the person waits for
|
|
1671
|
+
// the answer, and for its send-backs and new work; work already free when it asked does not
|
|
1672
|
+
// wake it (wakesWhileAsking).
|
|
1673
|
+
const onItsQuestion = () => input.actor.kind === 'agent' && turn === 'agent' && askedByAgent(project, me).length > 0;
|
|
1674
|
+
const keep = () => {
|
|
1675
|
+
const offerable = forMe ? offerableTo(project, me) : undefined;
|
|
1676
|
+
const asking = input.actor.kind === 'agent' && turn === 'agent'
|
|
1677
|
+
? wakesWhileAsking(project, me)
|
|
1678
|
+
: undefined;
|
|
1679
|
+
if (!asking)
|
|
1680
|
+
return offerable;
|
|
1681
|
+
return (item) => asking(item) && (offerable?.(item) ?? true);
|
|
1682
|
+
};
|
|
1683
|
+
const lookFor = () => topicsTurnedOn() ??
|
|
1684
|
+
noteWaiting(project, me) ??
|
|
1685
|
+
(input.actor.kind === 'agent' ? topicWaiting(project, me) : undefined) ??
|
|
1686
|
+
answerWaiting(project, me) ??
|
|
1687
|
+
oldestWaiting(project, filter, undefined, keep());
|
|
1688
|
+
// Waiting is listening: the agent is heard as it waits, so it counts as connected and its
|
|
1689
|
+
// profile stays confirmed.
|
|
1690
|
+
// When it was last heard: a wait whose session ended stops its agent listening at once.
|
|
1691
|
+
let heardAt;
|
|
1692
|
+
// On the command line its own process is watched: killed with its session, it leaves its
|
|
1693
|
+
// agent counted as gone at once, not a listening window later (P2S-R2-7, P8-R2-7).
|
|
1694
|
+
const waiter = input.channel === 'cli' ? { waiter: process.pid } : {};
|
|
1695
|
+
const heard = input.actor.kind === 'agent'
|
|
1696
|
+
? waitBeat(project.db, {
|
|
1697
|
+
agent: me,
|
|
1698
|
+
channel: input.channel,
|
|
1699
|
+
harness: input.harness,
|
|
1700
|
+
...waiter,
|
|
1701
|
+
})
|
|
1702
|
+
: undefined;
|
|
1703
|
+
const beat = heard
|
|
1704
|
+
? {
|
|
1705
|
+
beat: {
|
|
1706
|
+
everyMs: heard.everyMs,
|
|
1707
|
+
run: () => {
|
|
1708
|
+
heardAt = heard.run();
|
|
1709
|
+
},
|
|
1710
|
+
},
|
|
1711
|
+
}
|
|
1712
|
+
: {};
|
|
1713
|
+
// It listens from the start, not from its first beat.
|
|
1714
|
+
beat.beat?.run();
|
|
1715
|
+
const waited = await watch(project.db, check, { ...options, ...beat }).finally(() => {
|
|
1716
|
+
owner.stop();
|
|
1717
|
+
if (heard && input.channel === 'cli') {
|
|
1718
|
+
// A wait whose session ended (it saw its owner gone) stays noted, as one killed with
|
|
1719
|
+
// it does: its agent's session reads as ended (P3C-R3-11).
|
|
1720
|
+
if (!owner.orphaned())
|
|
1721
|
+
endWaiter(project.db, me, process.pid);
|
|
1722
|
+
endProcess(project.db, process.pid);
|
|
1723
|
+
}
|
|
1724
|
+
});
|
|
1725
|
+
if (owner.orphaned() && heardAt)
|
|
1726
|
+
endListening(project.db, me, heardAt);
|
|
1727
|
+
// It waits no more once it found something or was stopped; a timeout is called again at once.
|
|
1728
|
+
const timedOut = !('found' in waited) && waited.stopped === 'timeout';
|
|
1729
|
+
if (heardAt && !timedOut)
|
|
1730
|
+
endWaiting(project.db, me, heardAt);
|
|
1731
|
+
if (!('found' in waited)) {
|
|
1732
|
+
return { ...waited, asked: onItsQuestion() ? askedByAgent(project, me) : [] };
|
|
1733
|
+
}
|
|
1734
|
+
const { found } = waited;
|
|
1735
|
+
const row = 'text' in found ? { data: found, text: found.text } : itemResult(project, found);
|
|
1736
|
+
// A parent whose parts wait to be merged: the merges are what the agent does now.
|
|
1737
|
+
const merges = 'text' in found ? undefined : mergeFirstFor(project, found.id);
|
|
1738
|
+
// The item it just let go of: how to set it aside, if the person wants it later (P3C-R3-2).
|
|
1739
|
+
const later = 'text' in found || input.actor.kind !== 'agent'
|
|
1740
|
+
? undefined
|
|
1741
|
+
: laterLine(project, found.id, me);
|
|
1742
|
+
// That the person took it up again, and their unanswered notes (P7-R3-8, P5-R3-8).
|
|
1743
|
+
const woken = 'text' in found ? [] : wokeLines(project, found.id);
|
|
1744
|
+
const added = [merges, later, ...woken].filter((line) => line !== undefined);
|
|
1745
|
+
const woke = added.length === 0 ? row : { ...row, text: [row.text, ...added].join('\n') };
|
|
1746
|
+
// While topics are on, what woke the agent reminds it to record side questions.
|
|
1747
|
+
const reminded = 'topics' in found ? woke : withTopicsReminder(project, input.actor, woke);
|
|
1748
|
+
// An agent woken on its turn reads what woke it, then waits again: told so in exact words.
|
|
1749
|
+
if (input.actor.kind !== 'agent' || turn !== 'agent')
|
|
1750
|
+
return reminded;
|
|
1751
|
+
return {
|
|
1752
|
+
...reminded,
|
|
1753
|
+
text: `${reminded.text}\n${waitAgainLine(me, input.channel, filter.collection)}`,
|
|
1754
|
+
};
|
|
1755
|
+
});
|
|
1756
|
+
if ('data' in result)
|
|
1757
|
+
return result;
|
|
1758
|
+
if (result.stopped === 'timeout') {
|
|
1759
|
+
const asked = result.asked.join(', ');
|
|
1760
|
+
const said = asked === ''
|
|
1761
|
+
? `No item reached the ${turn} turn within ${timeout}`
|
|
1762
|
+
: `The person has not answered your question on ${asked} within ${timeout}`;
|
|
1763
|
+
// A timeout is no end of the work: an agent waits again, with the exact command.
|
|
1764
|
+
const again = input.actor.kind === 'agent' && turn === 'agent'
|
|
1765
|
+
? `; keep waiting: ${keepWaitingCommand(input.actor.name, filter.collection)}`
|
|
1766
|
+
: '';
|
|
1767
|
+
throw new CommandFailure('timeout', `${said}${again}`);
|
|
1768
|
+
}
|
|
1769
|
+
if (owner.orphaned()) {
|
|
1770
|
+
throw new CommandFailure('interrupted', 'Stopped waiting: the session that started it ended');
|
|
1771
|
+
}
|
|
1772
|
+
throw new CommandFailure('interrupted', 'Interrupted while waiting');
|
|
1773
|
+
},
|
|
1774
|
+
};
|
|
1775
|
+
// An agent that claims, or is offered, an item in the repo's main checkout is told to work in its
|
|
1776
|
+
// own worktree (P1-15, P6-R2-3) while other agents hold work in the project (two agents in one
|
|
1777
|
+
// checkout change each other's files), or while that checkout sits on another open item's branch
|
|
1778
|
+
// (switching it here changes that item's work, as Integrar left it twice).
|
|
1779
|
+
function sharedCheckoutLine(project, input, id) {
|
|
1780
|
+
if (!inMainCheckout(input.cwd))
|
|
1781
|
+
return undefined;
|
|
1782
|
+
const me = input.actor.name;
|
|
1783
|
+
const others = [
|
|
1784
|
+
...new Set(listAgents(project.db)
|
|
1785
|
+
.filter((agent) => agent.name !== me && agent.holding.length > 0)
|
|
1786
|
+
.map(({ name }) => name)),
|
|
1787
|
+
];
|
|
1788
|
+
let on;
|
|
1789
|
+
try {
|
|
1790
|
+
on = currentBranch(input.cwd);
|
|
1791
|
+
}
|
|
1792
|
+
catch { }
|
|
1793
|
+
const holder = on === undefined ? undefined : openItemOn(project, on, id);
|
|
1794
|
+
const lines = [];
|
|
1795
|
+
if (holder && on) {
|
|
1796
|
+
lines.push(`This is the repository's main checkout, and it is on ${on}, the branch of ${holder}: do ${id ?? 'this item'} in its own git worktree (git worktree add ../<folder> -b <branch>) and leave ${holder}'s branch as it is.`);
|
|
1797
|
+
}
|
|
1798
|
+
if (others.length > 0) {
|
|
1799
|
+
lines.push(`${others.join(', ')} also holds work in this project, and you are in the repository's main checkout: do your work on your own branch in your own git worktree (git worktree add ../<folder> -b <branch>), never in files another agent is changing.`);
|
|
1800
|
+
}
|
|
1801
|
+
return lines.length > 0 ? lines.join('\n') : undefined;
|
|
1802
|
+
}
|
|
1803
|
+
// The open board item, other than `except`, whose protected branch is `branch` (never a base a
|
|
1804
|
+
// board protects: the base is every item's).
|
|
1805
|
+
function openItemOn(project, branch, except) {
|
|
1806
|
+
for (const board of liveBoards(project)) {
|
|
1807
|
+
const guard = guardedBranch(board.def);
|
|
1808
|
+
if (!guard || guard.guard.base === branch)
|
|
1809
|
+
continue;
|
|
1810
|
+
const found = listItems(project, { collection: board.collection }).find((item) => item.id !== except &&
|
|
1811
|
+
!isClosed(positionOf(item.state)) &&
|
|
1812
|
+
String(item.fields[guard.id] ?? '').trim() === branch);
|
|
1813
|
+
if (found)
|
|
1814
|
+
return found.id;
|
|
1815
|
+
}
|
|
1816
|
+
return undefined;
|
|
1817
|
+
}
|
|
1818
|
+
const claim = {
|
|
1819
|
+
name: 'claim',
|
|
1820
|
+
summary: 'Hold an item on the agent turn so no other agent can write it (default --ttl 15m); claiming it again extends it',
|
|
1821
|
+
args: ['id'],
|
|
1822
|
+
options: TTL,
|
|
1823
|
+
execute: (input) => {
|
|
1824
|
+
const [id = ''] = input.args;
|
|
1825
|
+
const { actor, option } = input;
|
|
1826
|
+
const ttl = ttlFrom(option('ttl'));
|
|
1827
|
+
const lease = { id, actor, ...(ttl === undefined ? {} : { ttlMs: ttl }) };
|
|
1828
|
+
return withAgent(input, (project) => {
|
|
1829
|
+
requireProfile(project.db, actor.name, { channel: input.channel });
|
|
1830
|
+
const item = claimItem(project, lease);
|
|
1831
|
+
const claimed = itemResult(project, item);
|
|
1832
|
+
// P3C-R3-11: the lease of an agent whose session ended is taken over, and said.
|
|
1833
|
+
const over = item.tookOver
|
|
1834
|
+
? `Took ${item.id} over from ${item.tookOver}: its session ended (no MCP server or wait of it runs), so its lease was yours to take.`
|
|
1835
|
+
: undefined;
|
|
1836
|
+
const shared = sharedCheckoutLine(project, input, id);
|
|
1837
|
+
const lines = [claimed.text, over, shared].filter((line) => line !== undefined);
|
|
1838
|
+
return {
|
|
1839
|
+
data: item.tookOver
|
|
1840
|
+
? { ...claimed.data, tookOver: item.tookOver }
|
|
1841
|
+
: claimed.data,
|
|
1842
|
+
text: lines.join('\n'),
|
|
1843
|
+
};
|
|
1844
|
+
});
|
|
1845
|
+
},
|
|
1846
|
+
};
|
|
1847
|
+
// How the name whoami gives back came through: the harness the session named, another one it is
|
|
1848
|
+
// known by, or one nobody knows (an agent seen only on the command line).
|
|
1849
|
+
function throughText({ harness, sameHarness }) {
|
|
1850
|
+
if (sameHarness)
|
|
1851
|
+
return 'through this harness';
|
|
1852
|
+
return harness === null ? '(its harness is not known)' : `through ${harness}`;
|
|
1853
|
+
}
|
|
1854
|
+
// The name a session takes: the one it worked under before here (same folder, same harness, not
|
|
1855
|
+
// connected now), so it keeps one name across sessions; else a new one, never one connected now.
|
|
1856
|
+
const whoami = {
|
|
1857
|
+
name: 'whoami',
|
|
1858
|
+
summary: 'Say which agent name to use in this session: the one you worked under before from this folder through the same harness (and not connected now), or that you pick a new one, not one of the agents connected now. --harness names the tool you run in (an MCP client names its own)',
|
|
1859
|
+
args: [],
|
|
1860
|
+
options: { harness: { placeholder: 'name' } },
|
|
1861
|
+
execute: (input) => {
|
|
1862
|
+
const { cwd, option } = input;
|
|
1863
|
+
const client = input.channel === 'mcp' ? input.harness?.name : undefined;
|
|
1864
|
+
const harness = option('harness') ?? client;
|
|
1865
|
+
return withProject(cwd, (project) => {
|
|
1866
|
+
const told = nameTold(project, input, harness);
|
|
1867
|
+
const name = told.data.given ? input.agent : (told.data.name ?? told.data.suggested);
|
|
1868
|
+
const drafts = openDraftLines(project, name ?? null);
|
|
1869
|
+
return drafts.length === 0 ? told : { ...told, text: [told.text, ...drafts].join('\n') };
|
|
1870
|
+
});
|
|
1871
|
+
},
|
|
1872
|
+
};
|
|
1873
|
+
// A board draft a restart may have cut off (p3-company run 2): Otea kept it, and a new session is
|
|
1874
|
+
// pointed to it, the command to carry it on with when the name it takes is the one holding it.
|
|
1875
|
+
function openDraftLines(project, name) {
|
|
1876
|
+
return openDraftsOf(project, systemClock()).map(({ item, name: board, holder }) => {
|
|
1877
|
+
const held = holder === null ? '' : `, held by ${holder}`;
|
|
1878
|
+
if (holder !== null && holder !== name)
|
|
1879
|
+
return `A board draft is open on ${item}, "${board}"${held}.`;
|
|
1880
|
+
return `A board draft is open on ${item}, "${board}"${held}: Otea kept it as it was. If you were drafting it, carry it on: otea show ${item} --as ${name ?? '<name>'} says how to hand it in.`;
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
// The items a name handed back still holds from its last session.
|
|
1884
|
+
function heldLine(name, ids) {
|
|
1885
|
+
const one = ids.length === 1;
|
|
1886
|
+
const release = one ? `otea release ${ids[0]}` : 'otea release <id>';
|
|
1887
|
+
return `${name} holds ${ids.join(', ')} from its last session: carry ${one ? 'it' : 'them'} on (otea next) or let go of ${one ? 'it' : 'them'} (${release}).`;
|
|
1888
|
+
}
|
|
1889
|
+
// What whoami tells the session about its name.
|
|
1890
|
+
function nameTold(project, input, harness) {
|
|
1891
|
+
const { cwd } = input;
|
|
1892
|
+
// Over MCP this server asks: a name it hears is this session's own.
|
|
1893
|
+
const session = input.channel === 'mcp' ? process.pid : undefined;
|
|
1894
|
+
if (input.agent !== undefined) {
|
|
1895
|
+
assertAgentName(input.agent);
|
|
1896
|
+
const advice = nameFor(project.db, { folder: cwd, harness, session });
|
|
1897
|
+
return {
|
|
1898
|
+
data: { ...advice, name: input.agent, given: true },
|
|
1899
|
+
text: `You are ${input.agent}: put it on every command (--as ${input.agent}; MCP tools: as).`,
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
// The name it is told is handed to this session: one asking at the same time gets another.
|
|
1903
|
+
const advice = offerName(project.db, { folder: cwd, harness, session });
|
|
1904
|
+
const others = advice.others.length > 0 ? advice.others : [];
|
|
1905
|
+
if (advice.name !== null) {
|
|
1906
|
+
const known = findAgent(project.db, advice.name);
|
|
1907
|
+
const when = known ? ` (last seen ${timeText(known.lastSeen)})` : '';
|
|
1908
|
+
return {
|
|
1909
|
+
data: { ...advice, reuse: true },
|
|
1910
|
+
text: [
|
|
1911
|
+
`Reuse your name: ${advice.name}${when}, the agent that worked here before ${throughText(advice)}, with no session working under it now. Put it on every command: --as ${advice.name} (MCP tools: as).`,
|
|
1912
|
+
...(advice.lately
|
|
1913
|
+
? [
|
|
1914
|
+
`${advice.name} acted moments ago: keep the name unless you know another terminal of yours works as ${advice.name} now; then take a new name of your own. Decide it yourself: never ask the person which name to use.`,
|
|
1915
|
+
]
|
|
1916
|
+
: []),
|
|
1917
|
+
// What its last session left held is this one's to carry on (P7-R3-11).
|
|
1918
|
+
...(advice.holding.length > 0 ? [heldLine(advice.name, advice.holding)] : []),
|
|
1919
|
+
...(others.length > 0
|
|
1920
|
+
? [`Others that worked here and are not connected now: ${others.join(', ')}.`]
|
|
1921
|
+
: []),
|
|
1922
|
+
].join('\n'),
|
|
1923
|
+
};
|
|
1924
|
+
}
|
|
1925
|
+
if (advice.suggested !== null) {
|
|
1926
|
+
const name = advice.suggested;
|
|
1927
|
+
return {
|
|
1928
|
+
data: { ...advice, reuse: false },
|
|
1929
|
+
text: `Take the name ${name}: your earlier name here is taken by a session working now, and ${name} is handed to this session only. Put it on every command: --as ${name} (MCP tools: as).`,
|
|
1930
|
+
};
|
|
1931
|
+
}
|
|
1932
|
+
const taken = advice.working.length > 0
|
|
1933
|
+
? `, not one of the agents connected now (${advice.working.join(', ')})`
|
|
1934
|
+
: '';
|
|
1935
|
+
return {
|
|
1936
|
+
data: { ...advice, reuse: false },
|
|
1937
|
+
text: `No earlier session of yours is known here: pick a new short name of your own (lowercase letters, digits and dashes)${taken}, and put it on every command (--as <name>; MCP tools: as).`,
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
// The profile an agent runs as: declared with --model and --effort (--harness too for a
|
|
1941
|
+
// command-line agent the first time; an MCP client names its own), or shown without them.
|
|
1942
|
+
const profileCommandSpec = {
|
|
1943
|
+
name: 'profile',
|
|
1944
|
+
summary: 'Declare the profile you run as: --model the exact model id and --effort the effort, as your harness names them (such as claude-opus-5-5 and high). Declare what this session tells you (your instructions, or what the person says); never open config files outside the project for it. Otherwise declare unknown. Never guess. --harness the tool you run in, the first time on the command line (an MCP client names its own). Declare it at the start of each session and whenever the model or effort changes; it is kept on everything you do. Without options, shows it',
|
|
1945
|
+
args: [],
|
|
1946
|
+
options: {
|
|
1947
|
+
model: { placeholder: 'id' },
|
|
1948
|
+
effort: { placeholder: 'level' },
|
|
1949
|
+
harness: { placeholder: 'name' },
|
|
1950
|
+
},
|
|
1951
|
+
execute: (input) => {
|
|
1952
|
+
const { actor, channel, harness, option } = input;
|
|
1953
|
+
const model = option('model');
|
|
1954
|
+
const effort = option('effort');
|
|
1955
|
+
const given = option('harness');
|
|
1956
|
+
return withAgent(input, (project) => {
|
|
1957
|
+
const known = findProfile(project.db, actor.name);
|
|
1958
|
+
if (model === undefined && effort === undefined && given === undefined) {
|
|
1959
|
+
if (!known) {
|
|
1960
|
+
const text = `${actor.name} has no profile yet: declare it with ${profileCommand(actor.name, channel)}`;
|
|
1961
|
+
return { data: { agent: actor.name, profile: null, confirmed: false }, text };
|
|
1962
|
+
}
|
|
1963
|
+
const view = profileView(known.profile);
|
|
1964
|
+
return {
|
|
1965
|
+
data: { agent: actor.name, profile: view, confirmed: known.confirmed },
|
|
1966
|
+
text: profileText(actor.name, view, known.confirmed, channel),
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
const declaredModel = model ?? known?.profile.model;
|
|
1970
|
+
const declaredEffort = effort ?? known?.profile.effort;
|
|
1971
|
+
if (declaredModel === undefined || declaredEffort === undefined) {
|
|
1972
|
+
throw new UsageError('Declare both --model <id> and --effort <level> the first time');
|
|
1973
|
+
}
|
|
1974
|
+
const declared = declareProfile(project.db, {
|
|
1975
|
+
agent: actor.name,
|
|
1976
|
+
channel,
|
|
1977
|
+
harness,
|
|
1978
|
+
model: declaredModel,
|
|
1979
|
+
effort: declaredEffort,
|
|
1980
|
+
...(given === undefined ? {} : { given }),
|
|
1981
|
+
});
|
|
1982
|
+
return { data: declared, text: profileText(actor.name, declared.profile, true, channel) };
|
|
1983
|
+
});
|
|
1984
|
+
},
|
|
1985
|
+
};
|
|
1986
|
+
function profileText(agent, profile, confirmed, channel) {
|
|
1987
|
+
const line = `${agent} runs as ${profileLine(profile)} on ${profile.harness} (family ${profile.family})`;
|
|
1988
|
+
return confirmed
|
|
1989
|
+
? line
|
|
1990
|
+
: `${line}; not confirmed in this session: declare it again with ${profileCommand(agent, channel)}`;
|
|
1991
|
+
}
|
|
1992
|
+
const heartbeat = {
|
|
1993
|
+
name: 'heartbeat',
|
|
1994
|
+
summary: 'Extend the lease you hold on an item (default --ttl 15m from now)',
|
|
1995
|
+
args: ['id'],
|
|
1996
|
+
options: TTL,
|
|
1997
|
+
execute: (input) => {
|
|
1998
|
+
const [id = ''] = input.args;
|
|
1999
|
+
const { actor, option } = input;
|
|
2000
|
+
const ttl = ttlFrom(option('ttl'));
|
|
2001
|
+
const lease = { id, actor, ...(ttl === undefined ? {} : { ttlMs: ttl }) };
|
|
2002
|
+
return withAgent(input, (project) => withNotes(project, id, itemResult(project, heartbeatItem(project, lease))));
|
|
2003
|
+
},
|
|
2004
|
+
};
|
|
2005
|
+
// What an agent's answer adds while notes from the person wait for its answer: their block after
|
|
2006
|
+
// the text, and the notes and that block in the data (`notes`, `text`).
|
|
2007
|
+
function withNotes(project, id, output) {
|
|
2008
|
+
const waiting = agentNotes(project, id);
|
|
2009
|
+
if (!waiting)
|
|
2010
|
+
return output;
|
|
2011
|
+
return {
|
|
2012
|
+
data: { ...output.data, notes: waiting.notes, text: waiting.text },
|
|
2013
|
+
text: `${output.text}\n\n${waiting.text}`,
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
// What a note's number is, and what a send-back reason is instead (P2S-R3-5): an agent tried to
|
|
2017
|
+
// answer a send-back reason with reply, as if it were a note.
|
|
2018
|
+
const SEND_BACK_IS_NO_NOTE = 'A send-back reason is not a note: address it in your work, then say what you did in the note of your next handoff (otea handoff <id> --note "...")';
|
|
2019
|
+
// In every MCP agent's tool list: kept short (token-budget.test.ts).
|
|
2020
|
+
const NOTE_ABOUT = "the number of the person's note you answer. A send-back reason is not a note: answer it in your next handoff's note";
|
|
2021
|
+
const reply = {
|
|
2022
|
+
name: 'reply',
|
|
2023
|
+
summary: 'Answer a note the person left while you do a step (--note, its number; next, show and heartbeat print them): a short answer; the step, round and lease stay as they are. A handoff waits until every note of the round is answered',
|
|
2024
|
+
args: ['id', 'answer'],
|
|
2025
|
+
options: { note: { required: true, placeholder: 'n', about: NOTE_ABOUT } },
|
|
2026
|
+
execute: (input) => {
|
|
2027
|
+
const [id = '', answer = ''] = input.args;
|
|
2028
|
+
const given = input.required('note');
|
|
2029
|
+
if (!/^[1-9]\d*$/.test(given))
|
|
2030
|
+
throw new UsageError(`--note must be the number of one of the person's notes (next, show and heartbeat print each with its number). ${SEND_BACK_IS_NO_NOTE}`);
|
|
2031
|
+
const { actor, channel } = input;
|
|
2032
|
+
return withAgent(input, (project) => {
|
|
2033
|
+
const replied = replyNote(project, { id, note: Number(given), text: answer, actor, channel });
|
|
2034
|
+
const next = keepWaitingLine(actor.name, channel, { idle: false });
|
|
2035
|
+
return { data: { ...replied, next }, text: [replied.text, next].join('\n') };
|
|
2036
|
+
});
|
|
2037
|
+
},
|
|
2038
|
+
};
|
|
2039
|
+
// The zone of an image a note is on, cut out for an agent that asks for it: the note says the zone
|
|
2040
|
+
// in percent; this gives its pixels, and for a PNG the pixels themselves in a file.
|
|
2041
|
+
const crop = {
|
|
2042
|
+
name: 'crop',
|
|
2043
|
+
summary: 'Cut out the zone of an image a note of the person is on (--note, its number; a note on a point gives a fifth of the image around it): a PNG is written to a file (--out, or the temp folder) to read as an image; any other image gets the zone in its pixels',
|
|
2044
|
+
args: ['id'],
|
|
2045
|
+
options: { note: { required: true, placeholder: 'n' }, out: { placeholder: 'file.png' } },
|
|
2046
|
+
execute: (input) => {
|
|
2047
|
+
const [id = ''] = input.args;
|
|
2048
|
+
const given = input.required('note');
|
|
2049
|
+
if (!/^[1-9]\d*$/.test(given))
|
|
2050
|
+
throw new UsageError('--note must be the number of a note');
|
|
2051
|
+
const out = input.option('out');
|
|
2052
|
+
return withAgent(input, (project) => {
|
|
2053
|
+
const cut = cropNote(project, {
|
|
2054
|
+
id,
|
|
2055
|
+
note: Number(given),
|
|
2056
|
+
...(out === undefined ? {} : { out }),
|
|
2057
|
+
});
|
|
2058
|
+
return { data: cut, text: cut.text };
|
|
2059
|
+
});
|
|
2060
|
+
},
|
|
2061
|
+
};
|
|
2062
|
+
// That a Done item's branch is in: Done takes no other change, so this is how its page and rows
|
|
2063
|
+
// learn the work was merged.
|
|
2064
|
+
const merged = {
|
|
2065
|
+
name: 'merged',
|
|
2066
|
+
summary: "Record that a Done item's branch was merged (--pr, its pull request; --commit, the merge commit), so its page and rows stop saying it waits to be merged",
|
|
2067
|
+
args: ['id'],
|
|
2068
|
+
options: { pr: { placeholder: 'url' }, commit: { placeholder: 'sha' } },
|
|
2069
|
+
execute: (input) => {
|
|
2070
|
+
const [id = ''] = input.args;
|
|
2071
|
+
const { actor, channel } = input;
|
|
2072
|
+
const pr = input.option('pr');
|
|
2073
|
+
const commit = input.option('commit');
|
|
2074
|
+
// With a PR, gh says whether it really merged and which branch: a wrong mark is refused. When
|
|
2075
|
+
// gh cannot tell, the mark is kept as given, with a note.
|
|
2076
|
+
const forge = pr === undefined ? undefined : prState(input.cwd, pr, input.gh);
|
|
2077
|
+
if (pr !== undefined && forge === undefined)
|
|
2078
|
+
input.warn(`could not check PR ${pr} with gh; recorded as merged as you said`);
|
|
2079
|
+
return withAgent(input, (project) => {
|
|
2080
|
+
const done = markMerged(project, {
|
|
2081
|
+
id,
|
|
2082
|
+
actor,
|
|
2083
|
+
channel,
|
|
2084
|
+
...(pr === undefined ? {} : { pr }),
|
|
2085
|
+
...(commit === undefined ? {} : { commit }),
|
|
2086
|
+
...(forge === undefined ? {} : { forge }),
|
|
2087
|
+
});
|
|
2088
|
+
const said = [done.pr, done.commit].filter(Boolean).join(', ');
|
|
2089
|
+
return { data: done, text: `Marked ${id} merged${said ? ` (${said})` : ''}.` };
|
|
2090
|
+
});
|
|
2091
|
+
},
|
|
2092
|
+
};
|
|
2093
|
+
const reopen = {
|
|
2094
|
+
name: 'reopen',
|
|
2095
|
+
summary: 'Take a Done, unmerged item back to the step that pushes its branch (its PR conflicts) and through review again',
|
|
2096
|
+
args: ['id'],
|
|
2097
|
+
options: { reason: { placeholder: 'why its branch must change' } },
|
|
2098
|
+
execute: (input) => {
|
|
2099
|
+
const [id = ''] = input.args;
|
|
2100
|
+
const { actor, channel } = input;
|
|
2101
|
+
const reason = input.option('reason') ?? '';
|
|
2102
|
+
return withAgent(input, (project) => {
|
|
2103
|
+
const { item, text } = reopenItem(project, { id, actor, channel, reason });
|
|
2104
|
+
// As any move answers: the item with its fields by name, and what to do now.
|
|
2105
|
+
return { data: { item: itemData(project, item), text }, text };
|
|
2106
|
+
});
|
|
2107
|
+
},
|
|
2108
|
+
};
|
|
2109
|
+
// The proof a tick names: an evidence entry (--evidence 3), a log line (--log build.log:212) or a
|
|
2110
|
+
// test of an attached report (--test "suite › name"); at most one.
|
|
2111
|
+
function proofSource(option) {
|
|
2112
|
+
const evidence = option('evidence');
|
|
2113
|
+
const log = option('log');
|
|
2114
|
+
const test = option('test');
|
|
2115
|
+
const given = [evidence, log, test].filter((value) => value !== undefined);
|
|
2116
|
+
if (given.length > 1)
|
|
2117
|
+
throw new OteaError('invalid_fields', 'Prove a point with one of --evidence, --log or --test');
|
|
2118
|
+
if (evidence !== undefined) {
|
|
2119
|
+
const n = Number(evidence.replace(/^#/, ''));
|
|
2120
|
+
if (!Number.isInteger(n) || n < 1)
|
|
2121
|
+
throw new OteaError('invalid_fields', '--evidence takes the number of an attached file, such as 3');
|
|
2122
|
+
return { evidence: n };
|
|
2123
|
+
}
|
|
2124
|
+
if (log !== undefined) {
|
|
2125
|
+
const at = /^(.+):(\d+)$/.exec(log.trim());
|
|
2126
|
+
if (!at?.[1] || !at[2])
|
|
2127
|
+
throw new OteaError('invalid_fields', "--log takes the log's file name and a line, such as build.log:212");
|
|
2128
|
+
return { log: { file: at[1], line: Number(at[2]) } };
|
|
2129
|
+
}
|
|
2130
|
+
if (test !== undefined)
|
|
2131
|
+
return { test };
|
|
2132
|
+
return {};
|
|
2133
|
+
}
|
|
2134
|
+
// Ticks a checklist point, with what proves it: Otea checks the log line exists and the test passes.
|
|
2135
|
+
const tick = {
|
|
2136
|
+
name: 'tick',
|
|
2137
|
+
summary: 'Tick a checklist point with its proof: --log file:line, --test "name" (passing, in an attached report) or --evidence n; --part names the checklist',
|
|
2138
|
+
args: ['id', 'point'],
|
|
2139
|
+
options: {
|
|
2140
|
+
part: { placeholder: 'checklist' },
|
|
2141
|
+
log: { placeholder: 'file:line' },
|
|
2142
|
+
test: { placeholder: 'name' },
|
|
2143
|
+
evidence: { placeholder: 'n' },
|
|
2144
|
+
},
|
|
2145
|
+
execute: (input) => {
|
|
2146
|
+
const [id = '', point = ''] = input.args;
|
|
2147
|
+
const { actor, channel, option } = input;
|
|
2148
|
+
const part = option('part');
|
|
2149
|
+
const source = proofSource(option);
|
|
2150
|
+
return withAgent(input, (project) => {
|
|
2151
|
+
const done = tickPoint(project, {
|
|
2152
|
+
id,
|
|
2153
|
+
point,
|
|
2154
|
+
source,
|
|
2155
|
+
actor,
|
|
2156
|
+
channel,
|
|
2157
|
+
...(part === undefined ? {} : { part }),
|
|
2158
|
+
});
|
|
2159
|
+
return withNotes(project, id, { data: done, text: done.text });
|
|
2160
|
+
});
|
|
2161
|
+
},
|
|
2162
|
+
};
|
|
2163
|
+
// An agent's question to the person: the turn is theirs until they answer, nothing else moves.
|
|
2164
|
+
const ask = {
|
|
2165
|
+
name: 'ask',
|
|
2166
|
+
summary: 'Ask the person a question while you do a step: the turn is theirs until they answer (the step, round and lease stay); wait wakes on the answer, and next and show give it',
|
|
2167
|
+
args: ['id', 'question'],
|
|
2168
|
+
options: {},
|
|
2169
|
+
execute: (input) => {
|
|
2170
|
+
const [id = '', question = ''] = input.args;
|
|
2171
|
+
const { actor, channel } = input;
|
|
2172
|
+
return withAgent(input, (project) => {
|
|
2173
|
+
const asked = askQuestion(project, { id, text: question, actor, channel });
|
|
2174
|
+
return { data: asked, text: asked.text };
|
|
2175
|
+
});
|
|
2176
|
+
},
|
|
2177
|
+
};
|
|
2178
|
+
// The answer the person gave in the chat to the agent's question, put on the question as theirs.
|
|
2179
|
+
const answer = {
|
|
2180
|
+
name: 'answer',
|
|
2181
|
+
summary: "Note on your question (otea ask) the person's answer given in the chat, in their words: it counts as theirs",
|
|
2182
|
+
args: ['id', 'answer'],
|
|
2183
|
+
options: {},
|
|
2184
|
+
execute: (input) => {
|
|
2185
|
+
const [id = '', text = ''] = input.args;
|
|
2186
|
+
const { actor, channel } = input;
|
|
2187
|
+
return withAgent(input, (project) => {
|
|
2188
|
+
const noted = noteChatAnswer(project, { id, text, actor, channel });
|
|
2189
|
+
// It ends with the exact wait: after a chat answer an agent said it waited, running no
|
|
2190
|
+
// wait (P3C-R3-9).
|
|
2191
|
+
const next = keepWaitingLine(actor.name, channel, { idle: false });
|
|
2192
|
+
return { data: { ...noted, next }, text: [noted.text, next].join('\n') };
|
|
2193
|
+
});
|
|
2194
|
+
},
|
|
2195
|
+
};
|
|
2196
|
+
const release = {
|
|
2197
|
+
name: 'release',
|
|
2198
|
+
summary: 'Drop the lease you hold on an item; moving it off the agent turn releases it too. --later sets it aside for every agent (next and wait skip it), held or let go of, until it moves, is claimed or the person takes it up',
|
|
2199
|
+
args: ['id'],
|
|
2200
|
+
options: { later: { flag: true }, quote: { placeholder: "the person's words" } },
|
|
2201
|
+
execute: (input) => {
|
|
2202
|
+
const [id = ''] = input.args;
|
|
2203
|
+
const { actor } = input;
|
|
2204
|
+
const later = input.flag('later');
|
|
2205
|
+
const quote = input.option('quote');
|
|
2206
|
+
if (quote !== undefined && !later)
|
|
2207
|
+
throw new UsageError('--quote goes with --later');
|
|
2208
|
+
return withAgent(input, (project) => {
|
|
2209
|
+
const item = releaseItem(project, {
|
|
2210
|
+
id,
|
|
2211
|
+
actor,
|
|
2212
|
+
later,
|
|
2213
|
+
...(quote === undefined ? {} : { quote }),
|
|
2214
|
+
});
|
|
2215
|
+
const released = itemResult(project, item);
|
|
2216
|
+
if (!later)
|
|
2217
|
+
return released;
|
|
2218
|
+
const aside = `Set ${item.id} aside for every agent: otea next and otea wait --unclaimed leave it out until it moves, an agent claims it (otea claim ${item.id}), or the person takes it up again.`;
|
|
2219
|
+
return { ...released, text: `${released.text}\n${aside}` };
|
|
2220
|
+
});
|
|
2221
|
+
},
|
|
2222
|
+
};
|
|
2223
|
+
const validate = {
|
|
2224
|
+
name: 'validate',
|
|
2225
|
+
summary: 'Check boards, collections and items without fixing anything; fails only on errors, not warnings',
|
|
2226
|
+
args: [],
|
|
2227
|
+
options: {},
|
|
2228
|
+
execute: ({ cwd }) => {
|
|
2229
|
+
const report = withProject(cwd, (project) => validateProject(project));
|
|
2230
|
+
const failure = report.errors > 0 ? 'validation_failed' : undefined;
|
|
2231
|
+
return { data: report, text: formatReport(report), ...(failure ? { failure } : {}) };
|
|
2232
|
+
},
|
|
2233
|
+
};
|
|
2234
|
+
const update = {
|
|
2235
|
+
name: 'update',
|
|
2236
|
+
summary: 'Change fields of an open item; a blank value clears a field that is not create-required',
|
|
2237
|
+
details: FIELD_DETAILS,
|
|
2238
|
+
args: ['id'],
|
|
2239
|
+
options: {
|
|
2240
|
+
title: {},
|
|
2241
|
+
description: {},
|
|
2242
|
+
field: { multiple: true, placeholder: 'key=value' },
|
|
2243
|
+
'field-file': FIELD_FILE,
|
|
2244
|
+
},
|
|
2245
|
+
execute: async (input) => {
|
|
2246
|
+
const [id = ''] = input.args;
|
|
2247
|
+
const title = input.option('title');
|
|
2248
|
+
const fields = await fieldsFrom(input);
|
|
2249
|
+
if (title === undefined && Object.keys(fields).length === 0) {
|
|
2250
|
+
throw new UsageError('Nothing to update; pass --title, --description, --field or --field-file');
|
|
2251
|
+
}
|
|
2252
|
+
const { actor } = input;
|
|
2253
|
+
const changes = { id, fields, actor, ...(title === undefined ? {} : { title }) };
|
|
2254
|
+
return withAgent(input, (project) => {
|
|
2255
|
+
refuseAttachedParts(project, id, Object.keys(fields), input);
|
|
2256
|
+
return itemResult(project, updateItem(project, changes));
|
|
2257
|
+
});
|
|
2258
|
+
},
|
|
2259
|
+
};
|
|
2260
|
+
// A part the agent attaches as a file, named as a field to fill (P3C-R3-5): refused with the exact
|
|
2261
|
+
// otea attach command, the file the agent gave with --field-file in it.
|
|
2262
|
+
function refuseAttachedParts(project, id, keys, input) {
|
|
2263
|
+
const board = liveBoardOf(project, getItem(project, id).collection);
|
|
2264
|
+
if (!board)
|
|
2265
|
+
return;
|
|
2266
|
+
const files = new Map(input.options('field-file').map((pair) => fieldPair(pair, '', 'field-file', '<file>')));
|
|
2267
|
+
for (const key of keys) {
|
|
2268
|
+
const part = partByName(board.def, key);
|
|
2269
|
+
if (!part || !isEvidence(part))
|
|
2270
|
+
continue;
|
|
2271
|
+
const file = files.get(key);
|
|
2272
|
+
throw attachedPart(part, id, file === undefined || file === '-' ? undefined : file);
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
// A diagram Otea cannot draw (outside its Mermaid flowchart subset, core/diagram.ts) is kept, and
|
|
2276
|
+
// the person sees its source: the agent is told, with the subset, so it can attach one that draws.
|
|
2277
|
+
function diagramNote(path, { filename }) {
|
|
2278
|
+
let source;
|
|
2279
|
+
try {
|
|
2280
|
+
source = readFileSync(path, 'utf8');
|
|
2281
|
+
}
|
|
2282
|
+
catch {
|
|
2283
|
+
return '';
|
|
2284
|
+
}
|
|
2285
|
+
const parsed = parseDiagram(source);
|
|
2286
|
+
if (parsed.ok)
|
|
2287
|
+
return '';
|
|
2288
|
+
return `\nOtea cannot draw ${filename} (line ${parsed.line}: ${parsed.message}): the person sees its source. It draws a Mermaid flowchart: flowchart or graph LR|TD|RL|BT first, then nodes id[label], id(label) or id{label} joined by -->, ---, -.-> or ==> (with |label|); attach a version that keeps to it.`;
|
|
2289
|
+
}
|
|
2290
|
+
const attach = {
|
|
2291
|
+
name: 'attach',
|
|
2292
|
+
summary: `Attach a file to an open item as evidence (at most ${MAX_EVIDENCE_MB} MB), into an evidence module of its type that accepts it; --module picks one when several do, --role before and after fill a compare; --point ticks that checklist point with it`,
|
|
2293
|
+
args: ['id', 'file'],
|
|
2294
|
+
options: {
|
|
2295
|
+
role: { choices: EVIDENCE_ROLES },
|
|
2296
|
+
module: { placeholder: 'id' },
|
|
2297
|
+
caption: { placeholder: 'text' },
|
|
2298
|
+
point: { placeholder: 'checklist point' },
|
|
2299
|
+
},
|
|
2300
|
+
execute: (input) => {
|
|
2301
|
+
const [id = '', file = ''] = input.args;
|
|
2302
|
+
const { cwd, actor, channel, option } = input;
|
|
2303
|
+
const role = option('role');
|
|
2304
|
+
const module = option('module');
|
|
2305
|
+
const caption = option('caption');
|
|
2306
|
+
const evidenceInput = {
|
|
2307
|
+
id,
|
|
2308
|
+
path: resolve(cwd, file),
|
|
2309
|
+
actor,
|
|
2310
|
+
channel,
|
|
2311
|
+
...(role === undefined ? {} : { role }),
|
|
2312
|
+
...(module === undefined ? {} : { module }),
|
|
2313
|
+
...(caption === undefined ? {} : { caption }),
|
|
2314
|
+
};
|
|
2315
|
+
return withAgent(input, (project) => {
|
|
2316
|
+
const evidence = attachEvidence(project, evidenceInput);
|
|
2317
|
+
// On a board, the evidence goes by its name, never its hidden id.
|
|
2318
|
+
const board = liveBoardOf(project, getItem(project, evidence.itemId).collection);
|
|
2319
|
+
const name = evidence.module === null ? undefined : board?.def.parts[evidence.module]?.name;
|
|
2320
|
+
const shown = name === undefined ? evidence : { ...evidence, module: name };
|
|
2321
|
+
const same = evidence.duplicate
|
|
2322
|
+
? `\n${evidence.itemId} already has this file as #${evidence.id}; nothing added.`
|
|
2323
|
+
: '';
|
|
2324
|
+
const data = name === undefined ? evidence : { ...evidence, moduleName: name };
|
|
2325
|
+
const point = option('point');
|
|
2326
|
+
const ticked = point === undefined
|
|
2327
|
+
? undefined
|
|
2328
|
+
: tickPoint(project, { id, point, source: { evidence: evidence.id }, actor, channel });
|
|
2329
|
+
const drawn = evidence.kind === 'diagram' ? diagramNote(evidenceInput.path, evidence) : '';
|
|
2330
|
+
const diff = evidence.diffNote === undefined ? '' : `\n${evidence.diffNote}`;
|
|
2331
|
+
const text = `${formatEvidence(shown)}${same}${diff}${drawn}${ticked ? `\n${ticked.text}` : ''}`;
|
|
2332
|
+
return withNotes(project, evidence.itemId, {
|
|
2333
|
+
// --json and MCP read the diagram's refusal to be drawn too.
|
|
2334
|
+
data: {
|
|
2335
|
+
...data,
|
|
2336
|
+
...(ticked ? { ticked } : {}),
|
|
2337
|
+
...(drawn ? { cannotDraw: drawn.trim() } : {}),
|
|
2338
|
+
},
|
|
2339
|
+
text,
|
|
2340
|
+
});
|
|
2341
|
+
});
|
|
2342
|
+
},
|
|
2343
|
+
};
|
|
2344
|
+
// A file attached by mistake, taken back before the item moves on (AGENTS3-4).
|
|
2345
|
+
const detach = {
|
|
2346
|
+
name: 'detach',
|
|
2347
|
+
summary: 'Take back a file you attached by mistake (its number in show), before the item moves on',
|
|
2348
|
+
args: ['id', 'evidence'],
|
|
2349
|
+
options: {},
|
|
2350
|
+
execute: (input) => {
|
|
2351
|
+
const [id = '', number = ''] = input.args;
|
|
2352
|
+
const evidence = Number(number.replace(/^#/, ''));
|
|
2353
|
+
if (!Number.isInteger(evidence) || evidence < 1) {
|
|
2354
|
+
throw new UsageError(`Not a file number: ${number}. Pass the number show gives it, such as 3`);
|
|
2355
|
+
}
|
|
2356
|
+
const { actor, channel } = input;
|
|
2357
|
+
return withAgent(input, (project) => {
|
|
2358
|
+
const entry = detachEvidence(project, { id, evidence, actor, channel });
|
|
2359
|
+
const text = `Detached #${entry.id} ${entry.filename} from ${entry.itemId}.`;
|
|
2360
|
+
return { data: { ...entry, detached: true }, text };
|
|
2361
|
+
});
|
|
2362
|
+
},
|
|
2363
|
+
};
|
|
2364
|
+
// The project the command runs in, when there is one; a local one is remembered for the server to
|
|
2365
|
+
// serve (a registered one it finds in the registry). Its database is closed again: the server
|
|
2366
|
+
// opens its own.
|
|
2367
|
+
function projectHere(cwd) {
|
|
2368
|
+
let project;
|
|
2369
|
+
try {
|
|
2370
|
+
project = openProject(cwd);
|
|
2371
|
+
}
|
|
2372
|
+
catch (error) {
|
|
2373
|
+
if (error instanceof OteaError && error.details?.kind === 'no_project')
|
|
2374
|
+
return undefined;
|
|
2375
|
+
throw error;
|
|
2376
|
+
}
|
|
2377
|
+
try {
|
|
2378
|
+
const { id } = project.identity;
|
|
2379
|
+
if (project.storage === 'local') {
|
|
2380
|
+
withMachine(process.env, (machine) => rememberLocalProject(machine, { id, root: project.root }));
|
|
2381
|
+
}
|
|
2382
|
+
return { id };
|
|
2383
|
+
}
|
|
2384
|
+
finally {
|
|
2385
|
+
project.db.close();
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
// The page to open, and the sign-in link that lands on it.
|
|
2389
|
+
function pages(url, token, here) {
|
|
2390
|
+
const next = here === undefined ? '/' : `/p/${here.id}/`;
|
|
2391
|
+
return {
|
|
2392
|
+
url: `${url}${next}`,
|
|
2393
|
+
signInUrl: `${url}/auth?token=${encodeURIComponent(token)}&next=${encodeURIComponent(next)}`,
|
|
2394
|
+
};
|
|
2395
|
+
}
|
|
2396
|
+
function alive(pid) {
|
|
2397
|
+
try {
|
|
2398
|
+
process.kill(pid, 0);
|
|
2399
|
+
return true;
|
|
2400
|
+
}
|
|
2401
|
+
catch (error) {
|
|
2402
|
+
return error.code === 'EPERM';
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
// This computer's otea serve, when one runs and answers with this Otea home's key.
|
|
2406
|
+
async function runningServer(home) {
|
|
2407
|
+
const info = readServeFile(home);
|
|
2408
|
+
const token = readUiToken(home);
|
|
2409
|
+
if (!info || !token || !alive(info.pid))
|
|
2410
|
+
return undefined;
|
|
2411
|
+
const url = `http://127.0.0.1:${info.port}`;
|
|
2412
|
+
const probe = await probeSignIn(`${url}/auth?token=${encodeURIComponent(token)}`);
|
|
2413
|
+
return probe === 'ours' ? { url, token } : undefined;
|
|
2414
|
+
}
|
|
2415
|
+
// How often the server looks for projects registered (or served) since it started, so each one's
|
|
2416
|
+
// notices go out without waiting for a page to open it.
|
|
2417
|
+
const SYNC_EVERY_MS = 10_000;
|
|
2418
|
+
async function serveUntil(signal, cwd, options) {
|
|
2419
|
+
const { port, lan, tailscale, probe, warn, gitHook } = options;
|
|
2420
|
+
const here = projectHere(cwd);
|
|
2421
|
+
const home = oteaHome();
|
|
2422
|
+
// One server per Otea home: a second otea serve points at the one running.
|
|
2423
|
+
const running = await runningServer(home);
|
|
2424
|
+
if (running)
|
|
2425
|
+
return { ...pages(running.url, running.token, here), attached: true };
|
|
2426
|
+
const token = ensureUiToken(home, { warn });
|
|
2427
|
+
const machine = openMachine();
|
|
2428
|
+
const source = machineProjects(process.env, machine);
|
|
2429
|
+
// The web server's modules load only here, so every other command starts without them.
|
|
2430
|
+
const [{ createServer }, { listen, localNetwork }, { pairingUrl }] = await Promise.all([
|
|
2431
|
+
import('../server/server.js'),
|
|
2432
|
+
import('../server/listen.js'),
|
|
2433
|
+
import('../server/pairing.js'),
|
|
2434
|
+
]);
|
|
2435
|
+
try {
|
|
2436
|
+
const server = createServer(source, {
|
|
2437
|
+
token,
|
|
2438
|
+
machine,
|
|
2439
|
+
computer: hostname(),
|
|
2440
|
+
tailscale,
|
|
2441
|
+
probe,
|
|
2442
|
+
// The server's own key pair for Web Push, kept beside the UI token.
|
|
2443
|
+
// Each push's outcome in this output (the device id, never its endpoint), so a phone that
|
|
2444
|
+
// never hears one says why.
|
|
2445
|
+
notify: {
|
|
2446
|
+
keys: ensureVapidKeys(home, { warn }),
|
|
2447
|
+
log: (line) => process.stdout.write(`${line}\n`),
|
|
2448
|
+
},
|
|
2449
|
+
network: localNetwork,
|
|
2450
|
+
gitHook,
|
|
2451
|
+
});
|
|
2452
|
+
const listening = await listen(server, port);
|
|
2453
|
+
// Open to the local network when it was left open (Settings › Phone, otea phone lan --open),
|
|
2454
|
+
// or for this run only with --lan; if it cannot open, Otea still serves this computer.
|
|
2455
|
+
if (lan || lanOpen(machine)) {
|
|
2456
|
+
await server.lan.open().catch((error) => {
|
|
2457
|
+
warn(`Could not open Otea to the local network: ${error.message}`);
|
|
2458
|
+
});
|
|
2459
|
+
}
|
|
2460
|
+
writeServeFile(home, { port: listening.port, pid: process.pid });
|
|
2461
|
+
const sync = setInterval(() => server.sync(), SYNC_EVERY_MS);
|
|
2462
|
+
sync.unref();
|
|
2463
|
+
const stop = () => {
|
|
2464
|
+
clearInterval(sync);
|
|
2465
|
+
removeServeFile(home, process.pid);
|
|
2466
|
+
return listening.close().finally(() => machine.close());
|
|
2467
|
+
};
|
|
2468
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
2469
|
+
const served = pages(listening.url, token, here);
|
|
2470
|
+
const door = server.phone.chosen();
|
|
2471
|
+
if (!door)
|
|
2472
|
+
return served;
|
|
2473
|
+
const urls = door.urls(listening.port);
|
|
2474
|
+
const code = server.phone.codes.issue();
|
|
2475
|
+
const first = urls[0];
|
|
2476
|
+
// The .local name comes first when it resolves; the same link by IP comes along.
|
|
2477
|
+
const byIp = urls.find((url) => !new URL(url).hostname.endsWith('.local'));
|
|
2478
|
+
const byAddress = door.kind === 'lan' && first !== byIp && byIp !== undefined
|
|
2479
|
+
? { byAddress: pairingUrl(byIp, code) }
|
|
2480
|
+
: {};
|
|
2481
|
+
return {
|
|
2482
|
+
...served,
|
|
2483
|
+
phone: {
|
|
2484
|
+
transport: door.kind,
|
|
2485
|
+
urls,
|
|
2486
|
+
pairingUrl: first === undefined ? undefined : pairingUrl(first, code),
|
|
2487
|
+
...byAddress,
|
|
2488
|
+
code: first === undefined ? undefined : formatCode(code.code),
|
|
2489
|
+
},
|
|
2490
|
+
};
|
|
2491
|
+
}
|
|
2492
|
+
catch (error) {
|
|
2493
|
+
source.close();
|
|
2494
|
+
machine.close();
|
|
2495
|
+
throw error;
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
function phoneText(phone) {
|
|
2499
|
+
if (phone.pairingUrl === undefined) {
|
|
2500
|
+
return 'LAN access is on, but this computer has no private network address a phone could reach';
|
|
2501
|
+
}
|
|
2502
|
+
const where = phone.transport === 'tailscale'
|
|
2503
|
+
? `Phone access through Tailscale: ${phone.urls.join(', ')} (your tailnet's devices only; if a phone cannot open it, run otea phone tailscale)`
|
|
2504
|
+
: `LAN access on: ${phone.urls.join(', ')} (same network only; otea phone tailscale reaches it when away)`;
|
|
2505
|
+
return [
|
|
2506
|
+
where,
|
|
2507
|
+
`Pair a phone: scan this code, or open ${phone.pairingUrl} (pairing code ${phone.code}, 10 minutes, works once; the phone then opens every project on this computer)`,
|
|
2508
|
+
...(phone.byAddress
|
|
2509
|
+
? [`If the phone cannot open the .local name, open ${phone.byAddress}`]
|
|
2510
|
+
: []),
|
|
2511
|
+
renderUnicodeCompact(phone.pairingUrl, { ecc: 'M', border: 2 }),
|
|
2512
|
+
'A new code and the paired devices are in the UI, in Settings > Phone; otea devices list and revoke them too',
|
|
2513
|
+
].join('\n');
|
|
2514
|
+
}
|
|
2515
|
+
// Why a server stops once the process that started it ended (P1-R3-5): it stopped saying nothing,
|
|
2516
|
+
// and a server started in the background seemed to die at random.
|
|
2517
|
+
function ownerGoneText(started) {
|
|
2518
|
+
return `serve stopped: the process that started it (${started}) ended, as when the terminal or the agent session that ran it closes. To keep it running on its own, start it with otea serve --no-owner, and stop it with Ctrl+C or by its process id.`;
|
|
2519
|
+
}
|
|
2520
|
+
const serve = {
|
|
2521
|
+
name: 'serve',
|
|
2522
|
+
summary: `Serve the live UI of every project on this computer on 127.0.0.1 (default port ${DEFAULT_PORT}) until Ctrl+C, and open this project's page signed in; when this computer's otea serve runs already, it opens this project there instead. It also opens to phones on the same network when that was left open (Settings > Phone, otea phone lan --open), and --lan opens it for this run only; a phone on Tailscale (otea phone tailscale) pairs without it. It stops once the process that started it ends (a terminal closed, an agent's session over), saying so on stderr; --no-owner keeps it running on its own, as when started in the background`,
|
|
2523
|
+
args: [],
|
|
2524
|
+
options: { port: {}, 'no-open': { flag: true }, 'no-owner': { flag: true }, lan: { flag: true } },
|
|
2525
|
+
execute: async ({ cwd, option, flag, signal, openUrl, warn, tailscale, probe, home }) => {
|
|
2526
|
+
// A server whose starter is gone (an agent's session that ran it in the background ended)
|
|
2527
|
+
// stops, as it would with the terminal that ran it, and says why; --no-owner keeps it.
|
|
2528
|
+
const owner = flag('no-owner') ? undefined : watchOwner(signal);
|
|
2529
|
+
owner?.signal.addEventListener('abort', () => {
|
|
2530
|
+
if (owner.orphaned())
|
|
2531
|
+
warn(ownerGoneText(owner.started));
|
|
2532
|
+
}, { once: true });
|
|
2533
|
+
const served = await serveUntil(owner?.signal ?? signal, cwd, {
|
|
2534
|
+
port: portFrom(option('port')),
|
|
2535
|
+
lan: flag('lan'),
|
|
2536
|
+
tailscale,
|
|
2537
|
+
probe,
|
|
2538
|
+
warn,
|
|
2539
|
+
gitHook: withHome(OTEA, home),
|
|
2540
|
+
}).catch((error) => {
|
|
2541
|
+
owner?.stop();
|
|
2542
|
+
throw error;
|
|
2543
|
+
});
|
|
2544
|
+
// Pointing at the server that runs: nothing of this process stays running.
|
|
2545
|
+
if (served.attached)
|
|
2546
|
+
owner?.stop();
|
|
2547
|
+
const { url, signInUrl, phone, attached } = served;
|
|
2548
|
+
// With --no-open the person signs a browser in by hand, from a terminal or from what an agent
|
|
2549
|
+
// that started the server relays. The link carries the server's key: it is never in --json.
|
|
2550
|
+
const signIn = !flag('no-open')
|
|
2551
|
+
? []
|
|
2552
|
+
: [
|
|
2553
|
+
`Sign a browser in at ${signInUrl} (it holds this computer's Otea key: keep it to yourself)`,
|
|
2554
|
+
];
|
|
2555
|
+
if (!flag('no-open')) {
|
|
2556
|
+
await openUrl(signInUrl).catch((error) => {
|
|
2557
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2558
|
+
warn(`Could not open a browser (${reason}); run "otea open" to try again`);
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
const where = attached
|
|
2562
|
+
? `Otea already runs on this computer: this project is at ${url}`
|
|
2563
|
+
: `Otea running at ${url}`;
|
|
2564
|
+
const running = [where, ...signIn].join('\n');
|
|
2565
|
+
const data = { url, ...(attached ? { attached } : {}) };
|
|
2566
|
+
if (!phone)
|
|
2567
|
+
return { data, text: running };
|
|
2568
|
+
return { data: { ...data, phone }, text: `${running}\n${phoneText(phone)}` };
|
|
2569
|
+
},
|
|
2570
|
+
};
|
|
2571
|
+
const devicesList = {
|
|
2572
|
+
name: 'devices list',
|
|
2573
|
+
summary: 'List the paired phones and tablets (local network or otea phone tailscale), with when each was last seen; each one opens every project on this computer',
|
|
2574
|
+
args: [],
|
|
2575
|
+
options: {},
|
|
2576
|
+
execute: () => {
|
|
2577
|
+
const devices = withMachine(process.env, listDevices);
|
|
2578
|
+
const text = devices
|
|
2579
|
+
.map(({ id, name, pairedAt, lastSeenAt, hint }) => `${id} ${name} paired ${timeText(pairedAt)} last seen ${lastSeenAt ? timeText(lastSeenAt) : 'never'} token ··${hint}`)
|
|
2580
|
+
.join('\n');
|
|
2581
|
+
return { data: devices, text: text || 'No paired devices' };
|
|
2582
|
+
},
|
|
2583
|
+
};
|
|
2584
|
+
const devicesRevoke = {
|
|
2585
|
+
name: 'devices revoke',
|
|
2586
|
+
summary: 'Revoke a paired device: its token stops working at once, even while otea serve runs',
|
|
2587
|
+
args: ['id'],
|
|
2588
|
+
options: {},
|
|
2589
|
+
execute: ({ args: [id = ''] }) => {
|
|
2590
|
+
const device = withMachine(process.env, (machine) => revokeDevice(machine, id));
|
|
2591
|
+
return { data: device, text: `Revoked ${device.id} (${device.name})` };
|
|
2592
|
+
},
|
|
2593
|
+
};
|
|
2594
|
+
function notRunning(message) {
|
|
2595
|
+
return new CommandFailure('not_running', `${message}; run "otea serve" first`);
|
|
2596
|
+
}
|
|
2597
|
+
const open = {
|
|
2598
|
+
name: 'open',
|
|
2599
|
+
summary: "Open this project's page on this computer's running otea serve in the browser, signed in to act on items",
|
|
2600
|
+
args: [],
|
|
2601
|
+
options: { port: {} },
|
|
2602
|
+
execute: async ({ cwd, option, openUrl }) => {
|
|
2603
|
+
const here = projectHere(cwd);
|
|
2604
|
+
const home = oteaHome();
|
|
2605
|
+
const port = portToOpen(option('port'));
|
|
2606
|
+
const token = readUiToken(home);
|
|
2607
|
+
if (!token)
|
|
2608
|
+
throw notRunning('No Otea server has been started on this computer');
|
|
2609
|
+
const { url, signInUrl: link } = pages(`http://127.0.0.1:${port}`, token, here);
|
|
2610
|
+
const probe = await probeSignIn(link);
|
|
2611
|
+
if (probe === 'down')
|
|
2612
|
+
throw notRunning(`No Otea server answers on port ${port}`);
|
|
2613
|
+
if (probe === 'other')
|
|
2614
|
+
throw notRunning(`The Otea server on port ${port} is another Otea home's (OTEA_HOME)`);
|
|
2615
|
+
await openUrl(link).catch((error) => {
|
|
2616
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2617
|
+
throw new Error(`Could not open a browser (${reason})`);
|
|
2618
|
+
});
|
|
2619
|
+
return { data: { url }, text: `Opened Otea at ${url}` };
|
|
2620
|
+
},
|
|
2621
|
+
};
|
|
2622
|
+
// Stdout carries the protocol, so the command prints nothing itself.
|
|
2623
|
+
// The agent counts as heard as soon as its MCP client connects, and again on every beat while the
|
|
2624
|
+
// server stays open. Without a project yet there is nowhere to note it, and every tool call will
|
|
2625
|
+
// say so, so that is no warning.
|
|
2626
|
+
// Each server is its own session (process.pid): a name another open session works under is not
|
|
2627
|
+
// taken (claimName), and the refusal reaches the agent on its call.
|
|
2628
|
+
function heardBy(cwd, agent, harness, warn, newSession = false,
|
|
2629
|
+
// Its first call under the name: a new server its harness started may take it from the old one.
|
|
2630
|
+
fresh = newSession,
|
|
2631
|
+
// When it was heard, for the server to end its listening when its client closes.
|
|
2632
|
+
heard) {
|
|
2633
|
+
try {
|
|
2634
|
+
withProject(cwd, (project) => {
|
|
2635
|
+
claimName(project.db, agent, process.pid, undefined, undefined, process.ppid, fresh, harness?.name);
|
|
2636
|
+
const at = hearAgent(project.db, {
|
|
2637
|
+
agent,
|
|
2638
|
+
channel: 'mcp',
|
|
2639
|
+
harness,
|
|
2640
|
+
session: process.pid,
|
|
2641
|
+
launcher: process.ppid,
|
|
2642
|
+
...(newSession ? { newSession } : {}),
|
|
2643
|
+
});
|
|
2644
|
+
heard?.(at);
|
|
2645
|
+
});
|
|
2646
|
+
return true;
|
|
2647
|
+
}
|
|
2648
|
+
catch (error) {
|
|
2649
|
+
if (error instanceof OteaError && error.code === 'not_found')
|
|
2650
|
+
return true;
|
|
2651
|
+
if (error instanceof OteaError && error.code === 'name_in_use')
|
|
2652
|
+
return false;
|
|
2653
|
+
warn(`could not note ${agent} as seen: ${error.message}`);
|
|
2654
|
+
return true;
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
// The first call of an agent on this server: refused while another open session works under its
|
|
2658
|
+
// name, so two sessions never share one.
|
|
2659
|
+
function claimedBy(cwd, agent, fresh, client) {
|
|
2660
|
+
try {
|
|
2661
|
+
withProject(cwd, (project) => claimName(project.db, agent, process.pid, undefined, undefined, process.ppid, fresh, client?.name));
|
|
2662
|
+
}
|
|
2663
|
+
catch (error) {
|
|
2664
|
+
if (error instanceof OteaError && error.code === 'name_in_use')
|
|
2665
|
+
throw error;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
const mcp = {
|
|
2669
|
+
name: 'mcp',
|
|
2670
|
+
summary: 'Serve the agent commands as MCP tools on stdin and stdout until the client disconnects; each tool call acts as the agent its as argument names (or the one --as names). --project <id> pins the server to that project: it refuses writes from a folder of another one, and serves it when started outside any project. A tool answers with the text the command prints; --json makes it answer with the data otea --json prints, for a program that reads it',
|
|
2671
|
+
args: [],
|
|
2672
|
+
options: { project: { placeholder: 'id' } },
|
|
2673
|
+
execute: async ({ cwd, agent, pin: pinned, option, flag, signal, warn }) => {
|
|
2674
|
+
if (agent !== undefined)
|
|
2675
|
+
assertAgentName(agent);
|
|
2676
|
+
const pin = option('project') ?? pinned;
|
|
2677
|
+
// A harness that starts the server outside any project (its own config, kept for every folder)
|
|
2678
|
+
// gets the project the server is pinned to.
|
|
2679
|
+
if (pin !== undefined && !process.env.OTEA_PROJECT && !projectAt(cwd)) {
|
|
2680
|
+
process.env.OTEA_PROJECT = pin;
|
|
2681
|
+
}
|
|
2682
|
+
// Every agent that connected or called through this server, heard again on each beat until
|
|
2683
|
+
// the client disconnects: that is what makes it count as connected.
|
|
2684
|
+
const voices = new Set();
|
|
2685
|
+
// When this server last heard each of them: closing, it ends their listening (endListening).
|
|
2686
|
+
const lastHeard = new Map();
|
|
2687
|
+
const note = (name) => (at) => lastHeard.set(name, at);
|
|
2688
|
+
// Every name this server ever worked under: one it lost to a newer server never counts as new.
|
|
2689
|
+
const used = new Set();
|
|
2690
|
+
let client;
|
|
2691
|
+
// The client names its harness as it connects. Its agent is heard from its first call: a
|
|
2692
|
+
// harness that only loads the server (a background service, a session that never calls Otea)
|
|
2693
|
+
// is no agent at work, and shows as none.
|
|
2694
|
+
// The load is noted for its harness, though (P4-R2-10): otea connect --check and the desk can
|
|
2695
|
+
// tell the server works there before any tool is called.
|
|
2696
|
+
const greeted = (harness) => {
|
|
2697
|
+
client = harness;
|
|
2698
|
+
if (!harness)
|
|
2699
|
+
return;
|
|
2700
|
+
try {
|
|
2701
|
+
withProject(cwd, (project) => mcpLoaded(project.db, harness, systemClock, process.pid));
|
|
2702
|
+
}
|
|
2703
|
+
catch {
|
|
2704
|
+
// No project yet: every tool call will say so.
|
|
2705
|
+
}
|
|
2706
|
+
};
|
|
2707
|
+
// The names this server heard that were unknown before it did: one whose first call fails is
|
|
2708
|
+
// forgotten again, so a failed call leaves no agent «sin perfil» on the desk (P2S-R2-3).
|
|
2709
|
+
const newcomers = new Set();
|
|
2710
|
+
// When each agent last called through this server: a subagent that stopped calling has ended,
|
|
2711
|
+
// and the beat stops hearing it (P1-11); the session's own agent is the one it was started as,
|
|
2712
|
+
// else the first that called.
|
|
2713
|
+
const calls = new Map();
|
|
2714
|
+
let own = agent;
|
|
2715
|
+
const heard = (name) => {
|
|
2716
|
+
const fresh = !used.has(name);
|
|
2717
|
+
used.add(name);
|
|
2718
|
+
claimedBy(cwd, name, fresh, client);
|
|
2719
|
+
if (!knownAgent(cwd, name))
|
|
2720
|
+
newcomers.add(name);
|
|
2721
|
+
heardBy(cwd, name, client, warn, false, fresh, note(name));
|
|
2722
|
+
voices.add(name);
|
|
2723
|
+
calls.set(name, Date.now());
|
|
2724
|
+
own ??= name;
|
|
2725
|
+
};
|
|
2726
|
+
const still = (name) => {
|
|
2727
|
+
claimedBy(cwd, name, false, client);
|
|
2728
|
+
calls.set(name, Date.now());
|
|
2729
|
+
voices.add(name);
|
|
2730
|
+
};
|
|
2731
|
+
const failed = (name) => {
|
|
2732
|
+
if (!newcomers.delete(name))
|
|
2733
|
+
return;
|
|
2734
|
+
voices.delete(name);
|
|
2735
|
+
lastHeard.delete(name);
|
|
2736
|
+
try {
|
|
2737
|
+
withProject(cwd, (project) => forgetAgent(project.db, name));
|
|
2738
|
+
}
|
|
2739
|
+
catch {
|
|
2740
|
+
// No project to forget it in.
|
|
2741
|
+
}
|
|
2742
|
+
};
|
|
2743
|
+
// The server says it runs as it starts and on every beat, whether or not an agent calls through
|
|
2744
|
+
// it, so the desk and whoami never take a process that got its id after it ended for it
|
|
2745
|
+
// (P3C-R3-12); closing, it says it ended.
|
|
2746
|
+
const runs = (state = 'beat') => {
|
|
2747
|
+
try {
|
|
2748
|
+
withProject(cwd, (project) => {
|
|
2749
|
+
if (state === 'start')
|
|
2750
|
+
startProcess(project.db, process.pid);
|
|
2751
|
+
else if (state === 'end')
|
|
2752
|
+
endProcess(project.db, process.pid);
|
|
2753
|
+
else
|
|
2754
|
+
beatProcess(project.db, process.pid);
|
|
2755
|
+
});
|
|
2756
|
+
}
|
|
2757
|
+
catch {
|
|
2758
|
+
// No project yet: nobody watches this server.
|
|
2759
|
+
}
|
|
2760
|
+
};
|
|
2761
|
+
runs('start');
|
|
2762
|
+
// Each tool call it serves is noted, a wait as open until it ends: a newer server of the same
|
|
2763
|
+
// harness takes its agent's name only once this one went quiet (claimName, P8-R3-1).
|
|
2764
|
+
const calling = (command) => {
|
|
2765
|
+
const long = command === 'wait';
|
|
2766
|
+
const note = (open) => {
|
|
2767
|
+
try {
|
|
2768
|
+
withProject(cwd, (project) => noteCall(project.db, process.pid, systemClock, open));
|
|
2769
|
+
}
|
|
2770
|
+
catch {
|
|
2771
|
+
// No project yet: nobody takes a name here.
|
|
2772
|
+
}
|
|
2773
|
+
};
|
|
2774
|
+
note(long ? 1 : 0);
|
|
2775
|
+
return () => {
|
|
2776
|
+
if (long)
|
|
2777
|
+
note(-1);
|
|
2778
|
+
};
|
|
2779
|
+
};
|
|
2780
|
+
const beat = setInterval(() => {
|
|
2781
|
+
runs();
|
|
2782
|
+
const quiet = quietVoices(calls, own, Date.now()).filter((name) => voices.has(name));
|
|
2783
|
+
for (const name of quiet)
|
|
2784
|
+
voices.delete(name);
|
|
2785
|
+
endListeningAll(cwd, new Map(quiet.flatMap((name) => (lastHeard.has(name) ? [[name, lastHeard.get(name) ?? '']] : []))));
|
|
2786
|
+
for (const name of voices)
|
|
2787
|
+
if (!heardBy(cwd, name, client, warn, false, false, note(name)))
|
|
2788
|
+
voices.delete(name);
|
|
2789
|
+
}, LISTEN_BEAT_MS);
|
|
2790
|
+
beat.unref();
|
|
2791
|
+
const named = agent === undefined ? {} : { agent };
|
|
2792
|
+
try {
|
|
2793
|
+
// Whether the project keeps side topics, read once: the guide the agent gets says so.
|
|
2794
|
+
const topics = (() => {
|
|
2795
|
+
try {
|
|
2796
|
+
return withProject(cwd, (project) => topicsOn(project));
|
|
2797
|
+
}
|
|
2798
|
+
catch {
|
|
2799
|
+
return false;
|
|
2800
|
+
}
|
|
2801
|
+
})();
|
|
2802
|
+
// The MCP server's modules load only here, so every other command starts without them.
|
|
2803
|
+
const { createMcpServer, serveStdio } = await import('../mcp/server.js');
|
|
2804
|
+
await serveStdio(createMcpServer(COMMANDS, {
|
|
2805
|
+
cwd,
|
|
2806
|
+
...named,
|
|
2807
|
+
...(pin === undefined ? {} : { pin }),
|
|
2808
|
+
// otea mcp --json: results as the data --json prints, for a program; else the text.
|
|
2809
|
+
...(flag('json') ? { json: true } : {}),
|
|
2810
|
+
topics,
|
|
2811
|
+
warn,
|
|
2812
|
+
greeted,
|
|
2813
|
+
heard,
|
|
2814
|
+
still,
|
|
2815
|
+
failed,
|
|
2816
|
+
calling,
|
|
2817
|
+
}), signal);
|
|
2818
|
+
}
|
|
2819
|
+
finally {
|
|
2820
|
+
clearInterval(beat);
|
|
2821
|
+
// The client closed the session: its agents no longer listen through this server.
|
|
2822
|
+
endListeningAll(cwd, lastHeard);
|
|
2823
|
+
runs('end');
|
|
2824
|
+
}
|
|
2825
|
+
return undefined;
|
|
2826
|
+
},
|
|
2827
|
+
};
|
|
2828
|
+
// Whether the project knows the agent already (no project: as good as known, nothing to forget).
|
|
2829
|
+
function knownAgent(cwd, name) {
|
|
2830
|
+
try {
|
|
2831
|
+
return withProject(cwd, (project) => findAgent(project.db, name) !== undefined);
|
|
2832
|
+
}
|
|
2833
|
+
catch {
|
|
2834
|
+
return true;
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
// Whether a project resolves from the folder (or OTEA_PROJECT names one).
|
|
2838
|
+
function projectAt(cwd) {
|
|
2839
|
+
try {
|
|
2840
|
+
withProject(cwd, () => undefined);
|
|
2841
|
+
return true;
|
|
2842
|
+
}
|
|
2843
|
+
catch (error) {
|
|
2844
|
+
if (error instanceof OteaError && error.code === 'not_found')
|
|
2845
|
+
return false;
|
|
2846
|
+
throw error;
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
function endListeningAll(cwd, lastHeard) {
|
|
2850
|
+
if (lastHeard.size === 0)
|
|
2851
|
+
return;
|
|
2852
|
+
try {
|
|
2853
|
+
withProject(cwd, (project) => {
|
|
2854
|
+
for (const [name, at] of lastHeard)
|
|
2855
|
+
endListening(project.db, name, at, process.pid);
|
|
2856
|
+
});
|
|
2857
|
+
}
|
|
2858
|
+
catch {
|
|
2859
|
+
// The project may be gone; its agents' listening then lapses on its own.
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
// The fields a gate check matches: --field pairs, plus the branch and the repo, which default to
|
|
2863
|
+
// the git checkout's when given without a value (the branch to `defaultBranch`, when given; the
|
|
2864
|
+
// repo to the name the project gives the repo checked out, app/repos.ts).
|
|
2865
|
+
function gateFields({ option, options }, cwd, project, defaultBranch = () => currentBranch(cwd)) {
|
|
2866
|
+
const fields = {};
|
|
2867
|
+
const set = (key, value) => {
|
|
2868
|
+
if (key in fields)
|
|
2869
|
+
throw new UsageError(`Field "${key}" given twice`);
|
|
2870
|
+
fields[key] = value;
|
|
2871
|
+
};
|
|
2872
|
+
for (const pair of options('field'))
|
|
2873
|
+
set(...fieldPair(pair));
|
|
2874
|
+
const branch = option('branch');
|
|
2875
|
+
if (branch !== undefined)
|
|
2876
|
+
set('branch', branch || defaultBranch());
|
|
2877
|
+
const repo = option('repo');
|
|
2878
|
+
if (repo !== undefined)
|
|
2879
|
+
set('repo', repo || repoNameAt(project, cwd));
|
|
2880
|
+
return fields;
|
|
2881
|
+
}
|
|
2882
|
+
function gateText({ gate, allowed, items, refusal, person }) {
|
|
2883
|
+
// On a board, the step engine's words for each item, and why a push into a protected base
|
|
2884
|
+
// branch that brings in none of its items is refused; last, how the person lands their own.
|
|
2885
|
+
const said = items.filter((item) => allowed || !item.allowed).flatMap(({ text }) => text ?? []);
|
|
2886
|
+
if (refusal !== undefined)
|
|
2887
|
+
said.push(refusal);
|
|
2888
|
+
if (person !== undefined)
|
|
2889
|
+
said.push(person);
|
|
2890
|
+
if (said.length > 0)
|
|
2891
|
+
return said.join('\n');
|
|
2892
|
+
if (allowed) {
|
|
2893
|
+
const states = items.map(({ id, stateName }) => `${id} is ${stateName}`);
|
|
2894
|
+
return `${gate} allowed: ${states.join(', ')}`;
|
|
2895
|
+
}
|
|
2896
|
+
return items
|
|
2897
|
+
.filter((item) => !item.allowed)
|
|
2898
|
+
.map(({ id, stateName, allowedInNames }) => `${gate} refused: ${id} is ${stateName}; ${gate} is allowed only in ${allowedInNames.join(', ')}`)
|
|
2899
|
+
.join('\n');
|
|
2900
|
+
}
|
|
2901
|
+
// The commits a push sends, as `--commits <remote>..<local>` names them: what the remote has of
|
|
2902
|
+
// the branch and what it gets (the ids a pre-push hook reads; all zeros for a branch created or
|
|
2903
|
+
// deleted).
|
|
2904
|
+
function commitsOption(value) {
|
|
2905
|
+
const [from, to, ...rest] = value.split('..');
|
|
2906
|
+
if (from === undefined || to === undefined || rest.length > 0) {
|
|
2907
|
+
throw new UsageError('--commits takes <remote>..<local>, the commits the push sends');
|
|
2908
|
+
}
|
|
2909
|
+
return { from, to };
|
|
2910
|
+
}
|
|
2911
|
+
// A gate check fails open: anything that keeps it from answering allows the action, with a note.
|
|
2912
|
+
// A push or merge in a repo the project cannot match (--repo with no name) is refused, not
|
|
2913
|
+
// allowed, whatever its folder: on a project, failing open there would skip every gate.
|
|
2914
|
+
const check = {
|
|
2915
|
+
name: 'check',
|
|
2916
|
+
summary: 'Check whether the items matching the fields allow a gated action: exit 0 when allowed, 19 when refused, 2 for a gate nothing declares; repo names match whatever their case; it allows the action, with a note, when no item matches or the check cannot run, except a push of a branch no item names in a project where a board protects a base branch, which it refuses. --branch defaults to the branch checked out, --repo to the name the project gives the repo checked out (otea repos list), refused when the project does not know it. A push or merge into a base branch a board protects is checked against the items whose branches it brings in: --commits <remote>..<local> names the commits a push sends (the pre-push hook passes them), else the branch against the remote branch of the same name (origin/<branch>), or its upstream when the remote has none. A merge of a branch the person approved fetches it from its remote and is refused when it is not the approved commit (or a rebase of it with the same result), or when the check cannot fetch it',
|
|
2917
|
+
args: [],
|
|
2918
|
+
options: {
|
|
2919
|
+
gate: { required: true, placeholder: 'action' },
|
|
2920
|
+
field: { multiple: true, placeholder: 'key=value' },
|
|
2921
|
+
branch: { optionalValue: true, placeholder: 'name' },
|
|
2922
|
+
repo: { optionalValue: true, placeholder: 'name' },
|
|
2923
|
+
commits: { placeholder: 'remote..local' },
|
|
2924
|
+
},
|
|
2925
|
+
execute: async (input) => {
|
|
2926
|
+
const gate = input.required('gate');
|
|
2927
|
+
// The hook runs this check on every push: the person sees an outdated hook there.
|
|
2928
|
+
const outdated = outdatedGitHookLine(input.cwd);
|
|
2929
|
+
if (outdated !== undefined)
|
|
2930
|
+
input.warn(outdated);
|
|
2931
|
+
let result;
|
|
2932
|
+
try {
|
|
2933
|
+
const { cwd } = input;
|
|
2934
|
+
const named = input.option('branch');
|
|
2935
|
+
const commits = input.option('commits');
|
|
2936
|
+
const sent = commits === undefined ? undefined : commitsOption(commits);
|
|
2937
|
+
// A commit the repo does not have leaves the check blind to what it brings in (P3C-R3-3):
|
|
2938
|
+
// refused, never allowed with a note. All zeros is a deleted branch, which brings in nothing.
|
|
2939
|
+
if (sent && !/^0+$/.test(sent.to) && !hasCommit(cwd, sent.to)) {
|
|
2940
|
+
const text = `${gate} refused: could not check: ${sent.to} is not in this repository; fetch first.`;
|
|
2941
|
+
const data = { gate, allowed: false, items: [], refusal: text };
|
|
2942
|
+
return { data, text, failure: 'gate_refused' };
|
|
2943
|
+
}
|
|
2944
|
+
result = withProject(cwd, (project) => {
|
|
2945
|
+
// The branch is asked of git only when the check needs it.
|
|
2946
|
+
const branch = () => named || currentBranch(cwd);
|
|
2947
|
+
// A merge of an approved branch is checked against the remote as it is now (P3C-R3-1).
|
|
2948
|
+
const takes = (tip, base) => mergeTake(cwd, tip, base, sent?.to);
|
|
2949
|
+
const brings = () => ({
|
|
2950
|
+
...(sent === undefined
|
|
2951
|
+
? branchesBrought(cwd, branch(), remoteOf(cwd, branch()))
|
|
2952
|
+
: branchesBrought(cwd, sent.to, sent.from)),
|
|
2953
|
+
takes,
|
|
2954
|
+
// A push the hook names rewrites the remote branch unless it adds to it (P1-R3-3).
|
|
2955
|
+
...(sent === undefined
|
|
2956
|
+
? {}
|
|
2957
|
+
: { rewrites: () => rewritesRemote(cwd, sent.from, sent.to) }),
|
|
2958
|
+
});
|
|
2959
|
+
return checkGate(project, gate, gateFields(input, cwd, project, branch), brings);
|
|
2960
|
+
});
|
|
2961
|
+
}
|
|
2962
|
+
catch (error) {
|
|
2963
|
+
if (error instanceof UsageError)
|
|
2964
|
+
throw error;
|
|
2965
|
+
// Inside a project, a repo it cannot match could be any of its repos: refused, not allowed.
|
|
2966
|
+
if (error instanceof UnknownRepo) {
|
|
2967
|
+
input.warn(`${gate} refused: ${error.message}`);
|
|
2968
|
+
return { data: { gate, allowed: false, items: [] }, text: '', failure: 'gate_refused' };
|
|
2969
|
+
}
|
|
2970
|
+
// A field or a gate nothing names is a typo in the call, never a reason to allow the action.
|
|
2971
|
+
if (error instanceof OteaError && error.code === 'invalid_fields')
|
|
2972
|
+
throw new UsageError(error.message);
|
|
2973
|
+
if (error instanceof OteaError && error.code === 'invalid_gate')
|
|
2974
|
+
throw error;
|
|
2975
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2976
|
+
result = { gate, allowed: true, items: [], note: `could not check (${message})` };
|
|
2977
|
+
}
|
|
2978
|
+
if (result.note)
|
|
2979
|
+
input.warn(`${result.note}; ${gate} allowed`);
|
|
2980
|
+
if (result.items.length === 0 && result.refusal === undefined)
|
|
2981
|
+
return { data: result, text: '' };
|
|
2982
|
+
const text = gateText(result);
|
|
2983
|
+
if (result.allowed)
|
|
2984
|
+
return { data: result, text };
|
|
2985
|
+
return { data: result, text, failure: 'gate_refused' };
|
|
2986
|
+
},
|
|
2987
|
+
};
|
|
2988
|
+
// The hooks a command names, of those it takes; never none. No gate depends on a harness hook:
|
|
2989
|
+
// install writes only the git hook, and remove --claude takes out the Claude Code hooks an older
|
|
2990
|
+
// otea hook install --claude wrote, whose commands are gone.
|
|
2991
|
+
function hookTargets({ flag }, targets) {
|
|
2992
|
+
const named = targets.filter((target) => flag(target));
|
|
2993
|
+
if (named.length === 0) {
|
|
2994
|
+
throw new UsageError(`Name the hook: ${targets.map((target) => `--${target}`).join(' or ')}`);
|
|
2995
|
+
}
|
|
2996
|
+
return named;
|
|
2997
|
+
}
|
|
2998
|
+
function hookText({ path, action, content, note, said }) {
|
|
2999
|
+
const why = note === undefined ? '' : ` (${note})`;
|
|
3000
|
+
if (said === undefined && action === 'unchanged')
|
|
3001
|
+
return `${path} already has the Otea hook${why}`;
|
|
3002
|
+
if (said === undefined && action === 'absent')
|
|
3003
|
+
return `${path} has no Otea hook`;
|
|
3004
|
+
const done = { created: 'Wrote', updated: 'Rewrote', removed: 'Removed the Otea hook from' };
|
|
3005
|
+
const head = said ?? `${done[action]} ${path}${why}`;
|
|
3006
|
+
return content === undefined ? head : `${head}:\n${indent(content.trimEnd())}`;
|
|
3007
|
+
}
|
|
3008
|
+
function hookOutput(changes) {
|
|
3009
|
+
return { data: changes, text: changes.map(hookText).join('\n') };
|
|
3010
|
+
}
|
|
3011
|
+
const hookInstall = {
|
|
3012
|
+
name: 'hook install',
|
|
3013
|
+
summary: 'Make the gates hard in the repo here, whatever tool runs the push or merge: --git writes a pre-push hook that runs otea check --gate push (never overwrites a hook of someone else); --forge has gh set a GitHub ruleset on the base branches the boards protect, so GitHub refuses a direct push, a force push and a deletion of them, or prints the steps to set it by hand',
|
|
3014
|
+
args: [],
|
|
3015
|
+
options: { git: { flag: true }, forge: { flag: true } },
|
|
3016
|
+
// Each hook is installed on its own: one that cannot be (no repo, a team's own pre-push hook)
|
|
3017
|
+
// never keeps another from being written, and the refusal says what was written.
|
|
3018
|
+
execute: (input) => {
|
|
3019
|
+
const changes = [];
|
|
3020
|
+
const refused = [];
|
|
3021
|
+
for (const target of hookTargets(input, ['git', 'forge'])) {
|
|
3022
|
+
try {
|
|
3023
|
+
changes.push(target === 'git'
|
|
3024
|
+
? installGitHook(input.cwd, withHome(OTEA, input.home))
|
|
3025
|
+
: installForge(input.cwd, withProject(input.cwd, protectedBases), input.forge));
|
|
3026
|
+
}
|
|
3027
|
+
catch (error) {
|
|
3028
|
+
if (!(error instanceof CommandFailure || error instanceof OteaError))
|
|
3029
|
+
throw error;
|
|
3030
|
+
refused.push(error);
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
const [first] = refused;
|
|
3034
|
+
if (!first)
|
|
3035
|
+
return hookOutput(changes);
|
|
3036
|
+
const said = [...changes.map(hookText), ...refused.map(({ message }) => message)];
|
|
3037
|
+
throw new CommandFailure(failureCode(first), said.join('\n'));
|
|
3038
|
+
},
|
|
3039
|
+
};
|
|
3040
|
+
const hookRemove = {
|
|
3041
|
+
name: 'hook remove',
|
|
3042
|
+
summary: 'Remove the hooks Otea wrote, leaving every other hook and rule: --git the pre-push hook; --forge the GitHub ruleset hook install --forge set; --claude the Claude Code hooks and allow rules an older otea hook install --claude added to .claude/settings.local.json',
|
|
3043
|
+
args: [],
|
|
3044
|
+
options: { git: { flag: true }, forge: { flag: true }, claude: { flag: true } },
|
|
3045
|
+
execute: (input) => hookOutput(hookTargets(input, ['git', 'forge', 'claude']).map((target) => target === 'git'
|
|
3046
|
+
? removeGitHook(input.cwd)
|
|
3047
|
+
: target === 'forge'
|
|
3048
|
+
? removeForge(input.cwd, input.forge)
|
|
3049
|
+
: removeClaudeHook(input.cwd))),
|
|
3050
|
+
};
|
|
3051
|
+
// Side topics (app/topics.ts): what the person asked an agent off the work, kept as a short
|
|
3052
|
+
// conversation so none is left hanging. The agent records the question and answers it; the person
|
|
3053
|
+
// keeps it going, closes it or turns it into a task. They are not work: no lease, never in next.
|
|
3054
|
+
const topicOn = {
|
|
3055
|
+
name: 'topic on',
|
|
3056
|
+
summary: 'For the person: keep side topics for this project, so agents record the questions you ask them off the work, with their answers',
|
|
3057
|
+
args: [],
|
|
3058
|
+
options: {},
|
|
3059
|
+
execute: (input) => withProject(input.cwd, (project) => {
|
|
3060
|
+
setTopicsOn(project, true);
|
|
3061
|
+
return {
|
|
3062
|
+
data: { topics: true },
|
|
3063
|
+
text: 'Topics are on: agents record the side questions you ask them.',
|
|
3064
|
+
};
|
|
3065
|
+
}),
|
|
3066
|
+
};
|
|
3067
|
+
const topicOff = {
|
|
3068
|
+
name: 'topic off',
|
|
3069
|
+
summary: 'For the person: stop keeping side topics for this project; the ones kept stay',
|
|
3070
|
+
args: [],
|
|
3071
|
+
options: {},
|
|
3072
|
+
execute: (input) => withProject(input.cwd, (project) => {
|
|
3073
|
+
setTopicsOn(project, false);
|
|
3074
|
+
return { data: { topics: false }, text: 'Topics are off.' };
|
|
3075
|
+
}),
|
|
3076
|
+
};
|
|
3077
|
+
const topicAdd = {
|
|
3078
|
+
name: 'topic add',
|
|
3079
|
+
summary: 'Record a question the person asked you off the work at hand, not a request to do work, before you answer it (--title, short; --session and --resume when known; --to <id>, a follow-up to that topic); then answer it with topic answer',
|
|
3080
|
+
args: ['question'],
|
|
3081
|
+
options: { title: {}, to: { placeholder: 'id' }, session: {}, resume: {} },
|
|
3082
|
+
execute: (input) => {
|
|
3083
|
+
const [question = ''] = input.args;
|
|
3084
|
+
const title = input.option('title');
|
|
3085
|
+
const to = input.option('to');
|
|
3086
|
+
const session = input.option('session');
|
|
3087
|
+
const resume = input.option('resume');
|
|
3088
|
+
const { actor } = input;
|
|
3089
|
+
return withAgent(input, (project) => {
|
|
3090
|
+
requireTopicsOn(project);
|
|
3091
|
+
const topic = addTopic(project, {
|
|
3092
|
+
question,
|
|
3093
|
+
actor,
|
|
3094
|
+
...(title === undefined ? {} : { title }),
|
|
3095
|
+
...(to === undefined ? {} : { to }),
|
|
3096
|
+
...(session === undefined ? {} : { session }),
|
|
3097
|
+
...(resume === undefined ? {} : { resume }),
|
|
3098
|
+
});
|
|
3099
|
+
const done = to === undefined ? `Recorded ${topic.id}` : `Added the follow-up to ${topic.id}`;
|
|
3100
|
+
return {
|
|
3101
|
+
data: topic,
|
|
3102
|
+
text: `${done}. Answer it with otea topic answer ${topic.id} --summary "<short answer>" --full "<your answer as you gave it>".`,
|
|
3103
|
+
};
|
|
3104
|
+
});
|
|
3105
|
+
},
|
|
3106
|
+
};
|
|
3107
|
+
const topicAnswer = {
|
|
3108
|
+
name: 'topic answer',
|
|
3109
|
+
summary: 'Answer a topic: --summary, a line or two; --full, your whole answer as given in the chat',
|
|
3110
|
+
args: ['id'],
|
|
3111
|
+
options: { summary: {}, full: {}, session: {}, resume: {} },
|
|
3112
|
+
execute: (input) => {
|
|
3113
|
+
const [id = ''] = input.args;
|
|
3114
|
+
const summary = input.option('summary');
|
|
3115
|
+
const full = input.option('full');
|
|
3116
|
+
const session = input.option('session');
|
|
3117
|
+
const resume = input.option('resume');
|
|
3118
|
+
const { actor } = input;
|
|
3119
|
+
return withAgent(input, (project) => {
|
|
3120
|
+
requireTopicsOn(project);
|
|
3121
|
+
const topic = answerTopic(project, {
|
|
3122
|
+
id,
|
|
3123
|
+
actor,
|
|
3124
|
+
...(summary === undefined ? {} : { summary }),
|
|
3125
|
+
...(full === undefined ? {} : { full }),
|
|
3126
|
+
...(session === undefined ? {} : { session }),
|
|
3127
|
+
...(resume === undefined ? {} : { resume }),
|
|
3128
|
+
});
|
|
3129
|
+
return { data: topic, text: `Answered ${topic.id}; it is the person's turn.` };
|
|
3130
|
+
});
|
|
3131
|
+
},
|
|
3132
|
+
};
|
|
3133
|
+
// Every project on this computer, open while `use` reads them: the registered ones and the local
|
|
3134
|
+
// ones a server served (server/hub.ts).
|
|
3135
|
+
function withEveryProject(use) {
|
|
3136
|
+
const machine = openMachine();
|
|
3137
|
+
const source = machineProjects(process.env, machine);
|
|
3138
|
+
try {
|
|
3139
|
+
return use(source.list());
|
|
3140
|
+
}
|
|
3141
|
+
finally {
|
|
3142
|
+
source.close();
|
|
3143
|
+
machine.close();
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
// A project of this computer by id, or by name when no other project has it.
|
|
3147
|
+
function servedProject(served, ref) {
|
|
3148
|
+
const byId = served.find((each) => each.id === ref);
|
|
3149
|
+
const named = served.filter((each) => each.name === ref);
|
|
3150
|
+
if (!byId && named.length > 1) {
|
|
3151
|
+
const ids = named.map(({ id }) => id).join(', ');
|
|
3152
|
+
throw new OteaError('invalid_name', `Several projects are named "${ref}" (${ids}); use its id`);
|
|
3153
|
+
}
|
|
3154
|
+
const found = byId ?? named[0];
|
|
3155
|
+
if (!found)
|
|
3156
|
+
throw new OteaError('not_found', `No project "${ref}" on this computer; run otea projects list`);
|
|
3157
|
+
if (!found.project)
|
|
3158
|
+
throw new OteaError('not_found', found.unavailable ?? `${found.name} is not available`);
|
|
3159
|
+
return found.project;
|
|
3160
|
+
}
|
|
3161
|
+
const topicList = {
|
|
3162
|
+
name: 'topic list',
|
|
3163
|
+
summary: 'List the side topics that wait on someone, what is left hanging first (--all, closed ones too); --search: topics with any of the words, best first, with answers; then items whose threads say them; --all-projects: in every project',
|
|
3164
|
+
args: [],
|
|
3165
|
+
options: {
|
|
3166
|
+
all: { flag: true },
|
|
3167
|
+
search: { placeholder: 'words' },
|
|
3168
|
+
'all-projects': { flag: true },
|
|
3169
|
+
},
|
|
3170
|
+
execute: (input) => withReader(input, (project) => {
|
|
3171
|
+
const search = input.option('search');
|
|
3172
|
+
const filter = { all: input.flag('all'), ...(search === undefined ? {} : { search }) };
|
|
3173
|
+
const searching = search !== undefined && search.trim() !== '';
|
|
3174
|
+
// What was concluded is often in another project: a question about geo-api asked in
|
|
3175
|
+
// ventas-etl (P6-R2-4).
|
|
3176
|
+
if (input.flag('all-projects')) {
|
|
3177
|
+
const found = withEveryProject((served) => topicsEverywhere(served, project.identity.id, filter));
|
|
3178
|
+
return {
|
|
3179
|
+
data: searching ? found : found.topics,
|
|
3180
|
+
text: topicsEverywhereText(found, search),
|
|
3181
|
+
};
|
|
3182
|
+
}
|
|
3183
|
+
const topics = listTopics(project, filter);
|
|
3184
|
+
if (!searching)
|
|
3185
|
+
return { data: topics, text: topicsListText(topics, search) };
|
|
3186
|
+
// A search looks in the items' threads too, where a decision is often made (P3C-R2-8).
|
|
3187
|
+
const items = searchItems(project, search);
|
|
3188
|
+
const text = [topicsListText(topics, search), itemHitsText(items)].filter(Boolean);
|
|
3189
|
+
return { data: { topics, items }, text: text.join('\n\n') };
|
|
3190
|
+
}),
|
|
3191
|
+
};
|
|
3192
|
+
const topicShow = {
|
|
3193
|
+
name: 'topic show',
|
|
3194
|
+
summary: 'Show a side topic: its question, answers and notes, with each full answer (--project, of another project)',
|
|
3195
|
+
args: ['id'],
|
|
3196
|
+
options: { project: { placeholder: 'id or name' } },
|
|
3197
|
+
execute: (input) => {
|
|
3198
|
+
const [id = ''] = input.args;
|
|
3199
|
+
const other = input.option('project');
|
|
3200
|
+
return withReader(input, (project) => {
|
|
3201
|
+
const topic = other === undefined
|
|
3202
|
+
? requireTopic(project, id)
|
|
3203
|
+
: withEveryProject((served) => requireTopic(servedProject(served, other), id));
|
|
3204
|
+
return { data: topic, text: topicText(topic) };
|
|
3205
|
+
});
|
|
3206
|
+
},
|
|
3207
|
+
};
|
|
3208
|
+
const topicNote = {
|
|
3209
|
+
name: 'topic note',
|
|
3210
|
+
summary: 'For the person: keep a topic going with a note; the agent that answered it gets it',
|
|
3211
|
+
args: ['id', 'text'],
|
|
3212
|
+
options: {},
|
|
3213
|
+
execute: (input) => {
|
|
3214
|
+
const [id = '', text = ''] = input.args;
|
|
3215
|
+
return withReader(input, (project) => {
|
|
3216
|
+
const topic = noteTopic(project, { id, text, actor: input.reader });
|
|
3217
|
+
return { data: topic, text: `Left a note on ${topic.id}; it is the agent's turn.` };
|
|
3218
|
+
});
|
|
3219
|
+
},
|
|
3220
|
+
};
|
|
3221
|
+
const topicClose = {
|
|
3222
|
+
name: 'topic close',
|
|
3223
|
+
summary: 'For the person: close a topic you have read',
|
|
3224
|
+
args: ['id'],
|
|
3225
|
+
options: {},
|
|
3226
|
+
execute: (input) => {
|
|
3227
|
+
const [id = ''] = input.args;
|
|
3228
|
+
return withReader(input, (project) => {
|
|
3229
|
+
const topic = closeTopic(project, { id, actor: input.reader });
|
|
3230
|
+
return { data: topic, text: `Closed ${topic.id}.` };
|
|
3231
|
+
});
|
|
3232
|
+
},
|
|
3233
|
+
};
|
|
3234
|
+
export const COMMANDS = [
|
|
3235
|
+
init,
|
|
3236
|
+
projectsList,
|
|
3237
|
+
projectsCurrent,
|
|
3238
|
+
projectsAdd,
|
|
3239
|
+
projectsRelink,
|
|
3240
|
+
projectsForget,
|
|
3241
|
+
reposList,
|
|
3242
|
+
reposAdd,
|
|
3243
|
+
reposRemove,
|
|
3244
|
+
migrateCommand,
|
|
3245
|
+
connect,
|
|
3246
|
+
collectionIconCommand,
|
|
3247
|
+
create,
|
|
3248
|
+
list,
|
|
3249
|
+
show,
|
|
3250
|
+
boardAdd,
|
|
3251
|
+
boardDraft,
|
|
3252
|
+
board,
|
|
3253
|
+
promptCommand,
|
|
3254
|
+
brief,
|
|
3255
|
+
events,
|
|
3256
|
+
stats,
|
|
3257
|
+
wait,
|
|
3258
|
+
claim,
|
|
3259
|
+
profileCommandSpec,
|
|
3260
|
+
whoami,
|
|
3261
|
+
heartbeat,
|
|
3262
|
+
release,
|
|
3263
|
+
update,
|
|
3264
|
+
attach,
|
|
3265
|
+
detach,
|
|
3266
|
+
link,
|
|
3267
|
+
unlink,
|
|
3268
|
+
next,
|
|
3269
|
+
reply,
|
|
3270
|
+
crop,
|
|
3271
|
+
merged,
|
|
3272
|
+
reopen,
|
|
3273
|
+
tick,
|
|
3274
|
+
topicOn,
|
|
3275
|
+
topicOff,
|
|
3276
|
+
topicAdd,
|
|
3277
|
+
topicAnswer,
|
|
3278
|
+
topicList,
|
|
3279
|
+
topicShow,
|
|
3280
|
+
topicNote,
|
|
3281
|
+
topicClose,
|
|
3282
|
+
ask,
|
|
3283
|
+
answer,
|
|
3284
|
+
handoffCommand,
|
|
3285
|
+
dropCommand,
|
|
3286
|
+
approveCommand,
|
|
3287
|
+
sendBack,
|
|
3288
|
+
move,
|
|
3289
|
+
relay,
|
|
3290
|
+
validate,
|
|
3291
|
+
check,
|
|
3292
|
+
hookInstall,
|
|
3293
|
+
hookRemove,
|
|
3294
|
+
serve,
|
|
3295
|
+
open,
|
|
3296
|
+
devicesList,
|
|
3297
|
+
devicesRevoke,
|
|
3298
|
+
...PHONE_COMMANDS,
|
|
3299
|
+
mcp,
|
|
3300
|
+
];
|
|
3301
|
+
export function findCommand(tokens) {
|
|
3302
|
+
return COMMANDS.find((command) => command.name.split(' ').every((word, index) => tokens[index] === word));
|
|
3303
|
+
}
|