kinitro.ai agent harness for Claude: briefs a kinitro.ai domain agent from the platform (persona, standing rules, start, every turn, context checkpoint, after…

kinitro.ai lets business users work with AI agents that know their business, follow their procedures and keep their results in one governed place. This repository holds what you need to run a kinitro.ai agent in Claude.
kinitro.ai is an AI-native workspace for teams that work with AI agents. Each team or project gets its own domain: a governed place where its agents, knowledge, data and work management (tasks, todos, documents) live together. Agents in a domain carry a persona, working rules and procedures that the domain owner maintains, so they know the business and act the same way every time. Knowledge and memory stay in the domain instead of in a single chat, and every conversation is mirrored back into it. The kinitro-ai plugin for Claude Desktop and Claude Code connects Claude to your kinitro.ai tenant through MCP (https://methos.kinitro.ai/mcp), briefs Claude as your domain agent and keeps the work in kinitro.ai.
| Path | What it is |
|---|---|
plugins/kinitro-ai/ | The Claude Code plugin kinitro-ai (version 0.25.0). It briefs your agent from kinitro.ai and mirrors each conversation turn into your domain. |
.claude-plugin/marketplace.json | The marketplace entry that lets Claude Code install the plugin. |
docs/ | Guides for users, setup people and partners. |
assets/ | The kinitro ai logo. |
You need three things:
/kinitro domain: the plugin signs you in with a code from your email (no browser callback, no /mcp step) and then offers your domains; this works in the Claude Code terminal and in the Claude desktop app.git on the machine.Install the plugin once per machine, in a Claude Code session:
/plugin marketplace add ThorstenHornung/kinitro.ai
/plugin install kinitro-ai@kinitro-ai
The plugin is active at once and in every later session. Choose your domain with:
/kinitro
It opens the kinitro.ai domain selection and binds the session to the domain you choose (/kinitro verum binds directly). Step-by-step help: Getting started.
/plugin marketplace add https://methos.kinitro.ai/download/plugins/claude/marketplace.json
/plugin install kinitro-ai@kinitro-ai
/plugin marketplace add ThorstenHornung/kinitro.ai, as in the quick start above.From 0.23.2 the plugin checks once a day, at the first prompt of a session, whether the download page publishes a newer version, and tells you in one line. In Claude Code, run:
/kinitro update
It runs claude plugin marketplace update kinitro-ai and then claude plugin update kinitro-ai@kinitro-ai. Claude Code asks for your permission before these commands run, so nothing changes without your approval. Then run /reload-plugins to load the new version. In Cowork and the Claude desktop app, download the new zip from the download page and upload it again.
All instruction texts live in kinitro.ai and are edited by the domain owner. The plugin only decides when each section is handed to the agent.
| Moment | What is injected |
|---|---|
| First message of a conversation, and again after each compaction | Persona and Working rules |
| First prompt of a session | Session start |
| Every prompt | A one-line marker, the Every turn section, the agent's todo list (short form: one line of at most 160 characters per todo; the full text at the first turn, after a compaction and when the list changed) and a reminder to update it; at the first turn and after a compaction also the last 5 turns of the agent's chat |
| First prompt and after a compaction | The agent's notes and a map of its memory topics |
| Context window reaches 70 % (and again every 5 points more) | Context nearly full |
| First prompt after a compaction | After compaction |
| While Claude compacts the conversation | Compaction instruction (goes to the summarizer) |
| End of every turn | Your prompt and the agent's final answer are written into the agent's chat in kinitro.ai |
Details: How it works and Plugin reference.
Partners build specialized agent solutions on kinitro.ai and offer them to customers, at a charge. A solution combines persona, procedures, knowledge, data model, views and documents. Commercial terms are agreed individually during the beta. See For partners. To get access, contact Kinitro Consulting, support@kinitro.ai.
Proprietary beta software. See LICENSE.
hooks/register.tsx 2434 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3import type { DomainChoice } from '../types'
4import { VARIANT } from './variant'
5
6// kinitro-ai harness for Claude. All instruction TEXTS live in kinitro.ai; this file only decides WHEN
7// each section is injected. 0.23.6 (PO 16.10.2026): the briefing is the agent node's instruction set, injected as the
8// server gives it. get-briefing `instructions` is composed server-side (AIAgent first, then the agent node; the node's
9// persona replaces the AIAgent's; a type missing on both is empty). The Agent 101 reaches the agent through the server's
10// {{mx:include}} in the coldstart and postcompaction templates; the plugin neither expects nor cuts an Agent 101 block.
11// No domain edge is read. A domain without an agent node is refused with a plain message.
12
13// Todo housekeeping (0.23.1, PO 2026-10-16): the full todo list costs about 3,000 tokens on every prompt of a long list.
14// Every prompt gets a short list (one line per todo) and a push line; the full text only at the first turn, after a
15// compaction, after a domain choice and when the list changed since its last full injection. Nothing is ever deleted:
16// the push line only names what exceeds these limits.
17const TODO_MAX_AGE_DAYS = 7 // a todo older than this is named in the push line
18const TODO_MAX_ITEMS = 10 // more open todos than this are named in the push line
19const TODO_MAX_ITEM_CHARS = 400 // a todo text longer than this is named in the push line
20const TODO_TURN_LINE_CHARS = 160 // the short per-turn list shows this many chars of each todo
21
22// Chat tail (0.23.1, PO 2026-10-16): at session start and after compaction the last turns of the agent's chat (read-chat-tail)
23const CHAT_TAIL_TURNS = 5 // turns (a turn = the prompt and the answer: two messages)
24const CHAT_TAIL_MSG_CHARS = 600 // each message is cut to this
25const CHAT_TAIL_BLOCK_CHARS = 6000 // the whole block stays about this size: the oldest messages go first
26const CHAT_TAIL_SPEAKER_CHARS = 40 // the speaker name is cut to this
27const READ_TIMEOUT_MS = 3000 // the chat tail and the todo read in prompt.submit wait at most this long (review F1)
28
29const SERVER = 'kinitro_ai'
30// Build variant (PO 21.10.2026, hooks/variant.ts): the plugin name, its environment and the prefix of its local files. The
31// Production values give the names of 0.24.1 (0.24.2 adds the PROD marker, ruling R4); the Test build (kinitro-ai-test) gets its own names everywhere.
32// The host state (atom) keys must be string literals: the packager rewrites `plugin: 'kinitro-ai'` for the Test build.
33const F = VARIANT.files
34const PROBE_TOOL = `mcp__${VARIANT.name}__probe`
35const MARK = VARIANT.showEnv ? `${VARIANT.name} ${VARIANT.env}` : VARIANT.name // the prompt line marker: [kinitro-ai PROD 0.24.2] / [kinitro-ai-test TEST 0.24.2]
36const BRAND = VARIANT.showEnv ? `kinitro.ai ${VARIANT.env}` : 'kinitro.ai' // the band title
37const ENV_VAR = 'KINITRO_AI_ENV'
38// Everything is resolved from the seat (current-seat): no domain codes are hard-wired.
39const WARN_PCT = 70 // auto-compaction fires at 80 % in this environment
40const REWARN_STEP = 5 // warn again when the fill rises this many more points
41const MIRROR_PLATFORM = 'claude-code' // chat mirror (item 3413): turns go into the agent's kinitro.ai chat via mirror-messaging
42const OUTBOX_FILE = `${F}-outbox.json` // every turn is written here first, then sent; resending is safe (the verb ignores a repeat)
43const INBOX_FILE = `${F}-inbox.json` // new chat messages from kinitro.ai, told to the agent at its next prompt
44const BOX_MAX = 200
45const FETCH_MS = 60000
46const MAX_TEXT = 50000 // chars per prompt / answer sent to the chat
47const RETRY_MS = 20000 // retry a failed briefing load at most this often
48const LOG_FILE = `${F.replace(/^\./, '')}.log`
49const VERSION = '0.25.7'
50// update notice (PO 2026-10-16): at the first prompt, compare with the published marketplace.json on the download page
51const UPDATE_BASE = VARIANT.downloadBase // the download page; the environment variable KINITRO_AI_DOWNLOAD_BASE overrides it
52const UPDATE_TIMEOUT_MS = 2500
53const UPDATE_EVERY_MS = 24 * 3600 * 1000 // fetch at most once a day (timestamp in STATE_FILE); the last seen version is kept between checks
54const PENDING_VIEW_FILE = `${F}-pending` // written by the /kinitro fallback when the plugin was not running yet: finish the binding at the next prompt
55const REFRESH_MS = 24 * 3600 * 1000 // regular operation: instructions change rarely (PO 2026-10-08)
56const TEST_REFRESH_MS = 2 * 60 * 1000 // test mode (/kinitro test)
57const PAGE_TEXT_TOOLS = ['mcp__remote-devices__Claude_Browser__get_page_text', 'mcp__Claude_Browser__get_page_text']
58const BROWSER_TOOLS = ['mcp__remote-devices__Claude_Browser__preview_start', 'mcp__Claude_Browser__preview_start'] // the Claude app's browser pane (cloud session linked to the computer / desktop session)
59const SNAPSHOT_FILE = `${F}-selection.json` // approved slugs when the selection page was opened (selection-start)
60// Domain binding (kinitro.ai 2026-10-08): a connection may serve several domains; every call names its domain
61// with domainRef (the slug). The slug of this session lives in its session record (set it with probe action 'set-domain').
62// 0.20.0: the domain belongs to the SESSION, not to the current folder. A shell `cd` in the main session can move the
63// working directory, and the hook process may restart there. So each session has a record in a fixed place
64// (~/.kinitro-ai/sessions/<session id>.json) holding its home folder (the working folder of its first start) and its
65// domain. Every local file is read and written in that home folder, never in the current working directory.
66const DOMAIN_FILE = `${F}-domain` // folder default: the last domain chosen in this folder; a NEW session starts with it
67const SESSION_DOMAIN_PREFIX = `${F}-domain.` // + session id: written up to 0.19.x, still read once to adopt an older session's choice
68const SESSIONS_DIR = `${F}/sessions` // under the user's home directory: one record per session id
69const NO_DOMAIN_ARG = new Set(['current-seat', 'list-domains', 'open-domain']) // a server without session keys: verbs that take no domainRef
70// 0.24.0 (item 4.2.1-3590, PO 19.10.2026): the session key is mandatory. The plugin obtains it with open-domain when the
71// session binds, keeps it in $.state only (per Claude session; never in a file, the outbox, the log or $.store), adds it as
72// domainRef to every call of its own kinitro.ai server, the model's calls included, and never shows it to the model.
73const SESSION_KEY_PREFIX = 'kss_'
74const SESSION_KEY_RX = /kss_[A-Za-z0-9_-]+/g
75const KEY_HELD_TEXT = `[session key held by the ${VARIANT.name} plugin]`
76const KEY_NOTE = `The ${VARIANT.name} plugin holds this session and passes it on every kinitro.ai call; never pass domainRef yourself.`
77const KEYLESS_VERBS = new Set(['open-domain', 'list-domains', 'current-seat']) // answer without a key; never re-bound on their refusal
78const MAY_HAVE_RUN = 'The call may have run; check before repeating a write.' // confirmation review N2
79const REBIND_MS = 30000 // a refused key is replaced at most this often (one re-bind, no loop)
80const AGENT_FILE = `${F}/agent` // part 6: the agent node (id) this seat works as, in the PERSON's home folder only (fix round M3:
81 // never the project folder, never an environment variable a project's settings can set)
82const BUNDLED_RX = new RegExp(`^mcp__plugin_${VARIANT.name}_kinitro_ai__`) // the plugin's own server, exactly (fix round L1)
83// 0.25.0 (item 4.2.1-3910): the plugin's second own server, the device sign-in address /mcp/device (.mcp.json, no oauth block).
84// One of the two is the session's (its sign-in path); the other one's tools are refused and described as not used.
85const DEVICE_SERVER = 'kinitro_ai_device'
86const DEVICE_RX = new RegExp(`^mcp__plugin_${VARIANT.name}_kinitro_ai_device__`) // the own device server, exactly
87const OWN_RX = new RegExp(`^mcp__plugin_${VARIANT.name}_kinitro_ai(_device)?__`) // either own server (tool.call, tool.describe)
88// Each user message may start a fresh engine process while the kinitro.ai
89// connector is still connecting: the briefing and the hook state therefore
90// live in files that survive the restart, refreshed from kinitro.ai in the background.
91const CACHE_FILE = `${F}-briefing.json`
92const STATE_FILE = `${F}-state.json`
93const WAIT_FIRST_MS = 6000 // with no cache at all, wait this long for the connector
94// open UI comments (0.20.0): people comment on page controls in kinitro.ai; the agent learns about the open ones at its next prompt
95const COMMENTS_LIMIT = 20
96const COMMENTS_TIMEOUT_MS = 10000
97const COMMENTS_REMIND_MS = 30 * 60 * 1000 // the same open set is told again after this long
98const COMMENT_TEXT_MAX = 500
99
100// section names in the briefing
101const S = {
102 persona: 'Persona', rules: 'Working rules', start: 'Session start', turn: 'Every turn',
103 full: 'Context nearly full', after: 'After compaction', keep: 'Compaction instruction',
104} as const
105
106// ---- module state (resets on reload; session.start re-fills it) -----------
107type Briefing = { raw: string; sections: Record<string, string>; code: string; loadedAt: string; source: string; domainCode?: string; agentCode?: string; domainRef?: string; domainName?: string; agentName?: string; layers?: string }
108let briefing: Briefing | undefined
109let briefingError: string | undefined
110let lastLoadTry = 0
111let route = '-'
112let pending: PendingPrompt[] = [] // prompts of this turn that the person typed or another agent sent (item 3536)
113let warnedAt = 0
114let compactedPending = false
115let testArmed = false
116let lastInjected: string[] = []
117let composeCount = 0
118let lastMirrorError: string | undefined
119let compactions = 0
120let contextRenders = 0
121let personaSource = 'briefing document'
122let refreshing = false
123let refreshDone = false
124let domainRef: string | undefined // slug passed on every call; undefined = legacy seat-bound connection
125let bandRenders = 0
126let lastBandSurface = '-'
127let needsDomain: string | undefined // set when the connection serves several domains and no slug is configured
128// open UI comments: last check (module state), last injection (persisted in STATE_FILE, per session)
129type UiComment = { id: string; page?: { nodeId?: string; code?: string; title?: string }; control?: { id?: string; type?: string; label?: string }; controlState?: unknown; kind?: string; text?: string; createdAt?: string; status?: string; answer?: unknown; author?: { name?: string }; session?: { id?: string } }
130let openComments: UiComment[] = []
131let commentsTruncated = false
132let lastCommentCheck = '-'
133let lastCommentError: string | undefined
134let commentKey = '' // sorted ids of the open comments last told to the agent
135let commentInjectedAt = 0 // when they were told (ms)
136let commentSid = '' // in which session
137// todo list: hash of the list at its last FULL injection and in which session (persisted in STATE_FILE)
138let todoHash = ''
139let todoSid = ''
140// chat mirroring switch (PO 2026-10-16): off = no mirror-messaging call at all; persisted in STATE_FILE as mirror 'on'|'off', absent = on
141let mirrorOff = false
142// update notice: when the published marketplace.json was last fetched (ms) and the version it gave (persisted in STATE_FILE)
143let updateCheckedAt = 0
144let updateLatest = ''
145const logLines: string[] = []
146
147// ---- band state (host-held, survives module reloads) ----------------------
148const approvedA = atom({ plugin: 'kinitro-ai', key: 'approved' } as const, [] as DomainChoice[])
149const currentA = atom({ plugin: 'kinitro-ai', key: 'current' } as const, null as string | null)
150const chooserA = atom({ plugin: 'kinitro-ai', key: 'chooser' } as const, false)
151const selectorUrlA = atom({ plugin: 'kinitro-ai', key: 'selectorUrl' } as const, null as string | null)
152const bandNoteA = atom({ plugin: 'kinitro-ai', key: 'bandNote' } as const, null as string | null)
153const testModeA = atom({ plugin: 'kinitro-ai', key: 'testMode' } as const, false)
154const startPackA = atom({ plugin: 'kinitro-ai', key: 'startPack' } as const, false) // inject the session-start package on the next prompt (after binding a domain)
155const contextKeyA = atom({ plugin: 'kinitro-ai', key: 'contextKey' } as const, '') // domain + hash of persona/rules the agent last received
156const boundA = atom({ plugin: 'kinitro-ai', key: 'bound' } as const, null as string | null) // this session's slug, held by the host: survives reloads and a changed working folder
157const sessionKeyA = atom({ plugin: 'kinitro-ai', key: 'sessionKey' } as const, null as { sid: string; key: string } | null) // 0.24.0: this Claude session's kinitro.ai session key, host-held for this session only
158const secondNoticeA = atom({ plugin: 'kinitro-ai', key: 'secondNotice' } as const, false) // 0.24.0: the second connection was told in this session
159const headlessA = atom({ plugin: 'kinitro-ai', key: 'headless' } as const, false) // 0.24.3 (item 4.2.1-3696): this session is headless (isInteractive === false): the plugin stays inert; host-held, so a reload keeps it
160// 0.24.1 (item 4.2.1-3764): the approval this Claude session waits for, host-held so a reload never asks the server again
161const approvalA = atom({ plugin: 'kinitro-ai', key: 'approval' } as const, null as Approval | null)
162// 0.25.0 (item 4.2.1-3910): this Claude session's sign-in path (decided once per session) and its pending device sign-in, host-held
163const signInPathA = atom({ plugin: 'kinitro-ai', key: 'signInPath' } as const, null as SignInPathState | null)
164const signInA = atom({ plugin: 'kinitro-ai', key: 'signIn' } as const, null as SignIn | null)
165
166// ---- session key (0.24.0) -----------------------------------------------------
167let legacy = false // open-domain gave no session key: a server older than session keys; the slug goes in domainRef as before
168let binding = false // the plugin itself opens the session now (its own open-domain is no change by the agent)
169let keySlug: string | undefined // the domain the key's session works in, as far as this module knows
170let followSeat = false // the agent called open-domain itself: the binding follows the session's working domain
171let reloadDue = false // ... at the next prompt
172// 0.24.1 (item 4.2.1-3764): "approval needed" is a normal outcome. The plugin keeps the server's plain approvalUrl, the
173// domain and the agent (never the server's prose) and builds the label "Approve <Domain>" itself. The pending request is
174// looked at again only by checkApproval: open-domain {request} in the background (the server waits up to 25 s), single-
175// flight, started at each user turn, on "I approved it" and on set-domain/selection-done for the pending domain; never
176// awaited on a tool or turn path. No {domain} is sent again for the pending domain, so no second approval request.
177// An expired approval is dropped (heldApproval); any successful bind clears it (bindDomain).
178export type Approval = { sid: string; slug: string; request: string; url: string; domainName: string; agentName: string; expiresAt: string }
179const APPROVAL_FALLBACK_MS = 15 * 60 * 1000 // an answer without expiresAt: ask anew after this long
180let pendingApproval: Approval | undefined
181let keyEverHeld = false // fix round L5: once this session held a key it never falls back to the slug
182let rebindP: Promise<boolean> | undefined
183let lastRebind = 0
184let bindLock: Promise<unknown> = Promise.resolve()
185
186// $.state holds the key for the Claude session (it survives a reload and a compaction); the module keeps a mirror, because
187// every $.state read of one dispatch sees one moment and would miss a key written earlier in the same dispatch.
188// Fix round M1: the key is tied to the Claude session id, in $.state and in the mirror. A new session id (/clear, a second
189// session in the same engine process) resets every session-key value of the module and never sees the old key.
190let keyMirror: { sid: string; key: string | null } | undefined
191let stateSid: string | undefined
192function resetSessionKeyState() {
193 keyMirror = undefined; legacy = false; keyEverHeld = false; keySlug = undefined; pendingApproval = undefined
194 lastRebind = 0; followSeat = false; reloadDue = false; secondChecked = false
195 pathMirror = undefined; signInMirror = undefined; firstDeviceSid = undefined; toolPrefix = undefined; toolSource = undefined
196}
197async function syncSession($: any): Promise<string> {
198 let sid = ''
199 try { sid = String(await $.session.id()) } catch { /* no session id */ }
200 if (stateSid !== undefined && sid !== stateSid) resetSessionKeyState()
201 stateSid = sid
202 return sid
203}
204async function heldKey($: any): Promise<string | undefined> {
205 const sid = await syncSession($)
206 if (keyMirror?.sid === sid) return keyMirror.key ?? undefined
207 let v: any = null
208 try { v = await read($, sessionKeyA) } catch { return undefined }
209 const key = v && v.sid === sid && typeof v.key === 'string' ? v.key : null
210 keyMirror = { sid, key }
211 if (key) keyEverHeld = true
212 return key ?? undefined
213}
214async function keepKey($: any, key: string | null) {
215 const sid = await syncSession($)
216 keyMirror = { sid, key }
217 if (key) keyEverHeld = true
218 try { await update($, sessionKeyA, () => (key ? { sid, key } : null)) } catch { /* ignore */ }
219}
220
221/** The session key of an open-domain answer, or undefined. */
222export function sessionKeyOf(text: string): string | undefined {
223 try { const k = JSON.parse(text)?.sessionKey; return typeof k === 'string' && k.startsWith(SESSION_KEY_PREFIX) ? k : undefined } catch { return undefined }
224}
225
226/** The answer as the model may read it: no sessionKey, no sessionKeyMessage, no slug instruction, no kss_ value anywhere. */
227export function scrubKey(text: string): string {
228 let out = text
229 try {
230 const j = JSON.parse(text)
231 if (j && typeof j === 'object' && !Array.isArray(j) && j.status !== 'error' && ('sessionKey' in j || 'sessionKeyMessage' in j || /domainRef/.test(String(j.message ?? '')))) {
232 const { sessionKey: _k, sessionKeyMessage: _m, ...rest } = j
233 if (/domainRef/.test(String(rest.message ?? ''))) delete rest.message
234 out = JSON.stringify({ ...rest, session: KEY_NOTE })
235 }
236 } catch { /* not JSON: the pattern below still applies */ }
237 return out.replace(SESSION_KEY_RX, KEY_HELD_TEXT)
238}
239
240/** A refusal that means: this call has no valid session key (none, a slug in its place, unknown, of another sign-in). */
241export function isKeyRefusal(text: string): boolean {
242 return /session_key_required/.test(text) || (/domain_ref_unknown/.test(text) && /session key/i.test(text))
243}
244
245// a tool result as text, whatever its shape
246function resultText(r: any): string {
247 if (typeof r?.text === 'string') return r.text
248 if (typeof r?.result === 'string') return r.result
249 if (typeof r?.deny === 'string') return r.deny
250 return r?.result === undefined ? '' : JSON.stringify(r.result)
251}
252
253// the arguments of one call: the key on every call (current-seat and list-domains too); a server without keys: the slug as before
254function withSession(e: any, verb: string, key: string | undefined): any {
255 if (key) return { ...e, domainRef: key }
256 if (legacy && domainRef && e.domainRef === undefined && !NO_DOMAIN_ARG.has(verb)) return { ...e, domainRef }
257 return e
258}
259
260// part 6: the agent node this seat works as, from the seat's own setting; undefined = the domain's default
261async function seatAgent($: any): Promise<string | undefined> {
262 let userHome: string | undefined
263 try { userHome = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) } catch { /* ignore */ }
264 if (!userHome) return undefined
265 const v = await readFileTrim($, joinPath(userHome, AGENT_FILE))
266 if (!v) return undefined
267 if (/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(v)) return v
268 await log($, `seat setting ~/${AGENT_FILE} is not an agent node id: ignored`)
269 return undefined
270}
271
272function serial<T>(f: () => Promise<T>): Promise<T> {
273 const p = bindLock.then(f, f)
274 bindLock = p.catch(() => undefined)
275 return p
276}
277
278/** The approval out of a seat_approval_required answer (R1): the plain approvalUrl; the URL inside a Markdown approvalLink
279 * only when approvalUrl is absent. The label is built from to.domain, never from approvalLinkText. */
280export function approvalFromAnswer(a: any, slug: string, sid: string, now = Date.now()): Approval {
281 const md = /\]\((\S+?)\)/.exec(String(a?.approvalLink ?? ''))
282 const url = String(a?.approvalUrl ?? md?.[1] ?? '')
283 const exp = Date.parse(String(a?.expiresAt ?? ''))
284 return { sid, slug, request: String(a?.request ?? ''), url, domainName: String(a?.to?.domain ?? slug), agentName: String(a?.to?.agentNode ?? ''), expiresAt: new Date(Number.isNaN(exp) ? now + APPROVAL_FALLBACK_MS : exp).toISOString() }
285}
286
287/** The label of the approval link the person sees in the band and the chat. */
288export function approveLabel(a: Pick<Approval, 'domainName'>): string { return `Approve ${a.domainName}` }
289
290/** What set-domain and selection-done answer while the approval is pending (R3). */
291export function approvalResult(a: Approval) {
292 return {
293 status: 'approval_needed', bound: false, domain: a.domainName, agent: a.agentName || null, approvalLink: a.url || null, label: approveLabel(a),
294 sayToUser: `kinitro.ai needs your approval for ${a.domainName}. I also tried to open it in the browser pane; it may stay hidden.`,
295 next: 'After the approval, confirm here; then call set-domain again.',
296 }
297}
298
299/** The per-turn block while an approval is pending (R8, exact text). */
300export function approvalContextBlock(a: Approval): string {
301 return `kinitro.ai: ${a.domainName} waits for the user's approval. In your first reply give the link [${approveLabel(a)}](${a.url}) as a Markdown link, say the plugin also tried the browser pane, and ask the user to confirm here after approving.`
302}
303
304class ApprovalNeeded extends Error {
305 name = 'ApprovalNeeded'
306 constructor(public approval: Approval) { super(`waiting for the approval of ${approval.domainName}`) }
307}
308
309function approvalExpired(a: Approval, now = Date.now()): boolean { return Date.parse(a.expiresAt) <= now }
310
311// the pending approval of this Claude session (module mirror, else the host); a new session id never sees the old one
312async function heldApproval($: any): Promise<Approval | undefined> {
313 const sid = await syncSession($)
314 if (pendingApproval?.sid === sid && !approvalExpired(pendingApproval)) return pendingApproval
315 let v: Approval | null = null
316 try { v = await read($, approvalA) } catch { /* ignore */ }
317 pendingApproval = v && v.sid === sid ? v : undefined
318 if (pendingApproval && approvalExpired(pendingApproval)) { // review F2: an expired request is no pending approval
319 const gone = pendingApproval
320 await keepApproval($, null)
321 try { await update($, bandNoteA, () => `Approval for ${gone.domainName} was expired. Choose the domain again.`) } catch { /* ignore */ }
322 try { await log($, `approval for ${gone.slug}: expired`) } catch { /* ignore */ }
323 }
324 return pendingApproval
325}
326async function keepApproval($: any, a: Approval | null) {
327 pendingApproval = a ?? undefined
328 try { await update($, approvalA, () => a) } catch { /* ignore */ }
329}
330
331// R3: a binding probe action answers within this budget; the binding goes on in the background
332const TOOL_BUDGET_MS = 8000
333const OVER = Symbol('over')
334const STILL_BINDING = { status: 'binding', message: 'Still binding in the background; the band shows the result. Call set-domain again in a moment.' }
335async function withBudget<T>($: any, p: Promise<T>, ms: number): Promise<T | typeof OVER> {
336 const stop = new AbortController()
337 try {
338 return await Promise.race([p, $.clock.sleep(ms, { signal: stop.signal }).then(() => OVER, () => new Promise<never>(() => {}))])
339 } finally { stop.abort() }
340}
341
342// R2: the re-check of a pending approval. Single-flight, outside serial, started and never awaited on a tool or turn path:
343// open-domain {request} answers within a second of the yes, else pending after up to 25 s on the server.
344let checkP: Promise<void> | undefined
345// round 2: the check never touches `binding` (openSession's flag, under serial). Sharing it made an agent's own open-domain
346// during an open check count as the plugin's, and a check ending during a bind cleared that bind's flag. The hook knows the
347// check's own call by its request handle instead (ownRequests), so only that one call is the plugin's.
348const ownRequests = new Set<string>()
349function checkApproval($: any): Promise<void> {
350 if (checkP) return checkP
351 checkP = (async () => {
352 try {
353 const ap = await heldApproval($)
354 if (!ap?.request) return
355 let r: any
356 ownRequests.add(ap.request)
357 try { r = await mcp($, 'open-domain', { request: ap.request }) } finally { ownRequests.delete(ap.request) }
358 const st = String(r?.status ?? '')
359 if (st === 'approved' || st === 'moved') {
360 await keepApproval($, null)
361 await log($, `approval for ${ap.slug}: ${st}; binding`)
362 await bindDomain($, ap.slug)
363 } else if (st === 'denied' || st === 'expired') {
364 await keepApproval($, null)
365 await update($, bandNoteA, () => `Approval for ${ap.domainName} was ${st}. Choose the domain again.`)
366 await log($, `approval for ${ap.slug}: ${st}`)
367 }
368 } catch (err: any) { await log($, `approval check failed: ${String(err?.message ?? err).slice(0, 200)}`) }
369 finally { checkP = undefined }
370 })()
371 return checkP
372}
373
374// P1/P5: start this Claude session's kinitro.ai session in a domain (no key yet: open-domain mints one), or add the domain
375// to the session (with the key: no new key). A domain the sign-in has not approved goes through the approval link first.
376async function openSession($: any, pick: { slug?: string; id?: string }): Promise<any> {
377 return serial(async () => {
378 binding = true
379 try {
380 const doms = await mcp($, 'list-domains', {})
381 const d = (doms?.domains ?? []).find((x: any) => (pick.id ? String(x.id) === pick.id : x.slug === pick.slug))
382 if (!d) throw new Error(pick.id ? `domain ${pick.id} not found in list-domains` : `domain slug '${pick.slug}' not found in list-domains`)
383 const slug = String(d.slug)
384 const held = await heldKey($)
385 if (held && keySlug === slug) return d
386 const agent = await seatAgent($)
387 // R4: the pending request is reused ({request}); a new {domain} is never sent for the pending slug, and never while
388 // checkApproval asks for the same request (no two open-domain calls at once)
389 const held0 = await heldApproval($)
390 const pend = held0?.slug === slug ? held0 : undefined
391 if (pend && checkP) throw new ApprovalNeeded(pend)
392 let r: any
393 try {
394 r = await mcp($, 'open-domain', pend ? { request: pend.request } : { domain: String(d.id), ...(agent ? { agent } : {}) })
395 } catch (err: any) {
396 const a = err?.answer
397 if (a?.code === 'seat_approval_required' && a?.request) {
398 const ap = approvalFromAnswer(a, slug, await syncSession($))
399 await keepApproval($, ap)
400 throw new ApprovalNeeded(ap)
401 }
402 if (pend) await keepApproval($, null)
403 throw err
404 }
405 if (r?.status === 'pending' && pend) throw new ApprovalNeeded(pend)
406 if (pend) await keepApproval($, null)
407 if (r?.status === 'denied' || r?.status === 'expired' || r?.status === 'pending') throw new Error(`the person did not approve ${slug} (${r.status})`)
408 const key = await heldKey($)
409 if (!key && keyEverHeld) throw new Error(`open-domain gave no session key although this session held one: not switched to the domain slug`)
410 legacy = !key // LEGACY (remove in the release after the server enforces the key): a server older than session keys
411 keySlug = key ? slug : undefined
412 await log($, key ? `session ${held ? 'now also works in' : 'started in'} ${slug}${agent ? ' at the agent node of the seat setting' : ''}` : `open-domain gave no session key: a server without session keys; the domain goes on every call as before`)
413 return d
414 } finally { binding = false }
415 })
416}
417
418// P7: a refused key (or none) is replaced once by a new session in the session's domain; at most once per REBIND_MS
419async function rebindOnce($: any): Promise<boolean> {
420 // R8 (0.25.0): the device address refuses open-domain without a key: the key is dropped and the sign-in ends instead
421 if ((await pathNow($)) === 'device') {
422 if ((await heldKey($)) || (await heldSignIn($))) await endSignIn($, 'the session key was refused')
423 return false
424 }
425 if (binding) return false
426 if (rebindP) return rebindP
427 const now = Date.now()
428 if (now - lastRebind < REBIND_MS) return false
429 lastRebind = now
430 rebindP = (async () => {
431 try {
432 const slug = domainRef ?? (await readDomainFile($))
433 if (!slug) return false
434 await keepKey($, null); keySlug = undefined
435 await openSession($, { slug })
436 const ok = !!(await heldKey($))
437 await log($, ok ? `re-bound: a new session in ${slug}` : `re-bind in ${slug} gave no session key`)
438 return ok
439 } catch (err: any) { await log($, `re-bind failed: ${String(err?.message ?? err).slice(0, 300)}`); return false }
440 finally { rebindP = undefined }
441 })()
442 return rebindP
443}
444
445// ---- device sign-in (0.25.0, item 4.2.1-3910) -----------------------------------
446// Q4 (T13, PO 21.10.2026): "OAuth when the session is local and interactive, device path otherwise; the plugin decides, the
447// person does nothing." The path is decided once per Claude session (session.start, else at the first hook that needs it) and
448// held in $.state. On the device path the plugin signs in itself: sign-in on /mcp/device with the person's email (the setting,
449// else asked through the agent once), the pending key held like any session key (never shown), the approval page link in
450// the band and the turn. The re-check runs at each user turn, on "I approved it" and on the probe action sign-in-check; no
451// timer, no new sign-in by itself after an end (concept 8.1 not ruled). The server's prose never reaches the model or the band.
452export type SignInPath = 'oauth' | 'device'
453export type SignInPathState = { sid: string; path: SignInPath; reason: string }
454export type SignIn = { sid: string; url: string; mask: string; expiresAt: string; requestedAt: number }
455const PATH_MARKERS = ['SSH_CONNECTION', 'SSH_CLIENT', 'SSH_TTY'] as const
456const RESEND_MS = 60_000
457const SIGNIN_ENDED = 'The kinitro.ai sign-in ended.'
458const SIGNIN_FAILED_RX = /^kinitro\.ai sign-in failed/ // 0.25.7: a note starts like this and the reason follows (failNote)
459const DEVICE_UNAVAILABLE = `kinitro.ai sign-in by email code is not available here; type /${VARIANT.command} domain to sign in.`
460const RATE_NOTE_RX = /^Too many sign-in requests\./
461// 0.25.7 (item 4.2.1-3910): the reason a sign-in failed, in plain words. 0.25.6 swallowed it into one fixed sentence; the person
462// could not tell "the plugin refused its own call" from "kinitro.ai is down". The text is the plugin's own wording; a host or
463// server detail is cut to 140 characters and holds no key (scrubKey).
464export function plainReason(raw: string): string {
465 const t = String(raw ?? '').replace(/\s+/g, ' ').trim()
466 const clean = scrubKey(t)
467 const detail = clean.slice(0, 140)
468 if (/refused:|\$\.mcp\.call: /.test(t)) return `Claude Code refused the plugin's own sign-in call (${clean.replace(/^.*?(refused:|\$\.mcp\.call:)\s*/, '').slice(0, 140) || 'no reason given'})`
469 if (/ECONN|ENOTFOUND|EAI_AGAIN|fetch failed|network|certificate|TLS|SSL/i.test(t)) return `this computer cannot reach kinitro.ai (${detail})`
470 if (/timed? ?out|timeout/i.test(t)) return 'kinitro.ai did not answer in time; try again in a minute'
471 if (/no connected MCP server|not connected/i.test(t)) return `the kinitro.ai device server is not connected in this Claude session (${detail})`
472 return `the sign-in call failed (${detail || 'no detail'})`
473}
474export function plainCode(code: string | undefined, isError: boolean): string {
475 if (code === 'sign_in_rate_limited') return 'too many sign-in requests; wait a few minutes'
476 if (code === 'session_key_required') return 'kinitro.ai wants a sign-in first and gave no session key'
477 if (code) return `kinitro.ai answered the sign-in with the error code ${String(code).slice(0, 60)}`
478 return isError ? 'kinitro.ai answered the sign-in with an error and no code' : 'kinitro.ai answered the sign-in without a session key'
479}
480const failNote = (reason: string) => `kinitro.ai sign-in failed: ${reason}.`
481export const DEVICE_HINT = `Run /${VARIANT.command} sign-in`
482const EMAIL_ASK = `kinitro.ai sign-in: ask the user, in one short question in chat, for the email address of their kinitro.ai account, then call \`${PROBE_TOOL}\` with {"action": "sign-in", "email": "<address>"}. Never ask for a password or a code.`
483const CODE_TYPED = 'The user typed what looks like the sign-in code here. Tell them to type it only on the kinitro.ai page; do not repeat it.'
484const MODEL_SIGN_IN = `The ${VARIANT.name} plugin signs in itself: call ${PROBE_TOOL} with {"action": "sign-in"}.`
485
486/** R1: the sign-in path. The setting oauth or device wins; auto (or none): device when an SSH variable is set or
487 * CLAUDE_CODE_REMOTE is true, else OAuth. The reason names the setting or the variable, never a value. */
488export function chooseSignInPath(setting: string | undefined, env: Record<string, string | undefined>): { path: SignInPath; reason: string } {
489 const want = String(setting ?? '').trim().toLowerCase()
490 if (want === 'oauth' || want === 'device') return { path: want, reason: `setting signInPath=${want}` }
491 for (const name of PATH_MARKERS) if (String(env[name] ?? '').trim()) return { path: 'device', reason: name }
492 if (String(env.CLAUDE_CODE_REMOTE ?? '').trim().toLowerCase() === 'true') return { path: 'device', reason: 'CLAUDE_CODE_REMOTE' }
493 return { path: 'device', reason: 'default: the email-code sign-in; no localhost callback' } // 0.25.5: auto means device
494}
495
496/** The tool prefix of a build's device server: each build's prefix matches only its own device server. */
497export function devicePrefixFor(buildName: string): string { return `mcp__plugin_${buildName}_kinitro_ai_device__` }
498
499/** The mask of an address as the plugin shows and logs it: the first character, ***, @domain. */
500export function emailMask(email: string): string {
501 const t = String(email).trim(), at = t.indexOf('@')
502 return at < 0 ? '***' : `${t.slice(0, 1)}***${t.slice(at)}`
503}
504
505/** The device label sent with sign-in: COMPUTERNAME, else HOSTNAME, else "unknown device", cut to 80. */
506export function deviceLabel(env: Record<string, string | undefined>): string {
507 return (String(env.COMPUTERNAME ?? '').trim() || String(env.HOSTNAME ?? '').trim() || 'unknown device').slice(0, 80)
508}
509
510/** A prompt that is exactly six digits after trimming (what a sign-in code looks like). */
511export function isSixDigits(text: string): boolean { return /^\d{6}$/.test(String(text).trim()) }
512
513/** R3: an address the probe action sign-in accepts: exactly one @, at most 254 characters (trimmed). */
514function emailOk(email: string): boolean { return email.length <= 254 && email.split('@').length === 2 }
515
516/** R5: the per-turn block while the sign-in waits for the approval (exact text). */
517export function signInContextBlock(si: Pick<SignIn, 'url' | 'mask'>): string {
518 return `kinitro.ai sign-in waits for the user's approval. In your first reply give the link [Approve this sign-in](${si.url}) as a Markdown link and say: a 6-digit code was sent to ${si.mask}; type it only on that kinitro.ai page, on any device, never in this chat; then send any message here. Never ask for the code.`
519}
520
521/** R5: what a kinitro.ai call answers while the sign-in is pending, built by the plugin (no server text). */
522export function signInResult(si: Pick<SignIn, 'url' | 'mask'>) {
523 return {
524 status: 'sign_in_pending', approvalLink: si.url || null, label: 'Approve this sign-in',
525 sayToUser: `A 6-digit code was sent to ${si.mask}. Type it only on the kinitro.ai page behind the link, on any device, never in this chat; then send any message here.`,
526 }
527}
528
529let options: Record<string, unknown> = {} // the userConfig values of this load (register(on, options)); a change reloads the module
530let pathMirror: SignInPathState | undefined
531let signInMirror: { sid: string; value: SignIn | null } | undefined
532let ownSignInCall = false // 0.25.7: true only while signInNow makes its own device sign-in call (the host shows it to this plugin's own tool.call hook)
533let lastSignInFailure: { at: string; reason: string } | undefined // 0.25.7: what /kinitro status says about the last failed sign-in
534let firstDeviceSid: string | undefined // the Claude session whose first user turn on the device path was seen (R3, R4)
535let deviceServerName: string | undefined
536let signInP: Promise<any> | undefined
537let checkSignInP: Promise<void> | undefined
538
539function settingOf(field: 'signInPath' | 'email'): string {
540 const v = options[field]
541 return typeof v === 'string' ? v.trim() : ''
542}
543function ownPrefix(path: SignInPath): string { return path === 'device' ? DEVICE_PREFIX : BUNDLED_PREFIX }
544function hintFor(path: SignInPath | undefined): string { return path === 'device' ? DEVICE_HINT : AUTH_HINT }
545
546// the environment variables the path rule and the device label read ($.env.get takes a literal name)
547async function envValue(read: () => Promise<unknown>): Promise<string | undefined> {
548 try { const v = await read(); return typeof v === 'string' ? v : undefined } catch { return undefined }
549}
550async function pathEnv($: any): Promise<Record<string, string | undefined>> {
551 return {
552 SSH_CONNECTION: await envValue(() => $.env.get('SSH_CONNECTION')), SSH_CLIENT: await envValue(() => $.env.get('SSH_CLIENT')),
553 SSH_TTY: await envValue(() => $.env.get('SSH_TTY')), CLAUDE_CODE_REMOTE: await envValue(() => $.env.get('CLAUDE_CODE_REMOTE')),
554 }
555}
556async function labelEnv($: any): Promise<Record<string, string | undefined>> {
557 return { COMPUTERNAME: await envValue(() => $.env.get('COMPUTERNAME')), HOSTNAME: await envValue(() => $.env.get('HOSTNAME')) }
558}
559async function nowMs($: any): Promise<number> {
560 try { return Number(await $.clock.now()) } catch { return Date.now() }
561}
562function clockText(ms: number): string {
563 const d = new Date(ms), p = (n: number) => String(n).padStart(2, '0')
564 return `${p(d.getHours())}:${p(d.getMinutes())}`
565}
566
567// changed: the path moves after the first decision (fallback, escape): the tool descriptions are rendered again
568async function setPath($: any, path: SignInPath, reason: string, changed = true) {
569 const sid = await syncSession($)
570 pathMirror = { sid, path, reason }
571 toolPrefix = undefined; toolSource = undefined
572 try { await update($, signInPathA, () => pathMirror!) } catch { /* ignore */ }
573 if (changed) { try { $.ui.invalidate('tool.describe') } catch { /* ignore */ } }
574 await log($, `sign-in path ${path} (${reason})`)
575}
576
577/** 0.25.6: a stored oauth path is stale unless the person chose oauth by setting (the plugin brings no OAuth server any more). */
578export function staleOauthPath(stored: string, setting: string): boolean { return stored === 'oauth' && String(setting).trim().toLowerCase() !== 'oauth' }
579
580// R1: this Claude session's path; decided once (host-held, a reload keeps it)
581async function pathState($: any): Promise<SignInPathState> {
582 const sid = await syncSession($)
583 if (pathMirror?.sid === sid) return pathMirror
584 let v: SignInPathState | null = null
585 try { v = await read($, signInPathA) } catch { /* ignore */ }
586 if (v && v.sid === sid) {
587 // 0.25.6: a session started on 0.25.0 to 0.25.4 holds path oauth (state key signInPath, host-held, kept by --resume and /reload-plugins).
588 // 0.25.5 removed the OAuth server, so that binding points at nothing: unless the person chose oauth by setting, the session moves
589 // to the device path, and the key of the old server is dropped so the email-code sign-in can start.
590 if (staleOauthPath(v.path, settingOf('signInPath'))) {
591 await setPath($, 'device', 'migrated: the OAuth server is gone', true)
592 try { await keepKey($, null) } catch { /* ignore */ }
593 keySlug = undefined; briefing = undefined; domainRef = undefined; legacy = false
594 try { await keepSignIn($, null); await update($, bandNoteA, () => null) } catch { /* ignore */ }
595 return pathMirror!
596 }
597 pathMirror = v; return v
598 }
599 const c = chooseSignInPath(settingOf('signInPath'), await pathEnv($))
600 await setPath($, c.path, c.reason, false)
601 return pathMirror!
602}
603async function pathNow($: any): Promise<SignInPath> { return (await pathState($)).path }
604
605async function heldSignIn($: any): Promise<SignIn | undefined> {
606 const sid = await syncSession($)
607 if (signInMirror?.sid === sid) return signInMirror.value ?? undefined
608 let v: SignIn | null = null
609 try { v = await read($, signInA) } catch { /* ignore */ }
610 const value = v && v.sid === sid ? v : null
611 signInMirror = { sid, value }
612 return value ?? undefined
613}
614async function keepSignIn($: any, si: SignIn | null) {
615 const sid = await syncSession($)
616 signInMirror = { sid, value: si }
617 try { await update($, signInA, () => si) } catch { /* ignore */ }
618}
619
620// the device path holds no usable key yet: nothing but the sign-in and its check runs (no briefing, no seat, no mirror)
621async function signInWaiting($: any): Promise<boolean> {
622 if ((await pathNow($)) !== 'device') return false
623 return !(await heldKey($)) || !!(await heldSignIn($))
624}
625
626// R6/R8: the key and the pending sign-in are dropped; the band says so and offers "Sign in again"; nothing starts by itself
627async function endSignIn($: any, why: string) {
628 await keepSignIn($, null)
629 await keepKey($, null); keySlug = undefined
630 briefing = undefined; domainRef = undefined
631 try { await update($, currentA, () => null); await update($, chooserA, () => false); await update($, bandNoteA, () => SIGNIN_ENDED) } catch { /* ignore */ }
632 await log($, `sign-in ended: ${why}`)
633}
634
635// R1 fallback: the device server of this build, connected; else the session goes to the OAuth path with the note
636async function deviceServer($: any): Promise<string | undefined> {
637 if (deviceServerName) return deviceServerName
638 let c: any
639 try { c = await $.mcp.connect(DEVICE_SERVER) } catch (err: any) { c = { isConnected: false, reason: String(err?.message ?? err).slice(0, 80) } }
640 if (c?.isConnected) { deviceServerName = String(c.server || `plugin_${VARIANT.name}_${DEVICE_SERVER}`); return deviceServerName }
641 await log($, `device server not connected: ${c?.reason ?? 'unknown'}`) // 0.25.6: stays on the device path (no OAuth server exists); the next call connects again
642 lastSignInFailure = { at: new Date().toISOString(), reason: `the kinitro.ai device server did not connect (${String(c?.reason ?? 'no reason given').slice(0, 100)})` }
643 try { await update($, bandNoteA, () => DEVICE_UNAVAILABLE) } catch { /* ignore */ }
644 return undefined
645}
646
647// one call on the device server through the direct route (no hook sees it): sign-in and the plugin's own re-check
648async function deviceCall($: any, server: string, tool: string, args: Record<string, unknown>): Promise<{ text: string; isError: boolean; answer: any }> {
649 const r = await $.mcp.call(server, tool, args)
650 const text = (r?.content ?? []).map((b: any) => (b?.type === 'text' ? b.text : '')).join('')
651 let answer: any
652 try { answer = JSON.parse(text) } catch { /* not JSON */ }
653 return { text, isError: !!r?.isError, answer }
654}
655
656// R4/R7: sign-in on the device server. Single-flight; a pending sign-in younger than 60 s sends nothing; a resend carries the
657// pending key as domainRef and keeps it. The answer's key is held, its prose dropped; the mask is the plugin's own.
658function signInNow($: any): Promise<any> {
659 if (signInP) return signInP
660 signInP = (async () => {
661 try {
662 const email = settingOf('email')
663 if (!email) return { status: 'error', message: `No kinitro.ai account email is set. Ask the user for it, then call ${PROBE_TOOL} with {"action": "sign-in", "email": "<address>"}.` }
664 const si = await heldSignIn($)
665 const key = await heldKey($)
666 if (key && !si) return { status: 'signed_in', message: 'This session is signed in to kinitro.ai.' }
667 const now = await nowMs($)
668 if (si && now < si.requestedAt + RESEND_MS) return { status: 'too_soon', message: `A new code can be sent from ${clockText(si.requestedAt + RESEND_MS)}.` }
669 const server = await deviceServer($)
670 if (!server) return { status: 'error', message: DEVICE_UNAVAILABLE }
671 const env = await labelEnv($)
672 const args = { email, deviceLabel: deviceLabel(env), clientName: `Claude Code, ${VARIANT.name} ${VERSION}`.slice(0, 60), ...(si && key ? { domainRef: key } : {}) }
673 let r: { text: string; isError: boolean; answer: any }
674 try { ownSignInCall = true; r = await deviceCall($, server, 'sign-in', args) } catch (err: any) {
675 const why = plainReason(String(err?.message ?? err))
676 await log($, `sign-in failed: ${String(err?.message ?? err).slice(0, 300)}`)
677 lastSignInFailure = { at: new Date().toISOString(), reason: why }
678 await update($, bandNoteA, () => failNote(why))
679 return { status: 'error', message: failNote(why) }
680 } finally { ownSignInCall = false }
681 const a = r.answer
682 if (a?.code === 'sign_in_rate_limited') {
683 const note = `Too many sign-in requests. Try again in ${Math.max(1, Math.ceil(Number(a.retryAfterSeconds ?? 60) / 60))} minutes.`
684 await update($, bandNoteA, () => note)
685 await log($, `sign-in refused: sign_in_rate_limited (retry after ${Number(a.retryAfterSeconds ?? 0)} s)`)
686 return { status: 'error', message: note }
687 }
688 const k = r.isError ? undefined : sessionKeyOf(r.text)
689 if (!k || a?.status !== 'pending') {
690 await log($, `sign-in failed: ${String(a?.code ?? (r.isError ? 'error answer' : 'no session key in the answer')).slice(0, 80)}`)
691 const why = plainCode(a?.code ? String(a.code) : undefined, r.isError)
692 lastSignInFailure = { at: new Date().toISOString(), reason: why }
693 await update($, bandNoteA, () => failNote(why))
694 return { status: 'error', message: failNote(why) }
695 }
696 lastSignInFailure = undefined
697 await keepKey($, k); legacy = false; keySlug = undefined
698 const md = /\]\((\S+?)\)/.exec(String(a?.approvalLink ?? ''))
699 const next: SignIn = { sid: await syncSession($), url: String(a?.approvalUrl ?? md?.[1] ?? ''), mask: emailMask(email), expiresAt: String(a?.expiresAt ?? ''), requestedAt: now }
700 await keepSignIn($, next)
701 try { await update($, bandNoteA, () => null); await update($, currentA, () => null) } catch { /* ignore */ }
702 await log($, `sign-in: a code was sent to ${next.mask}${si ? ' again (same session key)' : ''}`)
703 return signInResult(next)
704 } finally { signInP = undefined }
705 })()
706 return signInP
707}
708
709// R6: the re-check of a pending sign-in: current-seat with the key. Pending: nothing changes. Ready: the domain and agent of
710// the seat answer are bound (bindDomain, the briefing, the held turns). Unknown key: the sign-in ended. Single-flight.
711function checkSignIn($: any): Promise<void> {
712 if (checkSignInP) return checkSignInP
713 checkSignInP = (async () => {
714 try {
715 const si = await heldSignIn($)
716 const key = await heldKey($)
717 if (!si || !key) return
718 const server = await deviceServer($)
719 if (!server) return
720 const r = await deviceCall($, server, 'current-seat', { domainRef: key })
721 const code = String(r.answer?.code ?? '')
722 if (code === 'sign_in_pending') return
723 if (code === 'domain_ref_unknown' || isKeyRefusal(r.text)) { await endSignIn($, code || 'the session key was refused'); return }
724 const dom = r.answer?.domain
725 if (r.isError || !dom?.id) { await log($, `sign-in check: no seat in the answer (${code || 'no code'})`); return }
726 await keepSignIn($, null)
727 let slug = typeof dom.slug === 'string' ? dom.slug : ''
728 if (!slug) slug = String(((await mcp($, 'list-domains', {}))?.domains ?? []).find((x: any) => String(x.id) === String(dom.id))?.slug ?? '')
729 if (!slug) { await log($, 'sign-in approved, but the working domain is not in list-domains'); lastSignInFailure = { at: new Date().toISOString(), reason: 'the domain you approved is not in your list of domains' }; await update($, bandNoteA, () => failNote('the domain you approved is not in your list of domains')); return }
730 await log($, `sign-in approved: this session works in ${slug}`)
731 await bindDomain($, slug)
732 } catch (err: any) { await log($, `sign-in check failed: ${String(err?.message ?? err).slice(0, 200)}`) }
733 finally { checkSignInP = undefined }
734 })()
735 return checkSignInP
736}
737
738// ---- the session's home folder and record (0.20.0) ---------------------------
739type SessionRecord = { sessionId: string; home: string; domain?: string | null; startedAt: string; updatedAt?: string }
740let homeDir: string | undefined // the session's home folder: every local file lives here
741let recordPath: string | null | undefined // ~/.kinitro-ai/sessions/<sid>.json; null when there is no user home or session id
742let sessionRecord: SessionRecord | undefined
743let lastSeenCwd: string | undefined
744
745function joinPath(dir: string, name: string): string {
746 return /[\\/]$/.test(dir) ? dir + name : `${dir}/${name}`
747}
748
749// the record of this session in the fixed place; created at the first start with the working folder of that moment
750async function sessionHome($: any): Promise<string> {
751 if (homeDir) return homeDir
752 let sid = '', cwd = '.', userHome: string | undefined
753 try { sid = await $.session.id() } catch { /* ignore */ }
754 // the project root first: a shell `cd` does not move it; the working directory only where there is none
755 try { cwd = (await $.session.root()) || (await $.session.cwd()) } catch { try { cwd = await $.session.cwd() } catch { /* ignore */ } }
756 try { userHome = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) } catch { /* ignore */ }
757 recordPath = sid && userHome ? joinPath(joinPath(userHome, SESSIONS_DIR), `${sid}.json`) : null
758 if (recordPath) {
759 try { if (await $.fs.exists(recordPath)) sessionRecord = JSON.parse(String(await $.fs.read(recordPath))) as SessionRecord } catch { sessionRecord = undefined }
760 if (!sessionRecord?.home) {
761 sessionRecord = { sessionId: sid, home: cwd, domain: null, startedAt: new Date().toISOString() }
762 try { await $.fs.write(recordPath, JSON.stringify(sessionRecord)) } catch { /* ignore */ }
763 }
764 }
765 homeDir = sessionRecord?.home ?? cwd
766 lastSeenCwd = homeDir
767 return homeDir
768}
769
770// absolute path of a local file in the session's home folder
771async function at($: any, name: string): Promise<string> {
772 return joinPath(await sessionHome($), name)
773}
774
775async function saveRecordDomain($: any, slug: string) {
776 await sessionHome($)
777 if (!recordPath || !sessionRecord) return
778 sessionRecord = { ...sessionRecord, domain: slug, updatedAt: new Date().toISOString() }
779 try { await $.fs.write(recordPath, JSON.stringify(sessionRecord)) } catch { /* ignore */ }
780}
781
782// a changed working folder never changes the binding: log it once per folder, with that folder's default if it differs
783async function noteCwd($: any) {
784 const home = await sessionHome($)
785 let cwd: string | undefined
786 try { cwd = await $.session.cwd() } catch { return }
787 if (!cwd || cwd === lastSeenCwd) return
788 lastSeenCwd = cwd
789 if (cwd === home) { await log($, `working folder back to the session home ${home}`); return }
790 const other = await readFileTrim($, joinPath(cwd, DOMAIN_FILE))
791 await log($, `working folder changed to ${cwd}${other ? ` (folder default ${other})` : ''}; the session keeps ${sessionRecord?.domain ?? domainRef ?? 'its binding'} and its files in ${home}`)
792}
793
794// ---- helpers: top level, because the engine only lets $ flow into these ----
795async function log($: any, line: string) {
796 logLines.push(`${new Date().toISOString()} ${scrubKey(line)}`) // fix round L2: no key in the log, whatever the line carries
797 try { await $.fs.write(await at($, LOG_FILE), logLines.join('\n') + '\n') } catch { /* ignore */ }
798}
799
800// kinitro.ai call through the engine's tool path (same route as the model's own
801// tool calls), falling back to the direct MCP route.
802// Where the kinitro.ai tools come from (0.21.0), best first:
803// bundled the plugin's own MCP server (.mcp.json): mcp__plugin_kinitro-ai_kinitro_ai__<verb>
804// user a server of the user named kinitro_ai: mcp__kinitro_ai__<verb>
805// connector the claude.ai connector inside Claude Code: mcp__claude_ai_Kinitro__<verb>
806// other any other server that has a current-seat tool and "kinitro" or "methos" in its name
807export type KinitroSource = 'bundled' | 'user' | 'connector' | 'other'
808const BUNDLED_PREFIX = `mcp__plugin_${VARIANT.name}_kinitro_ai__`
809const DEVICE_PREFIX = devicePrefixFor(VARIANT.name) // 0.25.0: the own device server's tools
810const USER_PREFIX = `mcp__${SERVER}__`
811const CONNECTOR_PREFIX = 'mcp__claude_ai_Kinitro__'
812const SEAT_VERB = 'current-seat'
813const SOURCE_LABEL: Record<KinitroSource, string> = { bundled: 'bundled plugin server', user: 'user server', connector: 'claude.ai connector', other: 'other server' }
814export const AUTH_HINT = `Type /${VARIANT.command} domain to sign in`
815// 0.25.6: what the probe says when no kinitro.ai tool is usable. It says what is missing and the probe's own step, never "type /kinitro" (the answer is read inside that command: a loop)
816export const SIGNIN_NEEDED = `not signed in to kinitro.ai yet; the email-code sign-in starts with ${PROBE_TOOL} action sign-in`
817const noTools = (_path: SignInPath) => `no kinitro.ai tools are visible in this session: ${SIGNIN_NEEDED}.`
818
819// pure: picks the kinitro.ai tool prefix from a list of tool names (the session's tool list). A server counts when it
820// has a current-seat tool; the bundled server wins over a user server, that over the claude.ai connector, that over the rest.
821// 0.25.0: the own server of the session's sign-in path is the bundled one; the inactive own server is never taken (the device
822// address lists its tools before any sign-in, the OAuth server none until it is authenticated).
823export function resolveKinitroTools(names: string[], path: SignInPath = 'oauth'): { prefix: string; source: KinitroSource } | undefined {
824 const own = ownPrefix(path), inactive = ownPrefix(path === 'device' ? 'oauth' : 'device')
825 const seats = new Set(names.filter((n) => n.endsWith(`__${SEAT_VERB}`) && !n.startsWith(inactive)))
826 const has = (prefix: string) => seats.has(prefix + SEAT_VERB)
827 if (has(own)) return { prefix: own, source: 'bundled' }
828 const bundled = [...seats].find((n) => n.startsWith(`mcp__plugin_${VARIANT.name}_`) && n.endsWith(`__${SEAT_VERB}`)) // the plugin's server under another server name
829 if (bundled) return { prefix: bundled.slice(0, -SEAT_VERB.length), source: 'bundled' }
830 if (has(USER_PREFIX)) return { prefix: USER_PREFIX, source: 'user' }
831 if (has(CONNECTOR_PREFIX)) return { prefix: CONNECTOR_PREFIX, source: 'connector' }
832 const other = [...seats].find((n) => /^mcp__.+__current-seat$/.test(n) && /kinitro|methos/i.test(n))
833 if (other) return { prefix: other.slice(0, -SEAT_VERB.length), source: 'other' }
834 return undefined
835}
836
837/** 0.24.0 (criterion 8, choice 1b): the prefixes of kinitro.ai servers in the session that are not the plugin's own. */
838export function secondConnections(names: string[]): string[] {
839 const seats = names.filter((n) => n.endsWith(`__${SEAT_VERB}`) && !BUNDLED_RX.test(n) && !SIBLING_RX.test(n))
840 const found = seats.filter((n) => n.startsWith(USER_PREFIX) || n.startsWith(CONNECTOR_PREFIX) || /kinitro|methos/i.test(n))
841 return [...new Set(found.map((n) => n.slice(0, -SEAT_VERB.length)))]
842}
843
844// Build variant (PO 21.10.2026): the bundled server of the OTHER kinitro.ai build (kinitro-ai beside kinitro-ai-test) is no
845// second connection to warn about; the gate below keeps a session to one of them.
846const SIBLING_RX = /^mcp__plugin_kinitro-ai(-test)?_kinitro_ai(_device)?__/ // review F4: exactly the two builds, each with its two own servers
847
848/** Whether a build is active, given KINITRO_AI_ENV (Architect ruling R1, 21.10.2026): both builds are active by default, so
849 * one session can work on Production and look at Test. The variable is only an override that switches ONE build off:
850 * TEST switches the Production build off, PROD switches the Test build off. */
851export function activeIn(env: 'PROD' | 'TEST', value: string | undefined): boolean {
852 const want = (value ?? '').trim().toUpperCase()
853 return env === 'TEST' ? want !== 'PROD' : want !== 'TEST'
854}
855
856let activeP: Promise<{ on: boolean; value: string | undefined }> | undefined
857function activeNow($: any): Promise<{ on: boolean; value: string | undefined }> {
858 if (!activeP) {
859 activeP = (async () => {
860 let v: string | undefined
861 try { v = (await $.env.get('KINITRO_AI_ENV')) ?? undefined } catch { /* unset */ }
862 return { on: activeIn(VARIANT.env, v), value: v }
863 })()
864 }
865 return activeP
866}
867
868// 0.24.3 (item 4.2.1-3696 criterion 6): inert = this build is switched off (KINITRO_AI_ENV) or the session is headless
869// (claude -p, build and worker sessions). An inert plugin passes every event through and touches nothing.
870let headlessKnown: boolean | undefined // read from the host once per module (a restarted module finds the flag there); set at session.start
871async function headlessNow($: any): Promise<boolean> {
872 if (headlessKnown === undefined) headlessKnown = await read($, headlessA)
873 return headlessKnown
874}
875async function inertNow($: any): Promise<boolean> {
876 return !(await activeNow($)).on || (await headlessNow($))
877}
878
879// the one log line of a headless session: in the person's folder, never in the working folder
880async function headlessLog($: any, line: string) {
881 try {
882 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
883 if (home) await $.fs.write(joinPath(home, `${F}/headless.log`), `${new Date().toISOString()} ${line}
884`)
885 } catch { /* ignore */ }
886}
887
888/** The one sentence that tells the person about a second connection and how to switch it off for this tool. */
889export function secondConnectionText(prefixes: string[]): string {
890 // 0.24.3 (6b): the claude.ai connector also serves the browser, Desktop and mobile, so it is switched off for this tool
891 // only (/mcp, Disable) and never removed in the claude.ai settings
892 const how = prefixes.map((p) => (p === USER_PREFIX ? 'claude mcp remove kinitro_ai' : p === CONNECTOR_PREFIX ? 'in Claude Code switch the claude.ai connector off for this tool only: /mcp, choose the claude.ai connector, Disable' : `switch ${p.slice(5, -2)} off for this tool in /mcp`))
893 return `A second kinitro.ai connection is present in this session (${prefixes.map((p) => p.slice(5, -2)).join(', ')}); the ${VARIANT.name} plugin uses only its own connection, so switch the other one off for this tool (${how.join('; ')}).`
894}
895
896// 0.24.0: the plugin works only with its own server (choice 1b); the fallback to a user server, the claude.ai connector or
897// any other server is withdrawn. Until the bundled server is listed, the list is read again at every call.
898let toolPrefix: string | undefined
899let toolSource: KinitroSource | undefined
900let seconds: string[] = []
901let secondChecked = false
902async function kinitroTools($: any): Promise<{ prefix: string | undefined; source: KinitroSource | undefined }> {
903 if (toolPrefix) return { prefix: toolPrefix, source: toolSource }
904 const path = await pathNow($)
905 try {
906 const names: string[] = (await $.tool.list()).map((t: any) => String(t.name))
907 const found = resolveKinitroTools(names, path)
908 toolPrefix = found?.prefix === ownPrefix(path) ? found.prefix : undefined // fix round L1: the exact own server, no lookalike
909 toolSource = toolPrefix ? 'bundled' : undefined
910 seconds = secondConnections(names)
911 } catch { /* nothing is visible */ }
912 return { prefix: toolPrefix, source: toolSource }
913}
914
915// the second connections in the session now (for the notice; read until it was told)
916async function secondConnectionsNow($: any): Promise<string[]> {
917 try { seconds = secondConnections((await $.tool.list()).map((t: any) => String(t.name))) } catch { /* keep the last */ }
918 return seconds
919}
920
921// the prefix to show or to name in texts: the resolved one, else the bundled name
922async function kinitroPrefix($: any): Promise<string> {
923 return (await kinitroTools($)).prefix ?? ownPrefix(await pathNow($))
924}
925
926// one call through the plugin's own server: the tool path (its tool.call hook adds the key), else the direct MCP route
927// (which no hook sees, so the key is added and an answer's key adopted here too). An error answer is final, not retried
928// on the other route; the thrown error carries the parsed answer.
929async function mcpOnce($: any, tool: string, args: Record<string, unknown>): Promise<{ text: string; isError: boolean }> {
930 const { prefix, source } = await kinitroTools($)
931 const path = await pathNow($)
932 const p = prefix ?? ownPrefix(path) // nothing visible yet (connecting, not signed in): the own server of the session's path
933 const errs: string[] = []
934 // fix round L4/M2: once the own server is listed, the tool path is the only route and a deny or a failure there is final
935 // (the call may have run; it is never repeated on the direct route). Only while no own tool is listed (nothing can have
936 // run) the direct MCP route is tried.
937 try {
938 const r: any = await $.tool.call({ tool: `${p}${tool}`, ...args })
939 if (r.deny) throw new Error(`denied: ${r.deny}`)
940 route = 'tool.call'
941 const t = resultText(r)
942 if (tool === 'open-domain' && !r.isError) { const k = sessionKeyOf(t); if (k) await keepKey($, k) } // where no hook stripped it first
943 return { text: scrubKey(t), isError: !!r.isError }
944 } catch (err: any) {
945 const msg = String(err?.message ?? err)
946 if (prefix) return { text: scrubKey(`${tool}: ${msg} ${MAY_HAVE_RUN}`), isError: true }
947 errs.push(`tool.call: ${msg}`)
948 }
949 try {
950 const r = await $.mcp.call(p.slice(5, -2), tool, args)
951 const t = (r.content ?? []).map((b: any) => (b.type === 'text' ? b.text : '')).join('')
952 route = 'mcp.call'
953 if (tool === 'open-domain' && !r.isError) { const k = sessionKeyOf(t); if (k) await keepKey($, k) }
954 return { text: scrubKey(t), isError: !!r.isError }
955 } catch (err: any) { errs.push(`mcp.call: ${String(err?.message ?? err)}`) }
956 throw new Error(scrubKey(`${source ? '' : noTools(path) + ' '}${errs.join(' | ')}`)) // fix round L2
957}
958
959async function mcp($: any, tool: string, args0: Record<string, unknown>) {
960 const callArgs = async () => {
961 const { domainRef: given, ...rest } = args0 as Record<string, unknown>
962 const key = await heldKey($)
963 if (key) return { ...rest, domainRef: key }
964 if (legacy) { const slug = given ?? (NO_DOMAIN_ARG.has(tool) ? undefined : domainRef); return slug ? { ...rest, domainRef: slug } : rest }
965 return given !== undefined ? { ...rest, domainRef: given } : rest
966 }
967 let out = await mcpOnce($, tool, await callArgs())
968 if (out.isError && !binding && !KEYLESS_VERBS.has(tool) && isKeyRefusal(out.text) && (await rebindOnce($))) out = await mcpOnce($, tool, await callArgs())
969 if (out.isError) {
970 const err: any = new Error(`${tool}: ${out.text.slice(0, 300)}`)
971 try { err.answer = JSON.parse(out.text) } catch { /* not JSON */ }
972 throw err
973 }
974 try { return JSON.parse(out.text) } catch { return { text: out.text } }
975}
976
977function parseSections(body: string): Record<string, string> {
978 const out: Record<string, string> = {}
979 for (const part of body.split(/^## /m).slice(1)) {
980 const nl = part.indexOf('\n')
981 out[part.slice(0, nl).trim()] = part.slice(nl + 1).trim()
982 }
983 return out
984}
985
986function sec(name: string): string {
987 return briefing?.sections[name] ?? ''
988}
989
990// identifies the persona and working rules the agent should hold: domain + content hash
991function personaKey(): string {
992 if (!briefing) return ''
993 const t = `${sec(S.persona)}\n${sec(S.rules)}`
994 let h = 5381
995 for (let i = 0; i < t.length; i++) h = ((h * 33) ^ t.charCodeAt(i)) >>> 0
996 return `${briefing.domainRef ?? '-'}:${t.length}:${h.toString(36)}`
997}
998
999
1000// Layer A: the agent's own native instruction-* contents on its agent node, appended to the matching section
1001const A_TYPES: Record<string, string> = {
1002 [S.persona]: 'instruction-persona', [S.rules]: 'instruction-standing', [S.start]: 'instruction-coldstart',
1003 [S.turn]: 'instruction-preturn-continue', [S.after]: 'instruction-postcompaction',
1004}
1005
1006async function readFileTrim($: any, f: string): Promise<string | undefined> {
1007 try { if (await $.fs.exists(f)) { const v = String(await $.fs.read(f)).trim(); return v || undefined } } catch { /* ignore */ }
1008 return undefined
1009}
1010
1011// the session's own choice (its record), then what the host holds, then a pre-0.20 session file, and only for a
1012// session that never had a domain: the default of its HOME folder. The current working directory is never asked.
1013async function readDomainFile($: any): Promise<string | undefined> {
1014 const home = await sessionHome($)
1015 if (sessionRecord?.domain) return sessionRecord.domain
1016 let sid = ''
1017 try { sid = await $.session.id() } catch { /* ignore */ }
1018 let held: string | null = null
1019 try { held = await read($, boundA) } catch { /* ignore */ }
1020 return held ?? (sid ? await readFileTrim($, joinPath(home, SESSION_DOMAIN_PREFIX + sid)) : undefined) ?? await readFileTrim($, joinPath(home, DOMAIN_FILE))
1021}
1022
1023// what the agent tells the user: names only, no codes, ids or paths
1024function confirmation(slug: string, bound: { text: string; approval?: Approval }) {
1025 if (bound.approval) return approvalResult(bound.approval)
1026 const message = bound.text
1027 const ok = domainRef === slug && !!briefing
1028 return ok
1029 ? { bound: true, domain: briefing?.domainName ?? slug, agent: briefing?.agentName ?? null, domainView: message.split('domain view: ')[1] ?? null, sayToUser: `This session now works for ${briefing?.domainName ?? slug}${briefing?.agentName && briefing.agentName !== briefing.domainName ? ` with the agent ${briefing.agentName}` : ''}.` }
1030 : { bound: false, reason: message, ...(toolSource ? {} : { sayToUser: `You are not signed in to kinitro.ai yet; I start the email-code sign-in now.` }) }
1031}
1032
1033// a choice: the session record, the host, and the folder default of the session's home folder (for the next new session)
1034async function writeDomainFiles($: any, slug: string) {
1035 try { await update($, boundA, () => slug) } catch { /* ignore */ }
1036 await saveRecordDomain($, slug)
1037 await $.fs.write(await at($, DOMAIN_FILE), slug + '\n')
1038}
1039
1040/** R9: the band note of a failed refresh: the message, key scrubbed, at most 160 chars. */
1041export function refreshErrorNote(err: any): string {
1042 return `Refresh failed: ${scrubKey(String(err?.message ?? err)).replace(/\s+/g, ' ').trim().slice(0, 160)}`
1043}
1044const REFRESH_NOTE_RX = /^Refresh failed:/
1045
1046// approved domains of the connection, and the address of the seat picker (approve more domains)
1047export async function refreshChoices($: any) {
1048 if (await signInWaiting($)) return // 0.25.0: the device path binds through the sign-in (checkSignIn)
1049 try {
1050 const seat = await mcp($, 'current-seat', {})
1051 const approved: DomainChoice[] = (seat?.approved ?? []).map((d: any) => ({ slug: String(d.slug), name: String(d.name) }))
1052 if (!approved.length && seat?.domain?.id) approved.push({ slug: '', name: String(seat.domain.name ?? 'seat-bound') })
1053 await update($, approvedA, () => approved)
1054 const anySlug = domainRef ?? approved.find((d) => d.slug)?.slug
1055 if (anySlug && (legacy || (await heldKey($)))) { // 0.24.0: the page is asked for within the session only
1056 const r = await mcp($, 'open-page', { target: 'selector', domainRef: anySlug })
1057 if (r?.url) await update($, selectorUrlA, () => String(r.url))
1058 }
1059 const prev = await read($, bandNoteA)
1060 if (prev && REFRESH_NOTE_RX.test(prev)) await update($, bandNoteA, () => null)
1061 } catch (err: any) {
1062 await log($, `refreshChoices failed: ${err?.message ?? err}`)
1063 try { await update($, bandNoteA, () => refreshErrorNote(err)) } catch { /* ignore */ }
1064 }
1065}
1066
1067// what the user switched to on the selection page, read from the browser pane ("This connection may now work in <Domain> as <Agent>")
1068async function switchedOnPage($: any, approved: DomainChoice[]): Promise<DomainChoice | undefined> {
1069 for (const tool of PAGE_TEXT_TOOLS) {
1070 try {
1071 const r: any = await $.tool.call({ tool })
1072 if (r?.deny || r?.isError) continue
1073 const text = String(r?.text ?? (typeof r?.result === 'string' ? r.result : JSON.stringify(r?.result ?? '')))
1074 const m = text.match(/may now work in (.+?) as /)
1075 if (!m) return undefined
1076 const hit = approved.find((d) => d.name === m[1]!.trim())
1077 await log($, `page says switched to '${m[1]}' -> ${hit?.slug ?? 'no approved match'}`)
1078 return hit
1079 } catch { /* try the next tool */ }
1080 }
1081 return undefined
1082}
1083
1084// open the domain view of the bound domain in the browser pane, straight from the plugin (no model turn).
1085// 0.22.0: the link is the shell of the domain (open-page target 'shell'). A server that does not know the target answers
1086// page_link_bad_target; then the plugin asks once more without a target and opens the page the older server gives.
1087async function openDomainView($: any): Promise<string> {
1088 if (!domainRef) return 'no domain bound'
1089 let url: string | undefined
1090 try {
1091 try { url = (await mcp($, 'open-page', { target: 'shell' }))?.url } catch (err: any) {
1092 if (!String(err?.message ?? err).includes('page_link_bad_target')) throw err
1093 await log($, 'open-page target shell not known by the server; asking again without a target')
1094 url = (await mcp($, 'open-page', {}))?.url
1095 }
1096 } catch (err: any) { return `open-page failed: ${err?.message ?? err}` }
1097 if (!url) return 'open-page gave no url'
1098 return openInPane($, url, readableLink(url))
1099}
1100
1101// 0.23.3: the readable link of the bound domain's view, for the offer to open it (no pane opened here).
1102async function domainViewLink($: any): Promise<string | undefined> {
1103 if (!domainRef) return undefined
1104 try {
1105 let url: string | undefined
1106 try { url = (await mcp($, 'open-page', { target: 'shell' }))?.url } catch (err: any) {
1107 if (!String(err?.message ?? err).includes('page_link_bad_target')) throw err
1108 url = (await mcp($, 'open-page', {}))?.url
1109 }
1110 return url ? readableLink(url) : undefined
1111 } catch (err: any) { await log($, `domain view link failed: ${err?.message ?? err}`); return undefined }
1112}
1113
1114// 0.23.3 (PO 16.10.2026): new sessions and domain switches OFFER the domain view in the built-in browser; nothing opens
1115// until the user says yes. Set at the first turn and after a binding the /kinitro command did not confirm itself.
1116let viewOfferPending = false
1117function viewOfferText(name: string, link: string): string {
1118 return `Offer the user once, in one short sentence at the end of your reply, to open the ${name} domain in the built-in browser, and give this readable link: ${link} . Open it only if the user says yes: \`${PROBE_TOOL}\` with {"action": "open-domain"}.`
1119}
1120
1121// 0.23.3: the link a person reads. The ?link= payload is no sign-in (the device cookie is); a domain view or node page
1122// opens without it for the signed-in person. The pane still gets the full link (it ties the page to this session).
1123// Only the seat selector and a single approval need the payload, so their links are shown as they are.
1124// 0.23.6 (PO 16.10.2026): the agent node's instruction set, per type, from get-briefing `instructions`, as given.
1125export type InstructionSet = Record<string, { text: string; source: string }>
1126
1127/** The plain refusal for a domain without an agent node. */
1128export function noAgentNodeText(domain: string): string {
1129 return `this domain (${domain}) has no agent node; add one (provision-domain-agent or the domain page), then choose the domain again`
1130}
1131
1132/** The instruction set out of a get-briefing answer, or undefined when the server does not send one (an older API). */
1133export function instructionSet(answer: any): InstructionSet | undefined {
1134 const list = answer?.instructions
1135 if (!Array.isArray(list)) return undefined
1136 const set: InstructionSet = {}
1137 for (const i of list) {
1138 const type = String(i?.type ?? ''), text = typeof i?.text === 'string' ? i.text.trim() : ''
1139 if (type && text) set[type] = { text, source: String(i?.source ?? '') }
1140 }
1141 return set
1142}
1143
1144/** The briefing sections of an instruction set: each type's text, as the server gives it, into its section. A type with
1145 * no text is left out. "Context nearly full" and "Compaction instruction" have no type of their own: they are read from a
1146 * `## ` heading of that name inside a given text, which itself stays unchanged in its own section. */
1147export function composeSections(set: InstructionSet, parse: (body: string) => Record<string, string>): Record<string, string> {
1148 const sections: Record<string, string> = {}
1149 for (const [title, type] of Object.entries(A_TYPES)) {
1150 const body = set[type]?.text
1151 if (body) sections[title] = body
1152 }
1153 for (const title of [S.full, S.keep]) {
1154 for (const v of Object.values(set)) { const part = parse(v.text)[title]; if (part) { sections[title] = part; break } }
1155 }
1156 return sections
1157}
1158
1159export function readableLink(url: string): string {
1160 try {
1161 const u = new URL(url)
1162 if (!u.searchParams.has('link')) return url
1163 u.searchParams.delete('link')
1164 return u.toString()
1165 } catch { return url }
1166}
1167
1168async function openInPane($: any, url: string, shown: string = url): Promise<string> {
1169 const errs: string[] = []
1170 for (const tool of BROWSER_TOOLS) {
1171 try {
1172 const r: any = await $.tool.call({ tool, url })
1173 if (r?.deny) { errs.push(`${tool}: denied ${r.deny}`); continue }
1174 if (r?.isError) { errs.push(`${tool}: ${String(r.text ?? r.result).slice(0, 160)}`); continue }
1175 await log($, `pane opened via ${tool}`)
1176 return `opened in the browser pane (${tool.split('__')[1]})`
1177 } catch (err: any) { errs.push(`${tool}: ${String(err?.message ?? err).slice(0, 160)}`) }
1178 }
1179 await log($, `pane not opened: ${errs.join(' | ')}`)
1180 return `browser pane not reachable; link: ${shown}`
1181}
1182
1183// bind this session to a domain: files, module state, briefing, band
1184type BindResult = { text: string; approval?: Approval }
1185async function bindDomain($: any, slug: string): Promise<BindResult> {
1186 await writeDomainFiles($, slug)
1187 briefing = undefined; needsDomain = undefined; domainRef = undefined
1188 await writeState($)
1189 await loadBriefing($)
1190 const ok = briefing && domainRef === slug
1191 const ap = ok ? undefined : await heldApproval($)
1192 if (ap && ap.slug === slug) {
1193 // R3: a normal outcome, no failure note; the band offers the approval link
1194 await update($, currentA, () => null)
1195 await update($, chooserA, () => true)
1196 await update($, bandNoteA, () => null)
1197 return { text: `approval needed for ${slug}`, approval: ap }
1198 }
1199 await update($, currentA, () => (ok ? slug : null))
1200 await update($, chooserA, () => !ok)hooks/variant.ts 22 lines1// Build variant of the kinitro-ai plugin (PO 21.10.2026: two plugins with separate connections, one source).
2// This file is the ONLY place that names the plugin, its environment and its local file names. The source carries the
3// Production values; the packager (Novatect tools/plugin/package_kinitro_plugin.py --variant test) writes the VARIANT line
4// anew for the Test build ("kinitro-ai-test", https://methos-test.kinitro.ai/mcp) and rewrites .mcp.json, plugin.json, the
5// host state keys (atom plugin literals, types/index.d.ts) and commands/kinitro.md (as commands/kinitro-test.md) to match.
6// Never edit the values by hand in a release tree.
7// name the plugin name: tool names (mcp__<name>__probe, mcp__plugin_<name>_kinitro_ai__<verb>), host state, texts
8// env PROD or TEST: which kinitro.ai host the bundled server talks to
9// showEnv true: the prompt context line and the domain band carry the environment ([kinitro-ai PROD 0.24.3],
10// [kinitro-ai-test TEST 0.24.3]); on for both builds from 0.24.2 (Architect ruling R4, 21.10.2026)
11// downloadBase the download page whose marketplace.json gives the update notice
12// command the slash command file (commands/<command>.md): /kinitro, /kinitro-test
13// files the prefix of every local file (.kinitro-ai-domain, .kinitro-ai-outbox.json, ~/.kinitro-ai/sessions, ...)
14// Activation (Architect ruling R1, 21.10.2026): both builds are active side by side in one session; each one's hooks touch
15// only its own server, probe, host state and local files. KINITRO_AI_ENV (read once per session) is an optional override:
16// TEST switches the Production build off, PROD the Test build; a build switched off refuses its own server's calls and
17// passes every other event through untouched.
18export type Variant = { name: string; env: 'PROD' | 'TEST'; showEnv: boolean; downloadBase: string; files: string; command: string }
19// @variant-begin (the packager replaces this line)
20export const VARIANT: Variant = { name: 'kinitro-ai', env: 'PROD', showEnv: true, downloadBase: 'https://methos.kinitro.ai/download/plugins/claude/', files: '.kinitro-ai', command: 'kinitro' }
21// @variant-end
22types/index.d.ts 24 lines1export type DomainChoice = { slug: string; name: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 'kinitro-ai': {
6 approved: DomainChoice[]
7 current: string | null
8 chooser: boolean
9 selectorUrl: string | null
10 bandNote: string | null
11 bound: string | null
12 testMode: boolean
13 startPack: boolean
14 contextKey: string
15 sessionKey: { sid: string; key: string } | null
16 approval: { sid: string; slug: string; request: string; url: string; domainName: string; agentName: string; expiresAt: string } | null
17 secondNotice: boolean
18 headless: boolean
19 signInPath: { sid: string; path: 'oauth' | 'device'; reason: string } | null
20 signIn: { sid: string; url: string; mask: string; expiresAt: string; requestedAt: number } | null
21 }
22 }
23}
24