mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 18:47:42 +01:00
* fix(check): the on-demand loop check signs in on the box, and is red when it cannot ask The first run of loki-loop-check.yml (2026-11-12, run 43188095136) printed "down: loki e2e could not mint a session on the box" two seconds in, and the job was green. Three things were wrong: - The deploy ships the runner a fixed list of scripts and nothing under scripts/test, so on the box there was no test to run and no token script. The workflow now carries the check's own files with it. - The check minted an Auth.js session cookie. Sign-in moved to AccountKit on 2026-11-01, where that cookie is no session. It now signs in the way a runner does: scripts/test/mint-check-token.ts mints an agent token for the operator that expires in two hours, the check uses it as a bearer and removes it on exit. The cookie mint stays as the fallback. - A check that could not sign in exited 0. With the verdict asked for, it exits 1, and it says why (long strings masked). scripts/test/loop-check-signs-in.ts pins all of it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): what production showed after the first fix, and why the check could not sign in Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(check): the loop check prints Loki's own reason for a task that does not start Its first full run on the live site (2026-11-12, run 43191224470) ended "still queued (Queued) after 35 min" and then guessed at the builder's sign-in. The run route already answers the track's sentence for an open run (detail), and the chat's reply says where the task went: the check prints both, right after the dispatch and again when it gives up. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): the first full check on the live site, 4 of 5 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): why the probe did not start, in Loki's own words Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(chat): an address to Loki is not the loki project; the loop check reaches the project it was sent to A project named in a message outranks the selected project, on purpose (lib/loki-fleet-commands). The assistant is called Loki and so is one of the projects, so "Loki, add a dark mode toggle" typed with orangecat selected was sent to the loki project. Found through the loop check on the live site (2026-11-12, run 43198552471): asked for project orangecat, it came back "Sent loki to the cloud runner", because its marker was "[loki-e2e]". Three runs in a row had waited behind the loki project's open run while reporting on a project the probe never reached. - project-mention: withoutAddressTo removes an address to the assistant before matching: the name at the start followed by punctuation, after a greeting, "@loki", or set off by a comma at the end. "Loki's sidebar", "in loki" and a bare "Loki fix the header" still name the project. - loki-loop-e2e: the marker is "[e2e-probe]" and names no project, and the check fails at once when Loki dispatched to another project than the one it asked for. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): the probe had been going to the loki project; the routing fix Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(queue): a run that has gone silent gives its project to the waiting message A project's shared session takes one message at a time: the claim gate holds the next one until the run ahead has closed. A run closes when its agent reports. An agent that ended its turn without reporting still has a process at its prompt, and the reaper shelters a run with a live process for up to MAX_RUN_HOURS, so the next message could wait twelve hours behind a session that was doing nothing. On the live site (2026-11-12) messages sent through Loki's chat read "This project is still on an earlier task" and were still queued 25 to 35 minutes later. - lib/orchestration/quiet-lane: the rule, pure. The runner beats while the terminal prints and while the agent waits at a sign-in or an approval. No beat for 20 minutes (twice the window after which every surface says Stalled), not waiting for a person, no command outstanding, and still so 90 seconds after it was first seen: release. The second look covers a runner that could not beat for a while and whose first request back is the claim. - db/queries/quiet-lane: reads those facts for the run at the head of each lane a message waits in, through olderOpenRunSql, and closes it with the reaper's own verdict (partial with the handoff note, else timeout with the sentence), ended at its last beat. No escalation. - claimNextPendingCommand calls it before the gate, so the message is claimed in the request that closed the run. - The waiting sentence carries the bound. A working agent prints, so its beat is seconds old at any age and it keeps its lane. Nothing is closed when nobody is waiting. scripts/test/quiet-lane.ts, and five scenarios in scripts/test/lane-and-reaper.ts against a real Postgres (13 of 13 locally). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(runs): a pull request that cannot merge is said in the thread, with the message that repairs it The fleet's sweep merges a green pull request and leaves a red or conflicted one waiting. A task sent from the chat that ended at such a pull request read "done, it merges on its own" until somebody opened GitHub. - feedback/fix-shipping: PrBlocker, prBlockerFor (a conflict when GitHub says mergeable: false, else the names of the checks that failed; cancelled and still-running are not failures), prBlockerNews (once per commit and reason). - feedback/fix-shipping-refresh: readBlockers on the refresh input; only then are the head commit's check runs and statuses read. - run-follow-notify: the fifteen-minute follower asks, and on news writes one line into the thread the task came from and sends one push. The line ends with the message to send ("<project>: fix the failing checks on <pull request> and push to the same branch."): a message naming a project is a task for it. - Loki does not send the repair itself: no agent run nobody asked for (lib/auto-dispatch). scripts/test/run-follow-notify.ts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): the 11:17 rehearsal failed on a slow box: sign-up 504, 96% memory, a 503 window Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): bots do not answer on the live site (502, 11:39 UTC); OrangeCat #1672; #1678 green Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(queue): only a run whose runner has reported output can be read as having stopped A runner from before the beat existed reports nothing while its agent works. Silence since delivery would have closed such a run after twenty minutes and typed the waiting message into a working session. A run that has never beaten now keeps its lane; one that truly never printed is the reaper's, which closes it as never started from the runner's own unverified ack. scripts/test/quiet-lane.ts, and a sixth scenario in scripts/test/lane-and-reaper.ts (14 of 14 locally). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(ops): the box usage report prints the builder's memory budget and finishes on a slow box On 2026-11-12 the box had 0.6 GiB available and no swap left, and the report was cancelled at its 20-minute limit inside the first du. Each disk walk now gets a minute. A new section prints what the runner unit holds, whether it has a memory ceiling, and which cgroup the sandboxes' processes are in: sandbox.ts relies on the unit's MemoryMax to bound sealed sessions. Read-only, names and sizes only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): what holds the box's memory, measured; the builder has no ceiling Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(queue): an idle run is closed before the next task starts; the runner's six-hour stop and a turn answered in seconds are read correctly Three faults in the idle rule (#1680), found by an independent review and shown failing first in scripts/test/lane-and-reaper.ts against main (13 passed, 4 failed; 17 of 17 after): - An idle run stopped holding its project but stayed open until the hourly reaper. The next task went into the same session, and its ready handoff closes every delivered open run of the project, so the idle run was recorded as done with the other run's summary. The claim now closes the idle run first, with the reaper's own function and sentence, and only when a task is waiting in that project (db/queries/idle-run-close). - The runner stops beating six hours into a run. Half an hour later the run read as idle while it printed, and the next prompt went into a working session. A last working beat at that horizon is not read as silence (RUN_PROGRESS_HORIZON_SECONDS). - A turn that ended before the runner began reporting on it never had a working beat, read as unknown and held its project for up to twelve hours. Every beat stamps lastBeatAt; a run the runner reports on that has printed no work since delivery is idle after the same half hour. A run with no beat of any size keeps its lane, as before. scripts/test/idle-run-release.ts, scripts/test/lane-and-reaper.ts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(ops): the box usage report can be asked for memory alone The disk walks took the whole 20 minutes twice on 2026-11-12, on a box that was swapping, when only the memory was wanted. what=memory stops after the memory sections. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * feat(ops): the builder can be given a memory ceiling, read and set from the Sealed builds workflow Measured on the box, 2026-11-12 12:19 UTC: loki-box-runner.service held 6.3 GiB with MemoryHigh and MemoryMax at infinity, every sandbox process is in that unit's cgroup, the box had no swap left, and the kernel had stopped 30 processes for memory since boot: the gateway 15 times, a live site 3 times, a sandbox 3 times. Every site unit has a 1G ceiling; the builder had none, though sandbox.ts relies on the unit's MemoryMax to bound sealed sessions. sealed-builds-ctl.sh gains three modes, run from sealed-builds.yml: - memory: read. What the builder holds, what bounds it, what the box has left. - memory-set, runs="<GiB>": MemoryMax and MemoryHigh one below it, and the builder's processes are marked to give first when the whole box runs out. Refused when the ceiling is below what the builder holds now, because that stops sessions at once; "force" after the number sets it anyway. Nothing is restarted. - memory-clear: undo. Nothing is set by a deploy. It is a decision, applied by a person. scripts/hetzner/test-sealed-builds-memory.sh, in test:ops. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(runs, chat): the blocked pull request notice is said once and its repair reaches the right project; an address to Loki is set off, and is the project when nothing else is From the independent review of this branch, each finding confirmed by a second agent told to refute it. The notice: - It would have repeated every tick. "Already said" lived in the ledger, the ledger is rebuilt on every refresh, and the dispatch card's own refresh does not read blockers. It is kept beside the ledger now (payload.prBlockerSaid, per reason), written once the line is in the thread. - Its repair line named the pull request by link. The link carries the repository owner's name, and a project of that name won the match: the repair for loki went to Bitbaum. The line names the number, opens with "In <project>," and uses a verb the chat's own rule takes as a task, for a conflict as well. The test sends it through projectMentionedIn and looksLikeDispatchTask for four projects and both reasons. - action_required and stale count as failed: neither turns green by waiting. The address: - "ok loki is broken, fix its header", "loki-loop-check is red" and "run the tests on @loki" lost the project; "Loki - add a toggle" kept it. An address is the name set off from the sentence (a comma, a colon, any dash with space around it, "please", "can you"), at the start of any sentence. - "loki: fix the header" is read as an address, so a selected project gets the work; with nothing selected and no other project named, the name is the project (projectNamedByAddress, the last resort of both paths). scripts/test/run-follow-notify.ts, scripts/test/project-mention.ts (114). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * fix(ops): the builder's ceiling is a ceiling only; docs(handoff): the box's memory, the review's findings, what is ready and not applied memory-set no longer sets MemoryHigh one below the ceiling: at the moment it is set the builder holds close to the ceiling, and a mark under what it holds would slow every session at once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi * docs(handoff): the box's memory now holds up OrangeCat merges: Browser smoke is red on main Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmt4p1jMfJnbJtpeNhi --------- Co-authored-by: Claude <noreply@anthropic.com>
329 lines
15 KiB
TypeScript
329 lines
15 KiB
TypeScript
/**
|
|
* NL command resolution for the Loki command composer (SSOT).
|
|
*
|
|
* Turns a plain-language input into a routable decision, per the design in
|
|
* docs/loki-command-surface.md and the operator's calls:
|
|
* - chat vs command: route each input to one or the other.
|
|
* - ask when ambiguous: a command with no resolvable project sets
|
|
* needsProject=true so the UI asks instead of guessing.
|
|
* - dispatch is fire-and-forget into the project's session (the caller posts
|
|
* to /api/inject); this resolver only RESOLVES, it does not dispatch.
|
|
*
|
|
* Resolution is one fast Groq call, with a deterministic fallback (the shared
|
|
* project-mention matcher, treat as command) when the LLM is unavailable — so
|
|
* the composer degrades to "named project → run", never to a hang.
|
|
*
|
|
* This is the single resolver shared by /api/command/resolve and the Loki
|
|
* /api/conversations/[id]/messages route — neither keeps its own copy.
|
|
*/
|
|
import { isBareConfirmation } from "@/lib/loki/confirmation";
|
|
import { callGroqText } from "@/lib/groq";
|
|
import { projectMentionedIn, projectNamedByAddress } from "@/lib/project-mention";
|
|
import { ORCHESTRATION_TASK_INTENT_IDS, type OrchestrationTaskIntentId } from "@/lib/orchestration";
|
|
|
|
export type CommandResolution = {
|
|
kind: "command" | "chat";
|
|
projectKey: string | null;
|
|
intentId: OrchestrationTaskIntentId | null;
|
|
prompt: string;
|
|
needsProject: boolean;
|
|
reason: string;
|
|
};
|
|
|
|
export type ResolveCommandInput = {
|
|
text: string;
|
|
projects: string[];
|
|
selectedProject?: string;
|
|
};
|
|
|
|
const SYSTEM = `You route an operator's input in a multi-project AI-agent console. Return ONLY compact JSON with keys: kind, projectKey, intentId, prompt, reason.
|
|
- kind: "command" if they want an agent to DO work on a project — including when they're done discussing and ready to build ("let's develop", "build it", "implement this", "start coding", "ship it", "make it happen", "go ahead"); "chat" if they're asking a question or still exploring ideas without asking to run work.
|
|
- projectKey: the EXACT project name (copied verbatim from the provided list) the input refers to, or null if none is named. NEVER invent a name that is not in the list.
|
|
- intentId: one of [${ORCHESTRATION_TASK_INTENT_IDS.join(", ")}] when the request clearly maps to one, else null. Hints: "code review"->quality; "review the ui"/"ux"->ux_review; "run tests"/"fix types"/"fix tests"->test_and_fix; "commit"/"push"->commit_push; "audit"/"full audit"->full_audit; "what next"/"keep going"/"next best"/"let's develop"/"build it"/"implement"->next_best; "deploy check"->deploy_check; "product review"->product; "wrap up"/"close"->close_session.
|
|
- prompt: the cleaned instruction to give the agent (for command) or the user's message (for chat), with the project name removed. For develop/build handoffs, include the concrete task from the message (or "Continue from our discussion and implement the plan we agreed.").
|
|
- reason: <= 8 words.`;
|
|
|
|
/** Phrases that mean "stop talking, start building" — deterministic fast path. */
|
|
const DEVELOP_READY_RE =
|
|
/\b(let['']?s|time to|ready to|go ahead(?: and)?|please|now)\s+(develop|build|implement|code|ship|make it|start(?:\s+coding)?)\b|\b(start|begin)\s+(develop(?:ment|ing)?|building|implement(?:ation|ing)?|coding)\b/i;
|
|
|
|
/** Imperative work — route to dispatch when a project is in context (not Q&A). */
|
|
const ACTION_VERB_RE =
|
|
/\b(implement|fix|add|build|ship|refactor|rewrite|migrate|update|write|create|patch|debug|investigate|optimize|remove|delete|integrate|wire|configure|set up|hook up|continue|keep going|move forward|make progress|next step|next best)\b/i;
|
|
|
|
const CHAT_QUESTION_RE =
|
|
/^(what|why|how|when|where|who|should|could|would|can you explain|tell me about|describe|compare|summarize|explain|list|show me|is there|are there)\b/i;
|
|
|
|
/**
|
|
* Asking to be TOLD something. Not every request phrased as an instruction is
|
|
* work for an agent — "I want you to tell me what is left to do with X" is a
|
|
* question wearing an imperative coat, and CHAT_QUESTION_RE misses it because
|
|
* the sentence opens with "I", not an interrogative.
|
|
*
|
|
* This mattered because the fallback at the bottom of looksLikeDispatchTask
|
|
* treats any sentence over 16 characters containing " for "/" on "/" in " as a
|
|
* task. That sentence contains "for it", so a plain question was routed to an
|
|
* agent, and — having no project — came back as a picker instead of an answer.
|
|
* Read the room before reading the grammar: if they asked to be told, tell them.
|
|
*/
|
|
const INFO_REQUEST_RE =
|
|
/^\s*(?:so\s+|and\s+|ok(?:ay)?,?\s+)?(?:i\s+(?:just\s+)?(?:want|need|would\s+like|'?d\s+like|wanna)\s+(?:you\s+)?to\s+(?:tell|explain|show|describe|summari[sz]e|list|walk|say)|i\s+(?:want|need|'?d\s+like)\s+to\s+(?:know|understand|see|hear)|(?:can|could|would|will)\s+you\s+(?:please\s+)?(?:tell|explain|show|describe|summari[sz]e|list|walk|remind|give)|tell\s+me|remind\s+me|walk\s+me\s+through|give\s+me\s+(?:a\s+|an\s+|the\s+)?(?:summary|rundown|status|overview|list|sense|picture|breakdown)|any\s+(?:idea|thoughts|update)|status\s+(?:of|on)\b)/i;
|
|
|
|
/**
|
|
* A yes/no question — "Are you able to…", "Is it possible…", "Do you know…".
|
|
*
|
|
* Observed 2026-10-05: "Are you able to work on improving Loki in this field."
|
|
* opened with none of CHAT_QUESTION_RE's words, carried no keyword verb, and
|
|
* has no question mark (voice input drops it) — so it reached the last-resort
|
|
* rule below, which reads " on " as a task, and an agent was queued to answer
|
|
* a question about whether it could. Auxiliary-led sentences ask; they do not
|
|
* order. "can/could/will you <verb>" is deliberately absent: that is how people
|
|
* politely give an instruction, and ACTION_VERB_RE decides those.
|
|
*/
|
|
const YES_NO_QUESTION_RE =
|
|
/^(?:so\s+|and\s+|ok(?:ay)?,?\s+)?(?:are|is|am|was|were|do|does|did|have|has|had|may|might|shall)\s+(?:you|it|there|this|that|we|i|they|loki|anything|everything)\b|^(?:can|could|would|will)\s+(?:you|it|loki)\s+(?:be\s+able|even|actually|really|ever)\b/i;
|
|
|
|
function inferIntentFromText(text: string): OrchestrationTaskIntentId | null {
|
|
const t = text.toLowerCase();
|
|
if (/\b(code review|review (?:the )?code)\b/.test(t)) return "quality";
|
|
if (/\b(review (?:the )?ui|ux review)\b/.test(t)) return "ux_review";
|
|
if (/\b(fix (?:types|tests)|run tests|test_and_fix)\b/.test(t)) return "test_and_fix";
|
|
if (/\b(commit|push)\b/.test(t)) return "commit_push";
|
|
if (/\b(full audit|audit the)\b/.test(t)) return "full_audit";
|
|
if (/\b(deploy check|deploy)\b/.test(t)) return "deploy_check";
|
|
if (/\b(next best|keep going|continue|move forward|make progress|develop|build it)\b/.test(t)) {
|
|
return "next_best";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Asked to be told, not to have something done — whatever else it contains. */
|
|
function readsAsQuestion(t: string): boolean {
|
|
return (
|
|
CHAT_QUESTION_RE.test(t) ||
|
|
INFO_REQUEST_RE.test(t) ||
|
|
YES_NO_QUESTION_RE.test(t) ||
|
|
(t.endsWith("?") && !ACTION_VERB_RE.test(t))
|
|
);
|
|
}
|
|
|
|
/**
|
|
* A request about the person's own life — their calendar, a reminder, a
|
|
* message or email to someone, a commitment — not work for a project.
|
|
*
|
|
* Found in production on 2026-10-15 with a fresh account that had one
|
|
* project: "Put an event in my calendar: dentist appointment on Monday at
|
|
* 9am" and "Add a commitment for me: send the new bakery menu to Anna by
|
|
* Friday" were both dispatched to that project as BUILD work (the action-task
|
|
* fast path below, with its sole-project fallback), failed with "Cloud builder
|
|
* access is private", and never reached the chat path whose proposal
|
|
* extractor drafts the event or the message for approval. A personal action
|
|
* must be answered, and drafted, never built.
|
|
*
|
|
* Narrow on purpose: the cue must be personal ("my calendar", "remind me",
|
|
* "send Anna a WhatsApp", "email the landlord") AND carry no build word, so
|
|
* "add a calendar page to the app" and "fix the email bug" still dispatch.
|
|
*/
|
|
const PERSONAL_ACTION_RE = new RegExp(
|
|
[
|
|
String.raw`\bmy (?:calendar|agenda|schedule|diary)\b`,
|
|
String.raw`\b(?:remind me|reminder for me)\b`,
|
|
String.raw`\b(?:add|make|log|note) (?:a |an )?commitment\b`,
|
|
String.raw`\bcommitment for me\b`,
|
|
String.raw`\b(?:put|add|create|book|schedule) (?:a |an )?(?:event|appointment)\b`,
|
|
String.raw`\b(?:schedule|book|arrange|set up)\b[^.]{0,24}\b(?:meeting|call|appointment|dinner|lunch|coffee)\b`,
|
|
String.raw`\b(?:send|write|draft)\b[^.]{0,30}\b(?:message|text|whatsapp|telegram|sms|email|e-mail)\b`,
|
|
String.raw`^(?:please\s+)?(?:email|e-mail|message|text|whatsapp|telegram|call|ring|phone)\s+(?!the\s+(?:api|endpoint|function|service)\b)\w`,
|
|
].join("|"),
|
|
"i",
|
|
);
|
|
const BUILD_WORD_RE =
|
|
/\b(?:implement|build|fix|refactor|deploy|ship|feature|bug|page|component|endpoint|button|ui|screen|app|integration|code|repo|test|tests)\b/i;
|
|
|
|
export function isPersonalActionRequest(text: string): boolean {
|
|
const t = text.trim();
|
|
if (!t || DEVELOP_READY_RE.test(t)) return false;
|
|
return PERSONAL_ACTION_RE.test(t) && !BUILD_WORD_RE.test(t);
|
|
}
|
|
|
|
/** True when the message is work to run, not a question for Loki chat. */
|
|
export function looksLikeDispatchTask(text: string): boolean {
|
|
const t = text.trim();
|
|
if (!t) return false;
|
|
// An explicit build handoff outranks everything — "ok, now please build it".
|
|
if (DEVELOP_READY_RE.test(t)) return true;
|
|
if (isPersonalActionRequest(t) || isBareConfirmation(t)) return false;
|
|
if (CHAT_QUESTION_RE.test(t)) return false;
|
|
if (INFO_REQUEST_RE.test(t)) return false;
|
|
if (YES_NO_QUESTION_RE.test(t)) return false;
|
|
if (t.endsWith("?") && !ACTION_VERB_RE.test(t)) return false;
|
|
if (ACTION_VERB_RE.test(t)) return true;
|
|
// Last resort: a bare "<project>: <thing>" or "ship the parser for X" with no
|
|
// recognised verb. Deliberately narrower than "contains a preposition" — that
|
|
// version swallowed ordinary sentences whole. The text must still READ as an
|
|
// instruction, i.e. start with a word that could be a verb, not with a
|
|
// pronoun or an article.
|
|
if (/^(i|we|you|it|they|he|she|the|a|an|my|our|this|that|there|here)\b/i.test(t)) return false;
|
|
return t.length >= 16 && /\b(for|on|in)\s+\S/.test(t);
|
|
}
|
|
|
|
/** True when the operator gave a short generic handoff ("let's develop it") — use
|
|
* the intent's orchestration template instead of the literal phrase as customPrompt. */
|
|
export function isGenericDevelopHandoff(text: string): boolean {
|
|
return DEVELOP_READY_RE.test(text) && text.trim().length < 48;
|
|
}
|
|
|
|
/**
|
|
* Resolve a natural-language input into a routable {@link CommandResolution}.
|
|
* Resolution is currently stateless; the route callers pass userId at the HTTP
|
|
* boundary (auth + scoping) and a future revision can bias by recent/active
|
|
* project, so the param is reserved here without being consumed yet.
|
|
*/
|
|
function pickProjectKey(
|
|
projects: string[],
|
|
namedInText: string | null,
|
|
selectedProject?: string,
|
|
/** When true, a sole registered project is enough context for a develop handoff. */
|
|
allowSingleProject = false,
|
|
/** The project named only by addressing the assistant ("loki: …"): the last
|
|
* resort before a sole project (lib/project-mention projectNamedByAddress). */
|
|
namedByAddress: string | null = null,
|
|
): string | null {
|
|
return (
|
|
namedInText ??
|
|
selectedProject ??
|
|
namedByAddress ??
|
|
(allowSingleProject && projects.length === 1 ? projects[0] : null)
|
|
);
|
|
}
|
|
|
|
export async function resolveCommand(
|
|
{ text, projects, selectedProject }: ResolveCommandInput,
|
|
userId?: string,
|
|
): Promise<CommandResolution> {
|
|
void userId; // reserved for per-user biasing; see doc comment.
|
|
// Spacing- and case-tolerant: "Orange Cat" resolves the registered `orangecat`.
|
|
const namedInText = projectMentionedIn(text, projects);
|
|
const namedByAddress = projectNamedByAddress(text, projects);
|
|
|
|
// Fast path — "let's develop it" with a known project should dispatch, not chat.
|
|
if (DEVELOP_READY_RE.test(text)) {
|
|
const projectKey = pickProjectKey(projects, namedInText, selectedProject, true, namedByAddress);
|
|
return {
|
|
kind: "command",
|
|
projectKey,
|
|
intentId: "next_best",
|
|
prompt: text,
|
|
needsProject: !projectKey,
|
|
reason: "develop handoff",
|
|
};
|
|
}
|
|
|
|
// A personal action (calendar, reminder, a message to someone) is answered
|
|
// and drafted for approval on the chat path — never built, whatever
|
|
// project happens to be selected or is the only one there is. A bare "yes,
|
|
// do it" is the same: its meaning is in the previous answer, which only the
|
|
// chat path reads (see lib/loki/confirmation.ts).
|
|
const personal = isPersonalActionRequest(text);
|
|
if (personal || isBareConfirmation(text)) {
|
|
return {
|
|
kind: "chat",
|
|
projectKey: null,
|
|
intentId: null,
|
|
prompt: text,
|
|
needsProject: false,
|
|
reason: personal ? "personal action" : "reply to the previous answer",
|
|
};
|
|
}
|
|
|
|
// Fast path — imperative task with project context → dispatch, not Loki chat.
|
|
if (looksLikeDispatchTask(text)) {
|
|
const projectKey = pickProjectKey(projects, namedInText, selectedProject, true, namedByAddress);
|
|
if (projectKey) {
|
|
return {
|
|
kind: "command",
|
|
projectKey,
|
|
intentId: inferIntentFromText(text),
|
|
prompt: text,
|
|
needsProject: false,
|
|
reason: "action task",
|
|
};
|
|
}
|
|
}
|
|
|
|
try {
|
|
const out = await callGroqText(
|
|
`Projects: ${JSON.stringify(projects)}\nCurrently selected project: ${selectedProject ?? "none"}\nInput: ${text}`,
|
|
{
|
|
feature: "command-resolve",
|
|
systemPrompt: SYSTEM,
|
|
maxTokens: 220,
|
|
temperature: 0,
|
|
timeoutMs: 8000,
|
|
},
|
|
);
|
|
const raw = JSON.parse(out.replace(/^```(?:json)?\s*|\s*```$/g, "").trim()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
|
|
const llmProject =
|
|
typeof raw.projectKey === "string" && projects.includes(raw.projectKey)
|
|
? raw.projectKey
|
|
: null;
|
|
const projectKey = pickProjectKey(
|
|
projects,
|
|
llmProject ?? namedInText,
|
|
selectedProject,
|
|
false,
|
|
namedByAddress,
|
|
);
|
|
const intentId =
|
|
typeof raw.intentId === "string" &&
|
|
(ORCHESTRATION_TASK_INTENT_IDS as readonly string[]).includes(raw.intentId)
|
|
? (raw.intentId as OrchestrationTaskIntentId)
|
|
: null;
|
|
const kind = raw.kind === "chat" ? "chat" : "command";
|
|
const prompt = typeof raw.prompt === "string" && raw.prompt.trim() ? raw.prompt.trim() : text;
|
|
|
|
return {
|
|
kind,
|
|
projectKey,
|
|
intentId,
|
|
prompt,
|
|
needsProject: kind === "command" && !projectKey,
|
|
reason: typeof raw.reason === "string" ? raw.reason.slice(0, 60) : "",
|
|
};
|
|
} catch {
|
|
// LLM unavailable → degrade to a deterministic command: project from the
|
|
// text or the current selection; ask if neither. A question stays a
|
|
// question — queueing an agent to answer "are you able to…?" is the one
|
|
// degradation worse than a slower answer.
|
|
const projectKey = pickProjectKey(
|
|
projects,
|
|
namedInText,
|
|
selectedProject,
|
|
false,
|
|
namedByAddress,
|
|
);
|
|
if (readsAsQuestion(text.trim())) {
|
|
return {
|
|
kind: "chat",
|
|
projectKey,
|
|
intentId: null,
|
|
prompt: text,
|
|
needsProject: false,
|
|
reason: "question (no llm)",
|
|
};
|
|
}
|
|
return {
|
|
kind: "command",
|
|
projectKey,
|
|
intentId: null,
|
|
prompt: text,
|
|
needsProject: !projectKey,
|
|
reason: "deterministic (no llm)",
|
|
};
|
|
}
|
|
}
|