@carrieros/cli-staging 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +26 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +160 -0
- package/dist/commands/update.js +285 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +229 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +364 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +132 -0
- package/dist/services/api.js +441 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +384 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +416 -0
- package/dist/services/device-auth.js +288 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +42 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +115 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +730 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1622 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +414 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,1622 @@
|
|
|
1
|
+
import { rememberCommandDetails, clearCommandDetails } from "../ui/command-details.js";
|
|
2
|
+
import { getPermissionMode, permissionModeLabel, permissionPolicy, rememberPermissionMode } from "../services/permission-mode.js";
|
|
3
|
+
import { analysisExplanation, renderAgentPlan, renderAgentOutcome, renderFailureAnalysis, workflowActivity, toolActivity } from "../ui/agent-presentation.js";
|
|
4
|
+
import { ActiveChangeView } from "../ui/change-review.js";
|
|
5
|
+
import { screenTask } from "../ui/screen.js";
|
|
6
|
+
import { CodingWorkflow } from "../services/coding-workflow.js";
|
|
7
|
+
import { TurnReadCache } from "../services/local-tools.js";
|
|
8
|
+
import { containerRuntime, verifyContainerRuntime } from "../services/container-runner.js";
|
|
9
|
+
import { executionContract } from "../services/execution-platform.js";
|
|
10
|
+
import { ensureJobHelper } from "../services/job-helper.js";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import chalk from "chalk";
|
|
14
|
+
import { ApiError } from "../services/api.js";
|
|
15
|
+
import { PROVIDER_ERROR_REASONS } from "../services/chat-stream.js";
|
|
16
|
+
import { capitalize, errorLine, info, line, success } from "../services/output.js";
|
|
17
|
+
import { detectLocalFiles } from "../services/file-detect.js";
|
|
18
|
+
import { fileTypeLabel, formatSize, uploadAndAttach, UploadError } from "../services/file-upload.js";
|
|
19
|
+
import { sleep, withSpinner } from "../services/spinner.js";
|
|
20
|
+
import { c } from "../ui/colors.js";
|
|
21
|
+
import { renderProjectBrief, workspaceContextHint } from "../services/project-context.js";
|
|
22
|
+
import { declaredClientTools, declaredCommandTools, declaredMutationTools, handleClientToolCall, localCommandsState, submitWithRetry } from "../services/client-tools.js";
|
|
23
|
+
import { APPROVAL_TIMEOUT_MS } from "../services/mutations.js";
|
|
24
|
+
import { createRenderer, toolKind, toolSummary } from "../ui/conversation.js";
|
|
25
|
+
import { watchForInterrupt } from "../ui/interrupt.js";
|
|
26
|
+
import { renderChangeRejected, renderChangeSummary, renderGroup, renderNoLongerValid, renderValidationFailed } from "../ui/change-review.js";
|
|
27
|
+
import { approveInScreen } from "../ui/screen-prompt.js";
|
|
28
|
+
import { createMutationCoordinator } from "../services/mutation-coordinator.js";
|
|
29
|
+
import { createCommandCoordinator } from "../services/command-coordinator.js";
|
|
30
|
+
import { displayCommand } from "../services/command-policy.js";
|
|
31
|
+
import { workspaceRoot } from "../services/local-files.js";
|
|
32
|
+
import { parseTestReport, renderCommandReview, renderCommandSummary, summariseOutput } from "../ui/command-review.js";
|
|
33
|
+
import { checkUrl, openUrl } from "../services/open-url.js";
|
|
34
|
+
import { renderAllSources, renderComplete, memoryMarkerLine, renderCompleteLive, renderError, renderSources, renderSourcesLive, renderUserMessage, searchCompletionLine, startThinking, streamAssistant } from "../ui/chat-renderer.js";
|
|
35
|
+
import { startLiveComposer } from "../ui/live.js";
|
|
36
|
+
import { pickFromList } from "../ui/select.js";
|
|
37
|
+
import { clarifyIntent } from "../ui/sia-qa.js";
|
|
38
|
+
import { parseSiaContext } from "../services/sia.js";
|
|
39
|
+
import { isMemoryMarker } from "../types/index.js";
|
|
40
|
+
import { TaskFileLedger, repositoryContext, repositoryState } from "../services/task-context.js";
|
|
41
|
+
import { getWorkspace } from "../services/workspace.js";
|
|
42
|
+
import { renderTaskContextRestored } from "../ui/task-context-card.js";
|
|
43
|
+
import { fetchTaskContext } from "./task-context-view.js";
|
|
44
|
+
// Shared by the `chat` command REPL and the interactive shell so chat, mode and
|
|
45
|
+
// model logic lives in exactly one place (no duplicated business logic).
|
|
46
|
+
export const AUTO_LABEL = "Auto (mode default)";
|
|
47
|
+
// Process-lifetime caches — the mode/model lists are stable per run.
|
|
48
|
+
let modeCache = null;
|
|
49
|
+
let modelCache = null;
|
|
50
|
+
export async function loadModes(client) {
|
|
51
|
+
return (modeCache ??= await client.models());
|
|
52
|
+
}
|
|
53
|
+
export async function loadModels(client) {
|
|
54
|
+
return (modelCache ??= await client.chatModels());
|
|
55
|
+
}
|
|
56
|
+
export function currentModelId(ctx) {
|
|
57
|
+
return ctx.config.get("model") ?? "";
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The model Fast Mode runs on — the admin's choice, as the server names it
|
|
61
|
+
* (GET /v1/chat/availability), e.g. "Qwen 3.8 27B". Null when the server can't
|
|
62
|
+
* serve Fast Mode; undefined until asked.
|
|
63
|
+
*/
|
|
64
|
+
let fastModelCache;
|
|
65
|
+
export async function loadFastModel(client) {
|
|
66
|
+
if (fastModelCache !== undefined)
|
|
67
|
+
return fastModelCache;
|
|
68
|
+
const fm = (await client.chatAvailability().catch(() => null))?.fast_mode;
|
|
69
|
+
fastModelCache = fm?.available && fm.model ? { id: fm.model, label: fm.label || fm.model } : null;
|
|
70
|
+
return fastModelCache;
|
|
71
|
+
}
|
|
72
|
+
/** Fast Mode is on and in effect (Standard chat only). */
|
|
73
|
+
export function fastInEffect(ctx) {
|
|
74
|
+
return ctx.fast && ctx.chatType === "standard";
|
|
75
|
+
}
|
|
76
|
+
/** Short label for the prompt/banner ("Auto" or e.g. "GPT-5.5"); with Fast Mode on, the Fast model. */
|
|
77
|
+
export function modelLabelShort(ctx) {
|
|
78
|
+
if (fastInEffect(ctx) && fastModelCache)
|
|
79
|
+
return fastModelCache.label;
|
|
80
|
+
const id = currentModelId(ctx);
|
|
81
|
+
if (!id)
|
|
82
|
+
return "Auto";
|
|
83
|
+
return modelCache?.find((m) => m.id === id)?.label ?? id;
|
|
84
|
+
}
|
|
85
|
+
/** Display name for a mode. The default mode's API name is "Carrier OS" (that's
|
|
86
|
+
* the Carrier-chat brand), but in a MODE context we show it as "General" so it
|
|
87
|
+
* reads as one mode among the others (Reasoning, Code, …). */
|
|
88
|
+
export function modeName(m) {
|
|
89
|
+
return m.id === "general" ? "General" : capitalize(m.name);
|
|
90
|
+
}
|
|
91
|
+
/** Friendly label for the active Carrier mode — "General" for the default, else
|
|
92
|
+
* its display name. Falls back to a capitalized id until modes are loaded. */
|
|
93
|
+
export function modeLabelShort(ctx) {
|
|
94
|
+
const id = ctx.mode;
|
|
95
|
+
if (id === "general")
|
|
96
|
+
return "General";
|
|
97
|
+
return modeCache?.find((m) => m.id === id)?.name ?? capitalize(id);
|
|
98
|
+
}
|
|
99
|
+
function reportError(err) {
|
|
100
|
+
errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The next step for each error the API can return.
|
|
104
|
+
*
|
|
105
|
+
* The API already sends human wording (utils/chatErrors.js), so the CLI's job is
|
|
106
|
+
* not to restate the problem — it's to say what to DO about it, which only the
|
|
107
|
+
* client knows because only the client has the commands. A code with no obvious
|
|
108
|
+
* next step maps to nothing rather than filler advice.
|
|
109
|
+
*/
|
|
110
|
+
const ERROR_HINTS = {
|
|
111
|
+
INVALID_API_KEY: "/login",
|
|
112
|
+
NO_ACCOUNT: "/login",
|
|
113
|
+
AUTH_ERROR: "/login",
|
|
114
|
+
// Client-side: no credential was stored at all (never signed in, or a dead
|
|
115
|
+
// refresh token cleared the session mid-run).
|
|
116
|
+
NOT_AUTHENTICATED: "/login",
|
|
117
|
+
// Server-side counterpart, if a request ever leaves without the header.
|
|
118
|
+
MISSING_API_KEY: "/login",
|
|
119
|
+
// Context overflow: a new conversation is the one reliable fix, and a
|
|
120
|
+
// roomier model is the other.
|
|
121
|
+
MCAI_BLOCKED: "/new",
|
|
122
|
+
// The model's context limit cannot be verified (a server configuration
|
|
123
|
+
// gap): another model is the fix, not a shorter message.
|
|
124
|
+
MCAI_UNVERIFIED: "/model",
|
|
125
|
+
SESSION_NOT_FOUND: "/sessions",
|
|
126
|
+
CARRIER_CHAT_MAINTENANCE: "/switch standard",
|
|
127
|
+
// Out of credit on this model — pick another rather than retrying into the
|
|
128
|
+
// same wall. (The server substitutes when it can; this is when it couldn't.)
|
|
129
|
+
PROVIDER_EXHAUSTED: "/model",
|
|
130
|
+
USAGE_LIMIT_REACHED: "/usage",
|
|
131
|
+
// Wallet empty — /usage is where the balance and spend live.
|
|
132
|
+
INSUFFICIENT_CREDITS: "/usage",
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* The abort signal for a turn, and how to stop listening for it.
|
|
136
|
+
*
|
|
137
|
+
* THERE IS ONE OWNER OF STDIN. When the caller supplies a signal — the shell
|
|
138
|
+
* does, because its composer keeps reading while the turn runs — the turn must
|
|
139
|
+
* NOT attach its own stdin listener, or two consumers fight over every
|
|
140
|
+
* keystroke. Standalone `cos chat` has no composer, so there it still watches
|
|
141
|
+
* stdin itself for Ctrl+C.
|
|
142
|
+
*/
|
|
143
|
+
function turnAbort(external) {
|
|
144
|
+
const controller = new AbortController();
|
|
145
|
+
if (external) {
|
|
146
|
+
// Linked rather than reused, so the turn itself can also stop (Ctrl+C at a
|
|
147
|
+
// change approval) without reaching into the shell's controller.
|
|
148
|
+
const forward = () => controller.abort();
|
|
149
|
+
if (external.aborted)
|
|
150
|
+
controller.abort();
|
|
151
|
+
else
|
|
152
|
+
external.addEventListener("abort", forward, { once: true });
|
|
153
|
+
return {
|
|
154
|
+
signal: controller.signal,
|
|
155
|
+
abort: () => controller.abort(),
|
|
156
|
+
stopWatching: () => external.removeEventListener("abort", forward)
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const stop = watchForInterrupt(() => controller.abort());
|
|
160
|
+
return { signal: controller.signal, abort: () => controller.abort(), stopWatching: stop };
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What a turn cost, taken from the response rather than computed here.
|
|
164
|
+
*
|
|
165
|
+
* The CLI never estimates spend: the model can be substituted when a provider
|
|
166
|
+
* is out of credit, so any local arithmetic would price the wrong model. Fields
|
|
167
|
+
* the API didn't send are simply omitted from the footer.
|
|
168
|
+
*/
|
|
169
|
+
/**
|
|
170
|
+
* Add a finished turn's real debit to the session total.
|
|
171
|
+
*
|
|
172
|
+
* Separate from rendering on purpose: a turn that searched the web prints a
|
|
173
|
+
* different footer and never builds a TurnSpend, and its credits must still
|
|
174
|
+
* count toward "this session".
|
|
175
|
+
*/
|
|
176
|
+
function recordTurnSpend(ctx, result) {
|
|
177
|
+
if (typeof result.credits_spent === "number") {
|
|
178
|
+
ctx.sessionCreditsSpent += result.credits_spent;
|
|
179
|
+
ctx.sessionSpendKnown = true;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function spendOf(result, ctx) {
|
|
183
|
+
return {
|
|
184
|
+
tokens: result.tokens_used,
|
|
185
|
+
costUsd: result.cost_usd,
|
|
186
|
+
creditsRemaining: result.credits_remaining ?? undefined,
|
|
187
|
+
unlimited: result.credits_unlimited ?? undefined,
|
|
188
|
+
sessionSpent: ctx?.sessionSpendKnown ? ctx.sessionCreditsSpent : undefined
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** True when the turn was cancelled by the user rather than failing. */
|
|
192
|
+
function wasAborted(err) {
|
|
193
|
+
return err instanceof ApiError && err.code === "ABORTED";
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Ctrl+C during a turn. Deliberately NOT an error block — the user did this on
|
|
197
|
+
* purpose, so it gets one quiet line and the prompt back.
|
|
198
|
+
*
|
|
199
|
+
* Chat now streams, and closing the stream cancels the model call server-side,
|
|
200
|
+
* so the old "the turn may still be charged" warning would overstate it. What
|
|
201
|
+
* was already generated (and any input already processed) is still recorded —
|
|
202
|
+
* the server keeps the partial answer — so the note says the reply stopped, not
|
|
203
|
+
* that nothing happened.
|
|
204
|
+
*/
|
|
205
|
+
function renderInterrupted() {
|
|
206
|
+
line(" " + c.warn("✗") + " " + c.dim("Cancelled — anything generated so far is kept in the session."));
|
|
207
|
+
line();
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Codes that all mean the same thing to a person: you are not signed in. They
|
|
211
|
+
* differ only in WHERE that was discovered — locally before the request, or by
|
|
212
|
+
* the API after it — which is an implementation detail, not something to show.
|
|
213
|
+
*/
|
|
214
|
+
const SIGNED_OUT = new Set(["NOT_AUTHENTICATED", "MISSING_API_KEY", "INVALID_API_KEY"]);
|
|
215
|
+
function errorTitle(err) {
|
|
216
|
+
return SIGNED_OUT.has(err.code) ? "You're not signed in" : err.message;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The API already sends human wording, so the default is just to name the code
|
|
220
|
+
* for support. The exceptions are the failures where the code tells the user
|
|
221
|
+
* nothing they can act on.
|
|
222
|
+
*/
|
|
223
|
+
function errorDetail(err) {
|
|
224
|
+
if (SIGNED_OUT.has(err.code)) {
|
|
225
|
+
return "Your session has expired, or you haven't signed in on this machine yet.";
|
|
226
|
+
}
|
|
227
|
+
// Network failures are about the endpoint, not the request — name it, since
|
|
228
|
+
// a wrong --url is the usual cause and no amount of retrying fixes it.
|
|
229
|
+
if (err.code === "NETWORK_ERROR")
|
|
230
|
+
return "Check the API is running, then try again.";
|
|
231
|
+
if (err.code === "INSUFFICIENT_CREDITS") {
|
|
232
|
+
return "Nothing was charged for this message.";
|
|
233
|
+
}
|
|
234
|
+
if (err.code === "TASK_TOO_LARGE_FOR_MODEL") {
|
|
235
|
+
return "Try splitting the coding work into smaller steps and send them one at a time.";
|
|
236
|
+
}
|
|
237
|
+
// The server's structured reason names the kind of provider failure.
|
|
238
|
+
return err.reason ? `${PROVIDER_ERROR_REASONS[err.reason]} · Error code: ${err.code}` : `Error code: ${err.code}`;
|
|
239
|
+
}
|
|
240
|
+
/** Render an API failure with its cause and the command that addresses it. */
|
|
241
|
+
function renderApiError(err) {
|
|
242
|
+
if (wasAborted(err)) {
|
|
243
|
+
renderInterrupted();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (!(err instanceof ApiError)) {
|
|
247
|
+
renderError("Something went wrong", err.message);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (err.code === "CARRIER_CHAT_MAINTENANCE") {
|
|
251
|
+
showCarrierMaintenance();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
// Running out of credits is a state to act on, not a fault — a red × made a
|
|
255
|
+
// billing prompt look like a crash.
|
|
256
|
+
const tone = err.code === "INSUFFICIENT_CREDITS" ? "warn" : "error";
|
|
257
|
+
renderError(errorTitle(err), errorDetail(err), ERROR_HINTS[err.code], tone);
|
|
258
|
+
}
|
|
259
|
+
/** The API owns availability and session identity. A stored Standard session
|
|
260
|
+
* cannot be continued under a Carrier label (or vice versa). The old chat is
|
|
261
|
+
* untouched and remains available through /sessions. */
|
|
262
|
+
export async function syncChatAvailability(ctx, client) {
|
|
263
|
+
const sessionId = ctx.config.get("sessionId");
|
|
264
|
+
const state = await client.chatAvailability(sessionId);
|
|
265
|
+
ctx.carrierMaintenance = state.carrier_chat_maintenance;
|
|
266
|
+
if (sessionId && state.session_chat_type !== ctx.chatType) {
|
|
267
|
+
ctx.config.set("sessionId", undefined);
|
|
268
|
+
ctx.config.set("sessionTitle", undefined);
|
|
269
|
+
line(" " + c.warn("⚠") + " " + c.dim("The saved chat belongs to another chat type. It remains in /sessions; a new chat will start here."));
|
|
270
|
+
}
|
|
271
|
+
return state;
|
|
272
|
+
}
|
|
273
|
+
export function showCarrierMaintenance() {
|
|
274
|
+
renderError("Carrier Chat is under maintenance", "Sending is paused while we upgrade it. You can still read existing chats. It'll be back — and a lot more powerful.", "/switch standard", "warn");
|
|
275
|
+
}
|
|
276
|
+
/** Checks immediately before any model turn; the initial shell banner is only
|
|
277
|
+
* advisory, because the admin can change the switch while the CLI stays open. */
|
|
278
|
+
async function allowChatTurn(ctx, client) {
|
|
279
|
+
try {
|
|
280
|
+
const state = await syncChatAvailability(ctx, client);
|
|
281
|
+
if (ctx.chatType === "carrier" && state.carrier_chat_maintenance) {
|
|
282
|
+
showCarrierMaintenance();
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
catch (err) {
|
|
288
|
+
renderApiError(err);
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Cache a newly-created conversation's title for the footer. Best-effort and
|
|
294
|
+
* deliberately un-awaited — a title is cosmetic, so it must never delay a reply
|
|
295
|
+
* or surface an error of its own.
|
|
296
|
+
*/
|
|
297
|
+
/**
|
|
298
|
+
* Say so when a different model answered than the one selected.
|
|
299
|
+
*
|
|
300
|
+
* The API substitutes a working model when the requested provider has run out
|
|
301
|
+
* of credit. That's the right behaviour — an answer beats a 404 — but it must
|
|
302
|
+
* never be silent, or the footer keeps claiming a model that didn't reply and
|
|
303
|
+
* the cost lands on a different line item than expected.
|
|
304
|
+
*/
|
|
305
|
+
function noteModelSubstitution(ctx, answered) {
|
|
306
|
+
if (!answered)
|
|
307
|
+
return null;
|
|
308
|
+
// Fast mode and Auto MODE both hand model choice to the backend, so a
|
|
309
|
+
// different answering model is expected routing — not the model you picked
|
|
310
|
+
// being unavailable. Reporting it as unavailability was alarming and wrong:
|
|
311
|
+
// in Auto, your selection is a preference the router may override by design.
|
|
312
|
+
const delegated = ctx.fast || ctx.mode === "auto";
|
|
313
|
+
const asked = delegated ? "" : currentModelId(ctx);
|
|
314
|
+
if (!asked || asked === answered)
|
|
315
|
+
return null;
|
|
316
|
+
const label = modelCache?.find((m) => m.id === answered)?.label ?? answered;
|
|
317
|
+
const askedLabel = modelCache?.find((m) => m.id === asked)?.label ?? asked;
|
|
318
|
+
return `${askedLabel} was unavailable — answered with ${label}.`;
|
|
319
|
+
}
|
|
320
|
+
async function learnSessionTitle(ctx, client, sessionId) {
|
|
321
|
+
try {
|
|
322
|
+
const s = await client.session(sessionId);
|
|
323
|
+
// Guard against a race: the user may have switched conversations while this
|
|
324
|
+
// was in flight, and overwriting the title then would mislabel the footer.
|
|
325
|
+
if (ctx.config.get("sessionId") === sessionId && s.title) {
|
|
326
|
+
ctx.config.set("sessionTitle", s.title);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
/* cosmetic only — leave the footer unnamed */
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Echo the prompt the way the user wrote it.
|
|
335
|
+
*
|
|
336
|
+
* When SIA has run, the string being sent carries an appended
|
|
337
|
+
* `[Clarification Context]` block — machine payload the model reads, not
|
|
338
|
+
* something to show raw. The website splits it the same way when rendering the
|
|
339
|
+
* transcript, so this keeps the two clients showing the same conversation.
|
|
340
|
+
*/
|
|
341
|
+
function renderPrompt(message, alreadyEchoed = false) {
|
|
342
|
+
const parsed = parseSiaContext(message);
|
|
343
|
+
if (!parsed) {
|
|
344
|
+
if (!alreadyEchoed)
|
|
345
|
+
renderUserMessage(message);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (!alreadyEchoed)
|
|
349
|
+
renderUserMessage(parsed.displayPrompt);
|
|
350
|
+
renderSiaContext(message);
|
|
351
|
+
}
|
|
352
|
+
/** The clarification answers SIA added, as dim continuation lines. */
|
|
353
|
+
function renderSiaContext(message) {
|
|
354
|
+
const parsed = parseSiaContext(message);
|
|
355
|
+
if (!parsed)
|
|
356
|
+
return;
|
|
357
|
+
for (const item of parsed.items) {
|
|
358
|
+
line(" " + c.dim("↳ " + item.label + ": ") + c.value(item.value));
|
|
359
|
+
}
|
|
360
|
+
line();
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Send one chat turn using the config's current mode + model, and render it.
|
|
364
|
+
* When `opts.footer` is supplied (the interactive shell), the input bar stays
|
|
365
|
+
* pinned at the bottom and the response streams above it; otherwise (the plain
|
|
366
|
+
* `chat` REPL) output just prints inline.
|
|
367
|
+
*/
|
|
368
|
+
/**
|
|
369
|
+
* Prefix the outgoing message with the project brief when one is armed.
|
|
370
|
+
*
|
|
371
|
+
* Applied to the REQUEST and not to the prompt: the brief is context for the
|
|
372
|
+
* model, not something the user typed, so it must never turn up in the echoed
|
|
373
|
+
* transcript or in the history the composer scrolls through.
|
|
374
|
+
*
|
|
375
|
+
* Cleared after a single send. The conversation keeps it in history from then
|
|
376
|
+
* on, so re-sending it every turn would pay for the same tokens repeatedly and
|
|
377
|
+
* push the real message further from the model's attention.
|
|
378
|
+
*
|
|
379
|
+
* Never allowed to break a turn: if the walk fails for any reason the message
|
|
380
|
+
* goes out exactly as it would have before.
|
|
381
|
+
*/
|
|
382
|
+
function withProjectContext(ctx, message) {
|
|
383
|
+
try {
|
|
384
|
+
// The opt-in brief already lists the workspace repositories, so send it when
|
|
385
|
+
// pending; otherwise attach the lightweight always-on workspace context so
|
|
386
|
+
// the model still knows the repositories exist. In single-repository mode
|
|
387
|
+
// workspaceContextHint() is null, so nothing is added (unchanged behaviour).
|
|
388
|
+
if (ctx.config.get("projectContextPending") === true) {
|
|
389
|
+
const brief = renderProjectBrief();
|
|
390
|
+
ctx.config.set("projectContextPending", false);
|
|
391
|
+
return `${brief}\n\n${message}`;
|
|
392
|
+
}
|
|
393
|
+
const ws = workspaceContextHint();
|
|
394
|
+
return ws ? `${ws}\n\n${message}` : message;
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return message;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
export async function chatTurn(ctx, client, message, opts = {}) {
|
|
401
|
+
if (!(await allowChatTurn(ctx, client)))
|
|
402
|
+
return;
|
|
403
|
+
// SIA rewrites the prompt, so it has to resolve before EITHER render path
|
|
404
|
+
// starts — the merged text is what gets echoed, sent and stored. A read-only
|
|
405
|
+
// task (a review) is fixed, not an ambiguous request, so it never clarifies.
|
|
406
|
+
let echoed = false;
|
|
407
|
+
if (ctx.sia && !opts.readOnly && !opts.sendAs && process.stdin.isTTY) {
|
|
408
|
+
// Echo BEFORE the questions. On the web the prompt stays sitting in the
|
|
409
|
+
// composer while the overlay opens beneath it, so it is always in view;
|
|
410
|
+
// in a terminal the questions would otherwise be the first thing on screen
|
|
411
|
+
// with no sign of what they are even about.
|
|
412
|
+
renderUserMessage(message);
|
|
413
|
+
echoed = true;
|
|
414
|
+
const result = await clarifyIntent(client, message);
|
|
415
|
+
if (result.cancelled) {
|
|
416
|
+
line();
|
|
417
|
+
line(" " + c.warn("⊘") + " " + c.dim("Cancelled — nothing sent."));
|
|
418
|
+
line();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
message = result.prompt;
|
|
422
|
+
}
|
|
423
|
+
const useLiveBar = opts.footer !== undefined && process.stdout.isTTY && process.env.TERM !== "dumb";
|
|
424
|
+
if (useLiveBar) {
|
|
425
|
+
await chatTurnLive(ctx, client, message, opts.footer ?? "", opts.webSearch, echoed, opts.signal, { readOnly: opts.readOnly, sendAs: opts.sendAs });
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const mode = ctx.mode;
|
|
429
|
+
const model = currentModelId(ctx);
|
|
430
|
+
// An explicit override (a one-shot `/websearch <query>`) beats the armed flag
|
|
431
|
+
// and the persisted preference, and leaves both untouched.
|
|
432
|
+
const webSearch = opts.webSearch ?? ctx.effectiveWebSearch;
|
|
433
|
+
renderPrompt(message, echoed);
|
|
434
|
+
const started = Date.now();
|
|
435
|
+
let spinner = startThinking();
|
|
436
|
+
const { signal, stopWatching } = turnAbort(opts.signal);
|
|
437
|
+
try {
|
|
438
|
+
const sessionId = ctx.config.get("sessionId");
|
|
439
|
+
const attached = ctx.attachedFileIds;
|
|
440
|
+
const result = await client.chatStream({
|
|
441
|
+
mode,
|
|
442
|
+
message: opts.sendAs ?? withProjectContext(ctx, message),
|
|
443
|
+
session_id: sessionId,
|
|
444
|
+
model: model || undefined,
|
|
445
|
+
chat_type: ctx.chatType,
|
|
446
|
+
web_search: webSearch,
|
|
447
|
+
speed: ctx.fast ? "fast" : undefined,
|
|
448
|
+
high_power: ctx.highPower ? true : undefined,
|
|
449
|
+
file_ids: attached.length ? attached : undefined,
|
|
450
|
+
client_tools: declaredClientTools(ctx)
|
|
451
|
+
}, {
|
|
452
|
+
// A local tool step is committed as its own quiet line; the spinner is
|
|
453
|
+
// paused around it so the two never draw over each other.
|
|
454
|
+
// (non-live path declares only read tools already — read-only by construction)
|
|
455
|
+
onClientToolCall: (call) => handleClientToolCall(ctx, client, call, {
|
|
456
|
+
onStart: (label) => {
|
|
457
|
+
spinner.stop();
|
|
458
|
+
line(" " + c.dim(`● ${label}`));
|
|
459
|
+
spinner = startThinking();
|
|
460
|
+
}
|
|
461
|
+
})
|
|
462
|
+
}, signal);
|
|
463
|
+
spinner.stop();
|
|
464
|
+
// A bare /websearch arms exactly one turn — spend it whether or not the
|
|
465
|
+
// turn ended up searching, so the footer never lies about what's pending.
|
|
466
|
+
if (opts.webSearch === undefined)
|
|
467
|
+
ctx.disarmWebSearch();
|
|
468
|
+
// Persist the session so the conversation continues across turns/invocations.
|
|
469
|
+
if (result.session_id && result.session_id !== sessionId) {
|
|
470
|
+
ctx.config.set("sessionId", result.session_id);
|
|
471
|
+
rememberPermissionMode(ctx.config);
|
|
472
|
+
// The chat response carries no title, and the backend generates one from
|
|
473
|
+
// the first message — fetch it once, in the background, so the footer can
|
|
474
|
+
// name the conversation without delaying the reply. Failure is silent:
|
|
475
|
+
// the footer simply stays unnamed.
|
|
476
|
+
void learnSessionTitle(ctx, client, result.session_id);
|
|
477
|
+
}
|
|
478
|
+
const sources = result.sources ?? [];
|
|
479
|
+
ctx.recordSearch(sources);
|
|
480
|
+
await streamAssistant(result.response);
|
|
481
|
+
const swapped = noteModelSubstitution(ctx, result.model);
|
|
482
|
+
if (swapped)
|
|
483
|
+
line(" " + c.warn("!") + " " + c.dim(swapped));
|
|
484
|
+
renderSources(sources);
|
|
485
|
+
recordTurnSpend(ctx, result);
|
|
486
|
+
const elapsed = (Date.now() - started) / 1000;
|
|
487
|
+
// One footer per turn: the search line already carries the duration, so
|
|
488
|
+
// printing the generic one underneath would just repeat it.
|
|
489
|
+
if (sources.length > 0) {
|
|
490
|
+
line(searchCompletionLine(sources.length, elapsed));
|
|
491
|
+
line();
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
renderComplete(elapsed, spendOf(result, ctx));
|
|
495
|
+
void showNewMemoryMarkers(ctx, client, result.session_id);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
catch (err) {
|
|
499
|
+
spinner.stop();
|
|
500
|
+
if (signal.aborted)
|
|
501
|
+
line(" ⊘ Cancelled — the turn stopped.");
|
|
502
|
+
else
|
|
503
|
+
renderApiError(err);
|
|
504
|
+
}
|
|
505
|
+
finally {
|
|
506
|
+
// Always detach, so the composer's own Ctrl+C (arm-then-exit) works again.
|
|
507
|
+
stopWatching();
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/** What the prompt asks, in the plan's own terms. */
|
|
511
|
+
function approvalQuestion(plans, correction = false) {
|
|
512
|
+
if (correction)
|
|
513
|
+
return plans.length > 1 ? `Approve all ${plans.length} corrective changes?` : "Approve this correction?";
|
|
514
|
+
if (plans.length > 1)
|
|
515
|
+
return `Approve all ${plans.length} changes?`;
|
|
516
|
+
switch (plans[0]?.name) {
|
|
517
|
+
case "revert_change":
|
|
518
|
+
return "Undo this change?";
|
|
519
|
+
case "delete_file":
|
|
520
|
+
return "Delete this file?";
|
|
521
|
+
case "create_file":
|
|
522
|
+
return "Create this file?";
|
|
523
|
+
default:
|
|
524
|
+
return "Approve this change?";
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/** "Running the project tests" reads better than the argv on an activity line. */
|
|
528
|
+
function commandActivityLabel(d) {
|
|
529
|
+
if (d.script)
|
|
530
|
+
return `Running the ${d.script.name} script`;
|
|
531
|
+
if (d.program === "git")
|
|
532
|
+
return `Checking git ${d.args[0] ?? "status"}`;
|
|
533
|
+
return `Running ${d.program}`;
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* chatTurn with the sticky bottom input bar + an activity timeline. The turn
|
|
537
|
+
* emits phase "events" (request_started → mode_selected → request_sent →
|
|
538
|
+
* waiting → done) as `activity.step()` calls; the real API request is fired up
|
|
539
|
+
* front so the timeline overlays the genuine wait (adding no latency), then the
|
|
540
|
+
* timeline collapses and the answer streams in word-by-word.
|
|
541
|
+
*/
|
|
542
|
+
async function chatTurnLive(ctx, client, message, footer, webSearchOverride,
|
|
543
|
+
/** The prompt was already echoed above the SIA questions — print only the
|
|
544
|
+
* answers, so it doesn't appear twice. */
|
|
545
|
+
alreadyEchoed = false,
|
|
546
|
+
/** Supplied by the shell, which owns stdin and therefore owns Ctrl+C. */
|
|
547
|
+
externalSignal,
|
|
548
|
+
/** A read-only turn declares no mutation/command tools; sendAs overrides the payload. */
|
|
549
|
+
turnOpts = {}) {
|
|
550
|
+
const mode = ctx.mode;
|
|
551
|
+
const model = currentModelId(ctx);
|
|
552
|
+
const sessionId = ctx.config.get("sessionId");
|
|
553
|
+
const webSearch = webSearchOverride ?? ctx.effectiveWebSearch;
|
|
554
|
+
clearCommandDetails(ctx);
|
|
555
|
+
const live = startLiveComposer(footer);
|
|
556
|
+
// One owner for everything this turn draws: the user's message, activity,
|
|
557
|
+
// approval cards, command output and the answer (see ui/conversation.ts).
|
|
558
|
+
const ui = createRenderer(live);
|
|
559
|
+
if (!alreadyEchoed)
|
|
560
|
+
ui.user(message);
|
|
561
|
+
renderSiaContext(message);
|
|
562
|
+
const started = Date.now();
|
|
563
|
+
// Ctrl+C aborts the request. The activity timeline is a client-side animation
|
|
564
|
+
// over a real await, so cancelling has to cut the HTTP call — stopping the
|
|
565
|
+
// spinner alone would leave the turn running invisibly.
|
|
566
|
+
const { signal, abort, stopWatching } = turnAbort(externalSignal);
|
|
567
|
+
// One prompt at a time: a file-change review and a command approval in the
|
|
568
|
+
// same step would otherwise both try to own the keyboard.
|
|
569
|
+
let terminal = Promise.resolve();
|
|
570
|
+
const withTerminal = (fn) => {
|
|
571
|
+
const run = terminal.then(fn, fn);
|
|
572
|
+
terminal = run.catch(() => undefined);
|
|
573
|
+
return run;
|
|
574
|
+
};
|
|
575
|
+
/**
|
|
576
|
+
* What the assistant has said so far.
|
|
577
|
+
*
|
|
578
|
+
* The model narrates as it works — a line before it reads something, another
|
|
579
|
+
* before it runs the tests — and those lines are the conversation. Text is
|
|
580
|
+
* committed at each boundary (a tool call, or the end of the turn), so a
|
|
581
|
+
* progress message lands ABOVE the activity it describes instead of arriving
|
|
582
|
+
* after everything as one block.
|
|
583
|
+
*/
|
|
584
|
+
let streamed = "";
|
|
585
|
+
let shown = 0;
|
|
586
|
+
const say = (upTo = streamed) => {
|
|
587
|
+
const text = upTo.slice(shown);
|
|
588
|
+
shown = upTo.length;
|
|
589
|
+
if (text.trim())
|
|
590
|
+
ui.assistant(text);
|
|
591
|
+
};
|
|
592
|
+
// A read-only turn (a review) offers NEITHER mutation nor command tools, so
|
|
593
|
+
// the model cannot change files or run commands whatever the prompt says.
|
|
594
|
+
// Plan mode uses the same gate. The mode is fixed for the turn, so switching
|
|
595
|
+
// it while a review is open never changes what this turn may do.
|
|
596
|
+
const permissionMode = getPermissionMode(ctx.config);
|
|
597
|
+
const permission = permissionPolicy(permissionMode);
|
|
598
|
+
const mutationTools = turnOpts.readOnly || !permission.changeTools ? undefined : declaredMutationTools(ctx);
|
|
599
|
+
const commandTools = turnOpts.readOnly || !permission.commands ? undefined : declaredCommandTools(ctx, undefined, permissionMode === "auto");
|
|
600
|
+
const commandState = localCommandsState(ctx, undefined, permissionMode === "auto");
|
|
601
|
+
const commandHint = turnOpts.readOnly
|
|
602
|
+
? "[LOCAL TOOL AVAILABILITY] This is a read-only turn; terminal commands are unavailable."
|
|
603
|
+
: !permission.commands
|
|
604
|
+
? "[LOCAL TOOL AVAILABILITY] Plan permission mode is active; terminal commands are unavailable."
|
|
605
|
+
: commandTools
|
|
606
|
+
? "[LOCAL TOOL AVAILABILITY] run_command is available. Manual/Accept Edits require command approval; Auto runs locally permitted commands without an individual prompt."
|
|
607
|
+
: !commandState.enabled
|
|
608
|
+
? ctx.config.get("localCommandsEnabled") === false
|
|
609
|
+
? "[LOCAL TOOL AVAILABILITY] Local commands were explicitly disabled with `/settings commands off`; the model has no run_command tool."
|
|
610
|
+
: "[LOCAL TOOL AVAILABILITY] Local commands are off. In Manual or Accept Edits, enable them with `/settings commands on`; selecting Auto opts in for the session."
|
|
611
|
+
: `[LOCAL TOOL AVAILABILITY] run_command is unavailable: ${commandState.blockedBy ?? "the interactive command tool is not available in this session"}. Do not claim that a command ran.`;
|
|
612
|
+
let taskView;
|
|
613
|
+
// What the final card needs that the workflow snapshot does not carry: why a
|
|
614
|
+
// change stopped (from the coordinator's recorded result codes) and the last
|
|
615
|
+
// validation's counts (from the actual command output). Display only.
|
|
616
|
+
const turnOutcome = {};
|
|
617
|
+
// Complete reads delivered to the model this turn. Tool results are not
|
|
618
|
+
// replayed into later turns, so reuse never outlives the turn.
|
|
619
|
+
const readCache = new TurnReadCache();
|
|
620
|
+
const workflow = mutationTools ? new CodingWorkflow(async () => {
|
|
621
|
+
if (!commandTools)
|
|
622
|
+
throw new Error("Secure verification commands are unavailable. Enable local commands and configure the required runtime before planning changes.");
|
|
623
|
+
const contract = executionContract();
|
|
624
|
+
if (contract.capability === "UNSUPPORTED")
|
|
625
|
+
throw new Error(contract.prerequisite);
|
|
626
|
+
if (contract.capability === "ISOLATED_RUNTIME_REQUIRED")
|
|
627
|
+
await verifyContainerRuntime(containerRuntime());
|
|
628
|
+
else
|
|
629
|
+
ensureJobHelper();
|
|
630
|
+
return contract;
|
|
631
|
+
}, lines => {
|
|
632
|
+
// Close the investigation step first, so its record sits ABOVE the plan it led to.
|
|
633
|
+
if (lines[0]?.startsWith("Plan:")) {
|
|
634
|
+
ui.stepEnd();
|
|
635
|
+
const snap = workflow.snapshot();
|
|
636
|
+
if (!turnOutcome.task && !Number(snap.corrections))
|
|
637
|
+
turnOutcome.task = snap.plan?.summary;
|
|
638
|
+
ui.commit(renderAgentPlan(snap, { rootCause: turnOutcome.rootCause }));
|
|
639
|
+
}
|
|
640
|
+
else if (lines[0]?.startsWith("Failure analysis")) {
|
|
641
|
+
ui.stepEnd();
|
|
642
|
+
turnOutcome.rootCause = analysisExplanation(lines).explanation;
|
|
643
|
+
ui.commit(renderFailureAnalysis(lines));
|
|
644
|
+
}
|
|
645
|
+
taskView?.refresh();
|
|
646
|
+
}, { signal, recoveryScope: () => client.mutationRecoveryScope(), onReadsInvalidated: () => readCache.invalidate() }) : undefined;
|
|
647
|
+
taskView = workflow ? new ActiveChangeView(() => workflow.snapshot(), screenTask) : undefined;
|
|
648
|
+
const mutations = mutationTools
|
|
649
|
+
? createMutationCoordinator({
|
|
650
|
+
signal,
|
|
651
|
+
approvalContext: () => workflow?.approvalContext(),
|
|
652
|
+
recoveryScope: () => client.mutationRecoveryScope(),
|
|
653
|
+
validatePlans: plans => workflow?.beforeMutation(plans),
|
|
654
|
+
approveEditsByPolicy: () => permission.approveEditsByPolicy,
|
|
655
|
+
// Recorded before delivery: an immediate reply finds the change already recorded.
|
|
656
|
+
record: payload => workflow?.mutationResult(payload),
|
|
657
|
+
submit: async (payload) => {
|
|
658
|
+
await submitWithRetry(client, payload);
|
|
659
|
+
taskView?.result(payload);
|
|
660
|
+
const code = payload.ok ? undefined : payload.error?.code;
|
|
661
|
+
if (code === "MUTATION_REJECTED" || code === "STALE_FILE") {
|
|
662
|
+
turnOutcome.declined = code === "MUTATION_REJECTED" ? "rejected" : "invalidated";
|
|
663
|
+
turnOutcome.declinedOperations = [...(turnOutcome.declinedOperations ?? []), payload.tool_call_id];
|
|
664
|
+
}
|
|
665
|
+
},
|
|
666
|
+
ui: {
|
|
667
|
+
review: (plans) => withTerminal(() => ui.borrow(async () => {
|
|
668
|
+
ui.stepEnd();
|
|
669
|
+
taskView?.review(plans);
|
|
670
|
+
const snapshot = workflow?.snapshot();
|
|
671
|
+
const planned = snapshot?.plan?.files ?? [];
|
|
672
|
+
const applied = (snapshot?.files ?? []);
|
|
673
|
+
const remaining = planned.filter(file => !applied.includes(file.path) && !plans.some(plan => plan.rel === file.path)).length;
|
|
674
|
+
ui.commit(renderGroup(plans, Number(snapshot?.corrections ?? 0) > 0, remaining, workspaceRoot()));
|
|
675
|
+
const question = approvalQuestion(plans, Number(snapshot?.corrections ?? 0) > 0);
|
|
676
|
+
const answer = await approveInScreen({ question, timeoutMs: APPROVAL_TIMEOUT_MS, signal });
|
|
677
|
+
workflow?.approval(answer);
|
|
678
|
+
taskView?.decision(plans, answer);
|
|
679
|
+
return answer;
|
|
680
|
+
})),
|
|
681
|
+
// Accept Edits: the same review card, marked as approved by the session's
|
|
682
|
+
// policy instead of asking; the coordinator's checks still follow.
|
|
683
|
+
approvedByPolicy: (plans) => {
|
|
684
|
+
ui.stepEnd();
|
|
685
|
+
taskView?.review(plans);
|
|
686
|
+
ui.commit([...renderGroup(plans, false, 0, workspaceRoot()), " " + c.accent("✓ Approved by " + permissionModeLabel(getPermissionMode(ctx.config))) + c.dim(getPermissionMode(ctx.config) === "auto" ? " — locally permitted commands run too; /settings commands off blocks them · /permissions to change" : " — commands still ask · /permissions to change"), ""]);
|
|
687
|
+
workflow?.approval("approve");
|
|
688
|
+
taskView?.decision(plans, "approve");
|
|
689
|
+
},
|
|
690
|
+
note: (lines) => ui.commit([...renderChangeSummary(lines), ""]),
|
|
691
|
+
noLongerValid: (rels) => { turnOutcome.declinedFiles = rels; ui.commit(renderNoLongerValid(rels)); },
|
|
692
|
+
rejected: (plans) => { turnOutcome.declinedFiles = plans.map((p) => p.rel); ui.commit(renderChangeRejected(plans)); },
|
|
693
|
+
// Refused before review (could not be planned, or blocked): say so, and why.
|
|
694
|
+
refused: (r) => ui.commit([` ${c.warn("⚠")} ${c.value("Change proposal refused")}${r.files.length ? c.dim(` · ${r.files.join(", ")}`) : ""}`, ` ${c.dim(r.message)}`, ""]),
|
|
695
|
+
cancelTurn: abort
|
|
696
|
+
}
|
|
697
|
+
})
|
|
698
|
+
: undefined;
|
|
699
|
+
let lastCommandOutput;
|
|
700
|
+
let commands;
|
|
701
|
+
if (commandTools) {
|
|
702
|
+
const auth = ctx.config.get("auth");
|
|
703
|
+
commands = createCommandCoordinator({
|
|
704
|
+
root: workspaceRoot(),
|
|
705
|
+
signal,
|
|
706
|
+
withTerminal,
|
|
707
|
+
recoveryScope: () => client.mutationRecoveryScope(),
|
|
708
|
+
approvalContext: () => workflow?.approvalContext(),
|
|
709
|
+
cliSecrets: [auth?.accessToken, auth?.refreshToken, ctx.config.get("secretKey")].filter((v) => typeof v === "string"),
|
|
710
|
+
submit: async (payload) => {
|
|
711
|
+
await submitWithRetry(client, payload);
|
|
712
|
+
const wasAnalyzing = workflow?.state === "ANALYZING_FAILURE";
|
|
713
|
+
workflow?.commandResult(payload);
|
|
714
|
+
if (workflow && !wasAnalyzing && workflow.state === "ANALYZING_FAILURE")
|
|
715
|
+
ui.commit(renderValidationFailed(workflow.snapshot(), turnOutcome.validationCounts, turnOutcome.failure));
|
|
716
|
+
taskView?.refresh();
|
|
717
|
+
},
|
|
718
|
+
ui: {
|
|
719
|
+
review: (decision, reason, repository, operationId) => ui.borrow(async () => {
|
|
720
|
+
ui.stepEnd();
|
|
721
|
+
// Auto: locally admitted commands are approved by the session's policy, and say so.
|
|
722
|
+
if (permission.approveCommandByPolicy(decision.tier)) {
|
|
723
|
+
ui.commit([" " + c.ok("✓") + " " + c.dim("Auto: running ") + c.cmd(displayCommand(decision.program, decision.args)) + c.dim(" without asking (contained, " + decision.tier + ").")]);
|
|
724
|
+
return "approve";
|
|
725
|
+
}
|
|
726
|
+
taskView?.commandStatus(`Review: ${displayCommand(decision.program, decision.args)}`);
|
|
727
|
+
ui.commit(renderCommandReview(decision, reason, repository, executionContract(), workspaceRoot(), operationId));
|
|
728
|
+
return approveInScreen({ question: "Run this command?", timeoutMs: APPROVAL_TIMEOUT_MS, signal });
|
|
729
|
+
}),
|
|
730
|
+
started: (decision) => {
|
|
731
|
+
taskView?.commandStatus(`Running: ${displayCommand(decision.program, decision.args)}`);
|
|
732
|
+
ui.commandStarted(commandActivityLabel(decision), displayCommand(decision.program, decision.effectiveArgs));
|
|
733
|
+
},
|
|
734
|
+
output: (_stream, text) => ui.commandOutput(text),
|
|
735
|
+
finished: ({ decision, result, errorCode, message: detail }) => {
|
|
736
|
+
if (result) {
|
|
737
|
+
turnOutcome.validationCounts = summariseOutput(result.output) || undefined;
|
|
738
|
+
turnOutcome.failure = parseTestReport(result.output).failure;
|
|
739
|
+
}
|
|
740
|
+
taskView?.commandStatus(renderCommandSummary(decision, result, errorCode, detail).join(" "));
|
|
741
|
+
if (result)
|
|
742
|
+
lastCommandOutput = result.output;
|
|
743
|
+
if (result)
|
|
744
|
+
rememberCommandDetails(ctx, JSON.stringify([client.mutationRecoveryScope(), ctx.config.get("sessionId"), workspaceRoot()]), result.output);
|
|
745
|
+
ui.commandEnded();
|
|
746
|
+
ui.commit([...renderCommandSummary(decision, result, errorCode, detail), ...(result ? [" /details shows the full bounded command output."] : []), ""]);
|
|
747
|
+
ui.status("thinking", "Thinking");
|
|
748
|
+
},
|
|
749
|
+
cancelTurn: abort
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
// Task Context (services/task-context.ts, server clientTools/taskContext.js).
|
|
754
|
+
// A coding turn in a conversation with earlier coding work: show that the
|
|
755
|
+
// previous task's context was restored, and tell the server which of the
|
|
756
|
+
// files it inspected changed on disk since. Context only — nothing here
|
|
757
|
+
// skips a read, restores an approval or resumes an operation.
|
|
758
|
+
const taskFiles = workflow ? new TaskFileLedger() : undefined;
|
|
759
|
+
const ownerScope = workflow ? client.mutationRecoveryScope() : undefined;
|
|
760
|
+
const repoContext = workflow ? repositoryContext(ownerScope, sessionId) : null;
|
|
761
|
+
// A different repository than the earlier work used: its file report would
|
|
762
|
+
// describe other code, so it is not sent; the server is told the repository changed.
|
|
763
|
+
const repoState = workflow && sessionId && repoContext?.same_repository !== false ? repositoryState(ownerScope, sessionId) : [];
|
|
764
|
+
if (workflow && sessionId) {
|
|
765
|
+
const restored = await fetchTaskContext(client, sessionId);
|
|
766
|
+
if (restored && !signal.aborted)
|
|
767
|
+
ui.commit(renderTaskContextRestored(restored, repoState, repoContext?.name ?? (() => { try {
|
|
768
|
+
return getWorkspace().project.name;
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
return undefined;
|
|
772
|
+
} })(), repoContext));
|
|
773
|
+
}
|
|
774
|
+
// request_started + request_sent: fire the real call immediately, then the
|
|
775
|
+
// brief client-side steps play over the actual wait. Settle it eagerly so a
|
|
776
|
+
// rejection during the steps is never an unhandled rejection.
|
|
777
|
+
const attached = ctx.attachedFileIds;
|
|
778
|
+
// Deltas are consumed as they arrive, but the answer is still rendered by the
|
|
779
|
+
// formatted renderer once complete — it needs the whole text to lay out
|
|
780
|
+
// markdown, and rendering half a code fence would reflow the screen. What the
|
|
781
|
+
// stream buys here is truth in the timeline: a real "writing" phase, and each
|
|
782
|
+
// local tool step shown as it happens instead of a guessed label.
|
|
783
|
+
const settled = client
|
|
784
|
+
.chatStream({
|
|
785
|
+
mode,
|
|
786
|
+
message: `${turnOpts.sendAs ?? withProjectContext(ctx, message)}\n\n${commandHint}`,
|
|
787
|
+
session_id: sessionId,
|
|
788
|
+
model: model || undefined,
|
|
789
|
+
chat_type: ctx.chatType,
|
|
790
|
+
web_search: webSearch,
|
|
791
|
+
speed: ctx.fast ? "fast" : undefined,
|
|
792
|
+
high_power: ctx.highPower ? true : undefined,
|
|
793
|
+
file_ids: attached.length ? attached : undefined,
|
|
794
|
+
client_tools: workflow ? [...(declaredClientTools(ctx) ?? []), "coding_workflow"] : declaredClientTools(ctx),
|
|
795
|
+
client_mutation_tools: mutationTools,
|
|
796
|
+
client_command_tools: commandTools,
|
|
797
|
+
repository_state: repoState.length ? repoState : undefined,
|
|
798
|
+
repository_context: repoContext ?? undefined
|
|
799
|
+
}, {
|
|
800
|
+
onDelta: (delta) => {
|
|
801
|
+
if (signal.aborted)
|
|
802
|
+
return;
|
|
803
|
+
streamed += delta;
|
|
804
|
+
ui.writing(streamed.slice(shown));
|
|
805
|
+
},
|
|
806
|
+
onClientToolCall: async (call) => {
|
|
807
|
+
// Whatever the model said before asking for this tool belongs above it.
|
|
808
|
+
say();
|
|
809
|
+
const activity = toolActivity(call.name, call.arguments ?? {}, workspaceRoot());
|
|
810
|
+
ui.status("thinking", activity);
|
|
811
|
+
await handleClientToolCall(ctx, client, call, {
|
|
812
|
+
onStart: (_label, tool) => ui.toolStart(activity, toolKind(tool)),
|
|
813
|
+
onDone: (_label, ok, tool, detail) => {
|
|
814
|
+
if (ok)
|
|
815
|
+
taskFiles?.touch(call.name, call.arguments);
|
|
816
|
+
ui.toolEnd(activity, toolKind(tool), toolSummary(tool, ok, detail), ok);
|
|
817
|
+
taskView?.refresh();
|
|
818
|
+
if (workflow)
|
|
819
|
+
ui.status("thinking", workflowActivity(workflow.snapshot()));
|
|
820
|
+
},
|
|
821
|
+
workflow,
|
|
822
|
+
readCache,
|
|
823
|
+
mutations,
|
|
824
|
+
commands,
|
|
825
|
+
// A refused proposal ends its step visibly, with the engine's reason.
|
|
826
|
+
onRefused: (r) => ui.toolEnd(activity, toolKind(call.name), `refused — ${r.reason}`, false)
|
|
827
|
+
});
|
|
828
|
+
taskView?.refresh();
|
|
829
|
+
if (workflow)
|
|
830
|
+
ui.status("thinking", workflowActivity(workflow.snapshot()));
|
|
831
|
+
}
|
|
832
|
+
}, signal)
|
|
833
|
+
.then((r) => ({ ok: true, r }))
|
|
834
|
+
.catch((e) => ({ ok: false, e }));
|
|
835
|
+
try {
|
|
836
|
+
// One honest line instead of a scripted checklist: the turn is waiting on
|
|
837
|
+
// the model until something real (a tool call, a delta) says otherwise.
|
|
838
|
+
ui.status("thinking", webSearch === true ? "Searching the web" : ctx.highPower ? "Thinking (high power)" : "Thinking");
|
|
839
|
+
const outcome = await settled;
|
|
840
|
+
ui.stepEnd();
|
|
841
|
+
ui.stop(); // the live region is done; what remains is committed below
|
|
842
|
+
if (!outcome.ok)
|
|
843
|
+
throw outcome.e;
|
|
844
|
+
const result = outcome.r;
|
|
845
|
+
if (webSearchOverride === undefined)
|
|
846
|
+
ctx.disarmWebSearch(); // spend the one-shot arm
|
|
847
|
+
if (result.session_id && result.session_id !== sessionId) {
|
|
848
|
+
ctx.config.set("sessionId", result.session_id);
|
|
849
|
+
rememberPermissionMode(ctx.config);
|
|
850
|
+
// The chat response carries no title, and the backend generates one from
|
|
851
|
+
// the first message — fetch it once, in the background, so the footer can
|
|
852
|
+
// name the conversation without delaying the reply. Failure is silent:
|
|
853
|
+
// the footer simply stays unnamed.
|
|
854
|
+
void learnSessionTitle(ctx, client, result.session_id);
|
|
855
|
+
}
|
|
856
|
+
// Stream the answer in the SAME pinned composer so the reply sits directly
|
|
857
|
+
// beneath the user's message (contiguous — no gap), with the input bar
|
|
858
|
+
// staying visible the whole time. Finished lines commit above the bar.
|
|
859
|
+
const sources = result.sources ?? [];
|
|
860
|
+
ctx.recordSearch(sources);
|
|
861
|
+
if (lastCommandOutput !== undefined)
|
|
862
|
+
rememberCommandDetails(ctx, JSON.stringify([client.mutationRecoveryScope(), ctx.config.get("sessionId"), workspaceRoot()]), lastCommandOutput);
|
|
863
|
+
say(result.response); // the final message — anything not already narrated
|
|
864
|
+
workflow?.interrupt();
|
|
865
|
+
if (workflow)
|
|
866
|
+
ui.commit(renderAgentOutcome(workflow.snapshot(), { ...turnOutcome, applied: mutations?.applied }));
|
|
867
|
+
const swapped = noteModelSubstitution(ctx, result.model);
|
|
868
|
+
if (swapped)
|
|
869
|
+
live.commit([" " + c.warn("!") + " " + c.dim(swapped)]);
|
|
870
|
+
renderSourcesLive(live, sources);
|
|
871
|
+
recordTurnSpend(ctx, result);
|
|
872
|
+
const elapsed = (Date.now() - started) / 1000;
|
|
873
|
+
// One footer per turn — see chatTurn.
|
|
874
|
+
if (sources.length > 0)
|
|
875
|
+
live.commit([searchCompletionLine(sources.length, elapsed), ""]);
|
|
876
|
+
else
|
|
877
|
+
renderCompleteLive(live, elapsed, spendOf(result, ctx));
|
|
878
|
+
void showNewMemoryMarkers(ctx, client, result.session_id);
|
|
879
|
+
live.stop();
|
|
880
|
+
}
|
|
881
|
+
catch (err) {
|
|
882
|
+
workflow?.interrupt();
|
|
883
|
+
if (workflow)
|
|
884
|
+
ui.commit(renderAgentOutcome(workflow.snapshot(), { ...turnOutcome, applied: mutations?.applied }));
|
|
885
|
+
ui.stepEnd();
|
|
886
|
+
ui.stop();
|
|
887
|
+
live.stop();
|
|
888
|
+
if (signal.aborted)
|
|
889
|
+
line(" ⊘ Cancelled — the turn stopped.");
|
|
890
|
+
else
|
|
891
|
+
renderApiError(err);
|
|
892
|
+
}
|
|
893
|
+
finally {
|
|
894
|
+
// Always detach, so the composer's own Ctrl+C (arm-then-exit) works again.
|
|
895
|
+
taskView?.clear();
|
|
896
|
+
stopWatching();
|
|
897
|
+
// Hash what this turn read or changed, as it is on disk NOW, for the next
|
|
898
|
+
// turn's freshness report. Also after a failed or cancelled turn: an
|
|
899
|
+
// applied change is on disk either way.
|
|
900
|
+
taskFiles?.touchApplied(mutations?.applied ?? []);
|
|
901
|
+
taskFiles?.commit(ownerScope, ctx.config.get("sessionId"));
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
// ── Chat type (Carrier Chat vs Standard) ──────────────────────────────────────
|
|
905
|
+
// Orthogonal to modes: modes tune HOW Carrier responds; chat type picks WHICH
|
|
906
|
+
// chat experience — the flagship Carrier Chat (app-instructions + carrier
|
|
907
|
+
// behaviour layer, same engine/128k-context/memory as the web app) or a plain
|
|
908
|
+
// standard chat.
|
|
909
|
+
export function chatTypeLabel(type) {
|
|
910
|
+
return type === "carrier" ? "Carrier Chat" : "Standard chat";
|
|
911
|
+
}
|
|
912
|
+
/** Short label for the prompt/banner. */
|
|
913
|
+
export function chatTypeLabelShort(ctx) {
|
|
914
|
+
return chatTypeLabel(ctx.chatType);
|
|
915
|
+
}
|
|
916
|
+
/** `/chat` — no arg shows the current type; `/chat carrier|standard` switches. */
|
|
917
|
+
export function setChatType(ctx, arg) {
|
|
918
|
+
const raw = arg.trim().toLowerCase();
|
|
919
|
+
if (!raw) {
|
|
920
|
+
line();
|
|
921
|
+
line(chalk.dim(" Chat type:"));
|
|
922
|
+
for (const t of ["carrier", "standard"]) {
|
|
923
|
+
const on = t === ctx.chatType;
|
|
924
|
+
const label = on ? chalk.bold(chatTypeLabel(t)) : chatTypeLabel(t);
|
|
925
|
+
const desc = t === "carrier"
|
|
926
|
+
? "Flagship Carrier OS chat - full persona, 128k context, memory."
|
|
927
|
+
: "Plain chat - Carrier persona without the app-instruction layer.";
|
|
928
|
+
line(` ${on ? chalk.green("►") : " "} ${label.padEnd(15)} ${chalk.dim(desc)}`);
|
|
929
|
+
}
|
|
930
|
+
line();
|
|
931
|
+
line(chalk.dim(" Switch with /chat carrier or /chat standard."));
|
|
932
|
+
line();
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const next = raw === "carrier" || raw === "carrieros"
|
|
936
|
+
? "carrier"
|
|
937
|
+
: raw === "standard" || raw === "plain" || raw === "normal"
|
|
938
|
+
? "standard"
|
|
939
|
+
: null;
|
|
940
|
+
if (next === null) {
|
|
941
|
+
errorLine(`Unknown chat type "${arg.trim()}". Use /chat carrier or /chat standard.`);
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (next === ctx.chatType) {
|
|
945
|
+
info(`Already in ${chatTypeLabel(next)}.`);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
ctx.setChatType(next); // clears the session — the next message starts fresh
|
|
949
|
+
info(`Switched to ${chatTypeLabel(next)}. A new conversation starts on your next message.`);
|
|
950
|
+
}
|
|
951
|
+
/** Arrow-key picker to switch chat type (Carrier ⇄ Standard). `/switch`. */
|
|
952
|
+
export async function pickChatType(ctx) {
|
|
953
|
+
const choices = [
|
|
954
|
+
{
|
|
955
|
+
value: "carrier",
|
|
956
|
+
label: chatTypeLabel("carrier"),
|
|
957
|
+
description: "Flagship Carrier OS chat — full persona, 128k context, memory.",
|
|
958
|
+
current: ctx.chatType === "carrier"
|
|
959
|
+
},
|
|
960
|
+
{
|
|
961
|
+
value: "standard",
|
|
962
|
+
label: chatTypeLabel("standard"),
|
|
963
|
+
description: "Plain chat — Carrier persona without the app-instruction layer.",
|
|
964
|
+
current: ctx.chatType === "standard"
|
|
965
|
+
}
|
|
966
|
+
];
|
|
967
|
+
const chosen = await pickFromList({
|
|
968
|
+
title: "Switch chat",
|
|
969
|
+
description: "Pick your chat experience. Switching starts a new conversation.",
|
|
970
|
+
initial: Math.max(0, choices.findIndex((ch) => ch.current)),
|
|
971
|
+
choices
|
|
972
|
+
});
|
|
973
|
+
if (chosen == null)
|
|
974
|
+
return; // Esc / Ctrl+C — leave it unchanged
|
|
975
|
+
const next = chosen;
|
|
976
|
+
if (next === ctx.chatType) {
|
|
977
|
+
info(`Already in ${chatTypeLabel(next)}.`);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
ctx.setChatType(next);
|
|
981
|
+
info(`Switched to ${chatTypeLabel(next)}. A new conversation starts on your next message.`);
|
|
982
|
+
}
|
|
983
|
+
// ── Web search ────────────────────────────────────────────────────────────────
|
|
984
|
+
// A capability of chat, not a separate tool. Three ways in, deliberately:
|
|
985
|
+
// /websearch arm the NEXT message, then fall back automatically
|
|
986
|
+
// /websearch <query> search right now, changing no state at all
|
|
987
|
+
// /websearch on|off a standing preference, persisted like mode/model
|
|
988
|
+
// Left unset the API follows the workspace's admin toggle (what the web does).
|
|
989
|
+
const WEB_SEARCH_NOTE = "Carrier still skips the search for code, math and timeless questions, and whenever files are attached.";
|
|
990
|
+
/**
|
|
991
|
+
* Footer label — null when there's nothing worth asserting (workspace default,
|
|
992
|
+
* or explicitly off).
|
|
993
|
+
*
|
|
994
|
+
* Armed and always-on share one label: the chip vanishing after a single turn
|
|
995
|
+
* is already what tells you the arm was one-shot, so a separate word for it
|
|
996
|
+
* would only add noise to the line you read most often.
|
|
997
|
+
*/
|
|
998
|
+
export function webSearchLabelShort(ctx) {
|
|
999
|
+
return ctx.webSearchArmed || ctx.webSearch === true ? "Websearch" : null;
|
|
1000
|
+
}
|
|
1001
|
+
/** "2m ago" / "just now" for the last search, or null if there hasn't been one. */
|
|
1002
|
+
export function lastSearchAgo(ctx) {
|
|
1003
|
+
const at = ctx.lastSearchAt;
|
|
1004
|
+
if (at === null)
|
|
1005
|
+
return null;
|
|
1006
|
+
const mins = Math.floor((Date.now() - at) / 60_000);
|
|
1007
|
+
if (mins < 1)
|
|
1008
|
+
return "just now";
|
|
1009
|
+
if (mins < 60)
|
|
1010
|
+
return `${mins}m ago`;
|
|
1011
|
+
const hours = Math.floor(mins / 60);
|
|
1012
|
+
return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
|
|
1013
|
+
}
|
|
1014
|
+
const ON_WORDS = ["on", "yes", "true", "enable", "enabled"];
|
|
1015
|
+
const OFF_WORDS = ["off", "no", "false", "disable", "disabled"];
|
|
1016
|
+
const AUTO_WORDS = ["auto", "default", "workspace"];
|
|
1017
|
+
/** True when the argument is a state word rather than a search query. */
|
|
1018
|
+
export function isWebSearchStateArg(arg) {
|
|
1019
|
+
const raw = arg.trim().toLowerCase();
|
|
1020
|
+
if (!raw)
|
|
1021
|
+
return true;
|
|
1022
|
+
return (ON_WORDS.includes(raw) ||
|
|
1023
|
+
OFF_WORDS.includes(raw) ||
|
|
1024
|
+
AUTO_WORDS.includes(raw) ||
|
|
1025
|
+
raw === "status");
|
|
1026
|
+
}
|
|
1027
|
+
/** `/websearch` with no argument — arm the next message. */
|
|
1028
|
+
export function armWebSearch(ctx) {
|
|
1029
|
+
if (ctx.webSearch === true) {
|
|
1030
|
+
info("Web search is already on for every message. /websearch off to stop.");
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
ctx.armWebSearch();
|
|
1034
|
+
line();
|
|
1035
|
+
line(" " + c.ok("✓") + " " + c.title("Web search enabled"));
|
|
1036
|
+
line();
|
|
1037
|
+
line(" " + c.dim("Scope ") + c.value("your next message"));
|
|
1038
|
+
line(" " + c.dim("Mode ") + c.value("live web"));
|
|
1039
|
+
line();
|
|
1040
|
+
line(" " + c.dim(WEB_SEARCH_NOTE));
|
|
1041
|
+
line();
|
|
1042
|
+
}
|
|
1043
|
+
/** `/websearch on|off|auto|status`. */
|
|
1044
|
+
export function setWebSearch(ctx, arg) {
|
|
1045
|
+
const raw = arg.trim().toLowerCase();
|
|
1046
|
+
if (!raw || raw === "status") {
|
|
1047
|
+
showWebSearchStatus(ctx);
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
if (AUTO_WORDS.includes(raw)) {
|
|
1051
|
+
ctx.disarmWebSearch();
|
|
1052
|
+
ctx.config.set("webSearch", undefined);
|
|
1053
|
+
info("Web search follows your workspace default.");
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
if (ON_WORDS.includes(raw)) {
|
|
1057
|
+
ctx.disarmWebSearch(); // a standing preference supersedes the one-shot arm
|
|
1058
|
+
ctx.setWebSearch(true);
|
|
1059
|
+
info(`Web search on for every message. ${WEB_SEARCH_NOTE}`);
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
if (OFF_WORDS.includes(raw)) {
|
|
1063
|
+
ctx.disarmWebSearch();
|
|
1064
|
+
ctx.setWebSearch(false);
|
|
1065
|
+
info("Web search off.");
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
errorLine(`Unknown value "${arg.trim()}". Use /websearch on, off, auto, or status.`);
|
|
1069
|
+
}
|
|
1070
|
+
/** `/websearch status` — the current state and what the last search returned. */
|
|
1071
|
+
export function showWebSearchStatus(ctx) {
|
|
1072
|
+
const status = ctx.webSearchArmed
|
|
1073
|
+
? "Armed"
|
|
1074
|
+
: ctx.webSearch === true
|
|
1075
|
+
? "Enabled"
|
|
1076
|
+
: ctx.webSearch === false
|
|
1077
|
+
? "Disabled"
|
|
1078
|
+
: "Workspace default";
|
|
1079
|
+
const scope = ctx.webSearchArmed
|
|
1080
|
+
? "next message only"
|
|
1081
|
+
: ctx.webSearch === true
|
|
1082
|
+
? "every message"
|
|
1083
|
+
: ctx.webSearch === false
|
|
1084
|
+
? "never"
|
|
1085
|
+
: "decided by your workspace";
|
|
1086
|
+
const ago = lastSearchAgo(ctx);
|
|
1087
|
+
const rows = [
|
|
1088
|
+
["Status", status],
|
|
1089
|
+
["Scope", scope],
|
|
1090
|
+
["Last search", ago ?? "none this session"]
|
|
1091
|
+
];
|
|
1092
|
+
if (ago)
|
|
1093
|
+
rows.push(["Results", `${ctx.lastSources.length} sources`]);
|
|
1094
|
+
line();
|
|
1095
|
+
line(" " + c.title("Web search"));
|
|
1096
|
+
line();
|
|
1097
|
+
for (const [k, v] of rows)
|
|
1098
|
+
line(" " + c.dim(k.padEnd(13)) + c.value(v));
|
|
1099
|
+
line();
|
|
1100
|
+
// Point at the state they're NOT in — a "turn it on" hint under a status that
|
|
1101
|
+
// already says Enabled is just noise.
|
|
1102
|
+
line(" " +
|
|
1103
|
+
(ctx.webSearch === true
|
|
1104
|
+
? c.dim("Stop with ") + c.cmd("/websearch off")
|
|
1105
|
+
: c.dim("Turn on with ") + c.cmd("/websearch on")));
|
|
1106
|
+
line(" " + c.dim("Search once with ") + c.cmd("/websearch <query>"));
|
|
1107
|
+
if (ago)
|
|
1108
|
+
line(" " + c.dim("Revisit results with ") + c.cmd("/sources"));
|
|
1109
|
+
line();
|
|
1110
|
+
}
|
|
1111
|
+
/** `/websearch <query>` — one search now, leaving every setting untouched. */
|
|
1112
|
+
export async function searchNow(ctx, client, query, footer) {
|
|
1113
|
+
await chatTurn(ctx, client, query, { footer, webSearch: true });
|
|
1114
|
+
}
|
|
1115
|
+
/** `/sources` — the full citation list from the most recent search. */
|
|
1116
|
+
export function showSources(ctx) {
|
|
1117
|
+
const sources = ctx.lastSources;
|
|
1118
|
+
if (sources.length === 0) {
|
|
1119
|
+
info("No sources yet. Ask something with web search on, then run /sources.");
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
renderAllSources(sources, lastSearchAgo(ctx));
|
|
1123
|
+
}
|
|
1124
|
+
/** `/open <n>` — open citation n from the last search in the default browser. */
|
|
1125
|
+
export function openSource(ctx, arg) {
|
|
1126
|
+
const sources = ctx.lastSources;
|
|
1127
|
+
if (sources.length === 0) {
|
|
1128
|
+
info("No sources yet. Ask something with web search on, then run /open <n>.");
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
const n = Number.parseInt(arg.trim(), 10);
|
|
1132
|
+
if (!Number.isInteger(n) || n < 1 || n > sources.length) {
|
|
1133
|
+
errorLine(`Pick a source between 1 and ${sources.length}. Run /sources to see them.`);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
const target = sources[n - 1];
|
|
1137
|
+
// Check before announcing, so a refused URL never prints "Opening…" first.
|
|
1138
|
+
const checked = checkUrl(target.url);
|
|
1139
|
+
if (!checked.ok) {
|
|
1140
|
+
errorLine(checked.reason);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
// Print the URL as well: on a headless box the spawn quietly no-ops, and this
|
|
1144
|
+
// line is then the whole answer rather than a silent failure.
|
|
1145
|
+
line();
|
|
1146
|
+
line(" " + c.dim(`Opening [${n}] `) + c.value(target.source?.trim() || "source"));
|
|
1147
|
+
line(" " + c.dim(checked.url));
|
|
1148
|
+
line();
|
|
1149
|
+
openUrl(checked.url);
|
|
1150
|
+
}
|
|
1151
|
+
// ── Fast mode & High Power ────────────────────────────────────────────────────
|
|
1152
|
+
// Two turn-shaping toggles that sit alongside mode/model, mirroring the web
|
|
1153
|
+
// composer. Fast shortens the pipeline; High Power runs HIPWR's 4-pass
|
|
1154
|
+
// refinement (EXPANSION → HARDENING → ARCHITECTURE → FINALIZATION).
|
|
1155
|
+
/** Modes HIPWR is compatible with — the same set the web composer allows. */
|
|
1156
|
+
const HIPWR_MODES = ["auto", "summary", "reasoning", "research"];
|
|
1157
|
+
/** Parse an on/off word. Returns null when it isn't one. */
|
|
1158
|
+
function onOff(arg) {
|
|
1159
|
+
const raw = arg.trim().toLowerCase();
|
|
1160
|
+
if (!raw)
|
|
1161
|
+
return null;
|
|
1162
|
+
if (["on", "yes", "true", "enable", "enabled"].includes(raw))
|
|
1163
|
+
return true;
|
|
1164
|
+
if (["off", "no", "false", "disable", "disabled"].includes(raw))
|
|
1165
|
+
return false;
|
|
1166
|
+
return null;
|
|
1167
|
+
}
|
|
1168
|
+
/** `/fast` toggles, `/fast on|off` sets. */
|
|
1169
|
+
export async function setFast(ctx, arg, client) {
|
|
1170
|
+
const raw = arg.trim();
|
|
1171
|
+
const next = raw ? onOff(raw) : !ctx.fast;
|
|
1172
|
+
if (next === null) {
|
|
1173
|
+
errorLine(`Unknown value "${raw}". Use /fast on or /fast off.`);
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
// Standard chat only, matching the web — it hides the toggle entirely for
|
|
1177
|
+
// Carrier Chat and Quick Chat. Fast mode swaps the provider for Groq/Llama,
|
|
1178
|
+
// which the Carrier persona isn't tuned for. Refuse here rather than letting
|
|
1179
|
+
// the server silently downgrade the turn to standard.
|
|
1180
|
+
if (next && ctx.chatType === "carrier") {
|
|
1181
|
+
errorLine("Fast mode is Standard chat only — Carrier Chat always uses its own models.");
|
|
1182
|
+
line(" " + c.dim("Run ") + c.cmd("/switch standard") + c.dim(" first."));
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
// As on the web: Fast Mode runs the admin's Fast model, which is text-only.
|
|
1186
|
+
let fast = null;
|
|
1187
|
+
if (next) {
|
|
1188
|
+
fast = client ? await loadFastModel(client) : null;
|
|
1189
|
+
if (!fast) {
|
|
1190
|
+
errorLine("Fast mode isn't available right now — the server has no Fast Mode model.");
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
if (ctx.attachedFileIds.length) {
|
|
1194
|
+
errorLine("Fast mode can't read files — its model is text-only.");
|
|
1195
|
+
line(" " + c.dim("Run ") + c.cmd("/detach") + c.dim(" first, then ") + c.cmd("/fast") + c.dim("."));
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
ctx.setFast(next);
|
|
1200
|
+
info(next
|
|
1201
|
+
? `Fast mode on — ${fast.label}, quicker replies, less refinement. /model is locked until /fast off.`
|
|
1202
|
+
: "Fast mode off — standard pipeline depth, your chosen model.");
|
|
1203
|
+
}
|
|
1204
|
+
/** `/hipwr` toggles, `/hipwr on|off` sets. Warns when the mode won't run it. */
|
|
1205
|
+
export function setHighPower(ctx, arg) {
|
|
1206
|
+
const raw = arg.trim();
|
|
1207
|
+
const next = raw ? onOff(raw) : !ctx.highPower;
|
|
1208
|
+
if (next === null) {
|
|
1209
|
+
errorLine(`Unknown value "${raw}". Use /hipwr on or /hipwr off.`);
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
ctx.setHighPower(next);
|
|
1213
|
+
if (!next) {
|
|
1214
|
+
info("High Power off.");
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
line();
|
|
1218
|
+
line(" " + c.ok("✓") + " " + c.title("High Power enabled"));
|
|
1219
|
+
line();
|
|
1220
|
+
line(" " + c.dim("Pipeline ") + c.value("4-pass refinement"));
|
|
1221
|
+
line(" " + c.dim("Passes ") + c.dim("expansion → hardening → architecture → finalization"));
|
|
1222
|
+
line();
|
|
1223
|
+
// Say so up front rather than letting the user wonder why nothing changed:
|
|
1224
|
+
// the engine silently declines HIPWR outside these modes.
|
|
1225
|
+
if (!HIPWR_MODES.includes(ctx.mode)) {
|
|
1226
|
+
line(" " +
|
|
1227
|
+
c.warn("!") +
|
|
1228
|
+
c.dim(` ${capitalize(ctx.mode)} mode doesn't run High Power. `) +
|
|
1229
|
+
c.dim("Switch to ") +
|
|
1230
|
+
c.value(HIPWR_MODES.join(", ")) +
|
|
1231
|
+
c.dim("."));
|
|
1232
|
+
line();
|
|
1233
|
+
}
|
|
1234
|
+
line(" " + c.dim("Trivial messages skip it regardless — it's for substantial work."));
|
|
1235
|
+
line();
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Footer chips for the turn-shaping toggles, in the order they're applied.
|
|
1239
|
+
*
|
|
1240
|
+
* Icons match the web's composer so the same capability reads the same in both
|
|
1241
|
+
* places: Zap for fast mode, Flame for High Power (chat-input.tsx).
|
|
1242
|
+
*/
|
|
1243
|
+
/**
|
|
1244
|
+
* Footer chips for whatever is switched on, already coloured — SIA gets its own
|
|
1245
|
+
* colour rather than the shared yellow, so the footer distinguishes "shapes the
|
|
1246
|
+
* answer" (Fast, HIPWR) from "shapes the question" (SIA).
|
|
1247
|
+
*/
|
|
1248
|
+
export function turnShapeLabels(ctx) {
|
|
1249
|
+
const out = [];
|
|
1250
|
+
if (ctx.fast)
|
|
1251
|
+
out.push(c.warn("⚡ Fast"));
|
|
1252
|
+
if (ctx.highPower)
|
|
1253
|
+
out.push(c.warn("🔥 HIPWR"));
|
|
1254
|
+
// ✦ (U+2726), not the ✨ emoji: emoji carry their own colour, so the chip
|
|
1255
|
+
// ignored c.magic and rendered yellow — and it is double-width, which the
|
|
1256
|
+
// footer's width maths counts as one column.
|
|
1257
|
+
// SIA is deliberately NOT shown. Auto is the default and it acts only when
|
|
1258
|
+
// the backend judges a prompt ambiguous, so a permanent chip advertises
|
|
1259
|
+
// something that usually does nothing — unlike Fast and HIPWR, which change
|
|
1260
|
+
// every turn. `/sia status` reports the state when it is actually in question.
|
|
1261
|
+
return out;
|
|
1262
|
+
}
|
|
1263
|
+
/** `/sia` toggles, `/sia on|off` sets. */
|
|
1264
|
+
const SIA_BLURB = {
|
|
1265
|
+
auto: "Auto — Carrier OS asks only when a prompt is genuinely ambiguous.",
|
|
1266
|
+
off: "Off — prompts are sent exactly as typed."
|
|
1267
|
+
};
|
|
1268
|
+
/** Print the current state. Says plainly when the chat type ignores it. */
|
|
1269
|
+
export function showSiaStatus(ctx) {
|
|
1270
|
+
line();
|
|
1271
|
+
line(" " + c.title("SIA"));
|
|
1272
|
+
if (ctx.chatType !== "standard") {
|
|
1273
|
+
line(" " + c.dim("Not used in Carrier Chat — it runs its own behaviour layer."));
|
|
1274
|
+
line(" " + c.dim("Your Standard setting is remembered and restored on ") + c.cmd("/switch standard"));
|
|
1275
|
+
line();
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
line(" " + c.dim("Mode: ") + c.value(capitalize(ctx.siaMode)));
|
|
1279
|
+
line(" " + c.dim(SIA_BLURB[ctx.siaMode]));
|
|
1280
|
+
line();
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* `/sia` picks, `/sia auto|off|status` sets or shows.
|
|
1284
|
+
*
|
|
1285
|
+
* There is no "on": the backend already decides whether a prompt needs
|
|
1286
|
+
* clarification (/v1/sia/questions answers `skip` for anything clear enough),
|
|
1287
|
+
* and it has no way to be told "ask anyway". An "on" that behaved exactly like
|
|
1288
|
+
* auto would be a label promising something the API cannot do — so `/sia on` is
|
|
1289
|
+
* accepted as an alias and reported honestly as Auto.
|
|
1290
|
+
*/
|
|
1291
|
+
export async function setSia(ctx, arg) {
|
|
1292
|
+
const raw = arg.trim().toLowerCase();
|
|
1293
|
+
if (raw === "status")
|
|
1294
|
+
return showSiaStatus(ctx);
|
|
1295
|
+
if (ctx.chatType !== "standard") {
|
|
1296
|
+
errorLine("SIA is Standard chat only — Carrier Chat runs its own behaviour layer.");
|
|
1297
|
+
line(" " + c.dim("Run ") + c.cmd("/switch standard") + c.dim(" first."));
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
let next = null;
|
|
1301
|
+
if (!raw) {
|
|
1302
|
+
const picked = await pickFromList({
|
|
1303
|
+
title: "SIA",
|
|
1304
|
+
description: "Clarifying questions before an ambiguous prompt is sent.",
|
|
1305
|
+
choices: [
|
|
1306
|
+
{ value: "auto", label: "Auto", description: SIA_BLURB.auto, current: ctx.siaMode === "auto" },
|
|
1307
|
+
{ value: "off", label: "Off", description: SIA_BLURB.off, current: ctx.siaMode === "off" }
|
|
1308
|
+
],
|
|
1309
|
+
initial: ctx.siaMode === "off" ? 1 : 0,
|
|
1310
|
+
stacked: true
|
|
1311
|
+
});
|
|
1312
|
+
if (picked === null)
|
|
1313
|
+
return; // Esc — leave the setting alone
|
|
1314
|
+
next = picked;
|
|
1315
|
+
}
|
|
1316
|
+
else if (raw === "auto" || raw === "on") {
|
|
1317
|
+
next = "auto";
|
|
1318
|
+
}
|
|
1319
|
+
else if (raw === "off") {
|
|
1320
|
+
next = "off";
|
|
1321
|
+
}
|
|
1322
|
+
if (next === null) {
|
|
1323
|
+
errorLine(`Unknown value "${raw}". Use /sia auto, /sia off, or /sia status.`);
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
ctx.setSiaMode(next);
|
|
1327
|
+
// "on" is an accepted alias, so say which state it actually landed in.
|
|
1328
|
+
info(`SIA ${capitalize(next)} — ${SIA_BLURB[next].replace(/^\w+ — /, "")}`);
|
|
1329
|
+
}
|
|
1330
|
+
// ── Carrier modes (behavior) ──────────────────────────────────────────────────
|
|
1331
|
+
export async function showModes(ctx, client) {
|
|
1332
|
+
try {
|
|
1333
|
+
const modes = await withSpinner(chalk.dim("Loading modes…"), () => loadModes(client));
|
|
1334
|
+
const active = ctx.mode;
|
|
1335
|
+
line();
|
|
1336
|
+
line(chalk.dim(" Carrier modes (behavior):"));
|
|
1337
|
+
for (const m of modes) {
|
|
1338
|
+
const on = m.id === active;
|
|
1339
|
+
const name = on ? chalk.bold(capitalize(m.name)) : capitalize(m.name);
|
|
1340
|
+
line(` ${on ? chalk.green("►") : " "} ${name.padEnd(12)} ${chalk.dim(m.description)}`);
|
|
1341
|
+
}
|
|
1342
|
+
line();
|
|
1343
|
+
}
|
|
1344
|
+
catch (err) {
|
|
1345
|
+
reportError(err);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
export async function setMode(ctx, client, arg) {
|
|
1349
|
+
const id = arg.trim().toLowerCase();
|
|
1350
|
+
if (!id) {
|
|
1351
|
+
await pickMode(ctx, client);
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
if (!ctx.modeIsSelectable) {
|
|
1355
|
+
info("Carrier Chat always uses the General mode. Switch to Standard chat to pick another.");
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
try {
|
|
1359
|
+
const modes = await loadModes(client);
|
|
1360
|
+
// "auto" is a routing option rather than a mode the API lists, so accept it
|
|
1361
|
+
// explicitly — it's the Standard-chat default and must stay selectable.
|
|
1362
|
+
if (id !== "auto" && !modes.some((m) => m.id === id)) {
|
|
1363
|
+
errorLine(`Unknown mode "${id}". Type /modes to see the options.`);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
ctx.config.set("mode", id);
|
|
1367
|
+
ctx.setSessionMode(id); // reflect immediately in the shell (over the session default)
|
|
1368
|
+
const name = id === "auto" ? "Auto" : (modes.find((m) => m.id === id)?.name ?? capitalize(id));
|
|
1369
|
+
info(`Mode changed to ${name} (applies to your next message).`);
|
|
1370
|
+
}
|
|
1371
|
+
catch (err) {
|
|
1372
|
+
reportError(err);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Chat entry for the interactive shell. If the message begins with (or quotes) a
|
|
1377
|
+
* local file path, upload + attach it silently and strip the path — the model
|
|
1378
|
+
* only ever sees the cleaned prompt + file_ids, never a Windows path. Otherwise
|
|
1379
|
+
* it's a normal chat turn. Thin client: upload/attach only, no parsing.
|
|
1380
|
+
*/
|
|
1381
|
+
export async function chatInputWithFiles(ctx, client, input, footer, signal) {
|
|
1382
|
+
const { files, prompt, rejected } = detectLocalFiles(input);
|
|
1383
|
+
// File uploads are writes too. Check before attaching anything, and let
|
|
1384
|
+
// chatTurn recheck before sending in case the admin flips the switch mid-upload.
|
|
1385
|
+
if (files.length > 0 && !(await allowChatTurn(ctx, client)))
|
|
1386
|
+
return;
|
|
1387
|
+
for (const r of rejected) {
|
|
1388
|
+
line(" " + c.warn("!") + " " + c.dim(`Not attached — outside this project: ${r}`));
|
|
1389
|
+
}
|
|
1390
|
+
if (files.length === 0) {
|
|
1391
|
+
await chatTurn(ctx, client, input, { footer, signal });
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
// Progressive, Claude-Code-style flow (in the transcript, no raw logs).
|
|
1395
|
+
line();
|
|
1396
|
+
line(c.dim(` Detected local file${files.length > 1 ? "s" : ""}`));
|
|
1397
|
+
line();
|
|
1398
|
+
for (const f of files) {
|
|
1399
|
+
const name = path.basename(f);
|
|
1400
|
+
let size = 0;
|
|
1401
|
+
try {
|
|
1402
|
+
size = fs.statSync(f).size;
|
|
1403
|
+
}
|
|
1404
|
+
catch {
|
|
1405
|
+
/* shown without size */
|
|
1406
|
+
}
|
|
1407
|
+
line(" " + c.value(name) + c.dim(` ${fileTypeLabel(name)} • ${formatSize(size)}`));
|
|
1408
|
+
}
|
|
1409
|
+
line();
|
|
1410
|
+
let anyAttached = false;
|
|
1411
|
+
for (const f of files) {
|
|
1412
|
+
try {
|
|
1413
|
+
const r = await uploadAndAttach(ctx, client, f, {
|
|
1414
|
+
onUploading: () => line(c.dim(" Uploading…")),
|
|
1415
|
+
onUploaded: () => success(" Uploaded"),
|
|
1416
|
+
onProcessing: () => line(c.dim(" Preparing document…"))
|
|
1417
|
+
});
|
|
1418
|
+
anyAttached = true;
|
|
1419
|
+
if (r.wasAttached)
|
|
1420
|
+
success(` ${r.filename} already attached`);
|
|
1421
|
+
else
|
|
1422
|
+
success(` Attached ${r.filename}`);
|
|
1423
|
+
}
|
|
1424
|
+
catch (err) {
|
|
1425
|
+
errorLine(" " + (err instanceof UploadError ? err.message : err.message));
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
line();
|
|
1429
|
+
if (!anyAttached)
|
|
1430
|
+
return; // nothing usable was attached — don't send a bare prompt
|
|
1431
|
+
if (!prompt) {
|
|
1432
|
+
// File(s) attached but no question — NEVER auto-send. Just tell them it's
|
|
1433
|
+
// ready; the footer shows what's attached and they can type when ready.
|
|
1434
|
+
line(" " + c.dim("Ready. Ask anything about it."));
|
|
1435
|
+
line();
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
await chatTurn(ctx, client, prompt, { footer, signal });
|
|
1439
|
+
}
|
|
1440
|
+
/** Arrow-key picker for the Carrier mode (↑/↓ + Enter; Esc/Ctrl+C cancels). */
|
|
1441
|
+
export async function pickMode(ctx, client) {
|
|
1442
|
+
let modes;
|
|
1443
|
+
try {
|
|
1444
|
+
modes = await withSpinner(chalk.dim("Loading modes…"), () => loadModes(client));
|
|
1445
|
+
}
|
|
1446
|
+
catch (err) {
|
|
1447
|
+
reportError(err);
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
// Carrier chat only ever uses the General mode; the other modes (Reasoning,
|
|
1451
|
+
// Code, Research, …) apply to Standard chat, which ALSO gets an "Auto" option
|
|
1452
|
+
// that lets Carrier pick the best mode from the message intent.
|
|
1453
|
+
const AUTO = {
|
|
1454
|
+
id: "auto",
|
|
1455
|
+
name: "Auto",
|
|
1456
|
+
description: "Let Carrier pick the best mode from your message intent."
|
|
1457
|
+
};
|
|
1458
|
+
const visible = ctx.modeIsSelectable ? [AUTO, ...modes] : modes.filter((m) => m.id === "general");
|
|
1459
|
+
const chosen = await pickFromList({
|
|
1460
|
+
title: ctx.chatType === "carrier" ? "Carrier mode" : "Select a mode",
|
|
1461
|
+
description: ctx.chatType === "carrier"
|
|
1462
|
+
? "Carrier chat uses the General mode. Switch to Standard chat (/switch) for other modes."
|
|
1463
|
+
: "Changes how Carrier responds. Applies to your next message.",
|
|
1464
|
+
initial: Math.max(0, visible.findIndex((m) => m.id === ctx.mode)),
|
|
1465
|
+
choices: visible.map((m) => ({
|
|
1466
|
+
value: m.id,
|
|
1467
|
+
label: modeName(m),
|
|
1468
|
+
description: m.description,
|
|
1469
|
+
current: m.id === ctx.mode
|
|
1470
|
+
}))
|
|
1471
|
+
});
|
|
1472
|
+
if (chosen == null)
|
|
1473
|
+
return; // Esc / Ctrl+C — leave the mode unchanged
|
|
1474
|
+
// Carrier Chat has exactly one entry, so a "selection" there changes nothing —
|
|
1475
|
+
// and must NOT be written, or picking General in Carrier would silently become
|
|
1476
|
+
// the Standard-chat mode the next time you switch.
|
|
1477
|
+
if (!ctx.modeIsSelectable)
|
|
1478
|
+
return;
|
|
1479
|
+
ctx.config.set("mode", chosen);
|
|
1480
|
+
ctx.setSessionMode(chosen); // reflect immediately in the shell (over the session default)
|
|
1481
|
+
const picked = modes.find((m) => m.id === chosen);
|
|
1482
|
+
info(`Mode changed to ${picked ? modeName(picked) : capitalize(chosen)} (applies to your next message).`);
|
|
1483
|
+
}
|
|
1484
|
+
// ── Provider models (the LLM behind a turn) ───────────────────────────────────
|
|
1485
|
+
export async function showModels(ctx, client) {
|
|
1486
|
+
try {
|
|
1487
|
+
const models = await withSpinner(chalk.dim("Loading models…"), () => loadModels(client));
|
|
1488
|
+
const active = currentModelId(ctx);
|
|
1489
|
+
line();
|
|
1490
|
+
line(chalk.dim(" Provider models:"));
|
|
1491
|
+
const autoOn = active === "";
|
|
1492
|
+
line(` ${autoOn ? chalk.green("►") : " "} ${(autoOn ? chalk.bold(AUTO_LABEL) : AUTO_LABEL).padEnd(28)}`);
|
|
1493
|
+
for (const m of models) {
|
|
1494
|
+
const on = m.id === active;
|
|
1495
|
+
const down = m.available === false;
|
|
1496
|
+
const label = on ? chalk.bold(m.label) : down ? chalk.dim(m.label) : m.label;
|
|
1497
|
+
const note = down ? chalk.dim(`${m.id} — provider out of credit`) : chalk.dim(m.id);
|
|
1498
|
+
line(` ${on ? chalk.green("►") : " "} ${label.padEnd(28)} ${note}`);
|
|
1499
|
+
}
|
|
1500
|
+
line();
|
|
1501
|
+
}
|
|
1502
|
+
catch (err) {
|
|
1503
|
+
reportError(err);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
export async function setModel(ctx, client, arg) {
|
|
1507
|
+
// Fast Mode picks the model (the server's Fast model), as the web locks its picker.
|
|
1508
|
+
if (fastInEffect(ctx)) {
|
|
1509
|
+
const fast = await loadFastModel(client);
|
|
1510
|
+
errorLine(`Fast mode is on — it runs on ${fast?.label ?? "the Fast Mode model"}.`);
|
|
1511
|
+
line(" " + c.dim("Run ") + c.cmd("/fast off") + c.dim(" to choose a model."));
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
const id = arg.trim().toLowerCase();
|
|
1515
|
+
if (!id) {
|
|
1516
|
+
await pickModel(ctx, client);
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
if (id === "auto" || id === "default") {
|
|
1520
|
+
ctx.config.set("model", "");
|
|
1521
|
+
info(`Model set to ${AUTO_LABEL}.`);
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
try {
|
|
1525
|
+
const models = await loadModels(client);
|
|
1526
|
+
const match = models.find((m) => m.id === id);
|
|
1527
|
+
if (!match) {
|
|
1528
|
+
errorLine(`Unknown model "${id}". Type /models to see the options.`);
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
if (currentModelId(ctx) === match.id) {
|
|
1532
|
+
// Picking what is already selected changed nothing — saying "changed"
|
|
1533
|
+
// makes the user doubt what state they are in.
|
|
1534
|
+
info(`Already using ${match.label}.`);
|
|
1535
|
+
return;
|
|
1536
|
+
}
|
|
1537
|
+
ctx.config.set("model", match.id);
|
|
1538
|
+
info(`Model changed to ${match.label} (applies to your next message).`);
|
|
1539
|
+
}
|
|
1540
|
+
catch (err) {
|
|
1541
|
+
reportError(err);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
/** Arrow-key picker for the provider model (Auto + each model; Esc/Ctrl+C cancels). */
|
|
1545
|
+
export async function pickModel(ctx, client) {
|
|
1546
|
+
let models;
|
|
1547
|
+
try {
|
|
1548
|
+
models = await withSpinner(chalk.dim("Loading models…"), () => loadModels(client));
|
|
1549
|
+
}
|
|
1550
|
+
catch (err) {
|
|
1551
|
+
reportError(err);
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
const current = currentModelId(ctx);
|
|
1555
|
+
const choices = [
|
|
1556
|
+
{
|
|
1557
|
+
value: "",
|
|
1558
|
+
label: AUTO_LABEL,
|
|
1559
|
+
description: "Use the current mode's default model",
|
|
1560
|
+
current: current === ""
|
|
1561
|
+
},
|
|
1562
|
+
// Unavailable models stay selectable — the API substitutes a working one and
|
|
1563
|
+
// tells you which answered — but they're labelled so the choice is informed.
|
|
1564
|
+
...models.map((m) => ({
|
|
1565
|
+
value: m.id,
|
|
1566
|
+
label: m.available === false ? `${m.label} (unavailable)` : m.label,
|
|
1567
|
+
description: m.available === false ? `${m.id} — provider out of credit` : m.id,
|
|
1568
|
+
current: m.id === current
|
|
1569
|
+
}))
|
|
1570
|
+
];
|
|
1571
|
+
const chosen = await pickFromList({
|
|
1572
|
+
title: "Select a model",
|
|
1573
|
+
description: "Switch the model for this and future messages.",
|
|
1574
|
+
initial: Math.max(0, choices.findIndex((ch) => ch.current)),
|
|
1575
|
+
choices
|
|
1576
|
+
});
|
|
1577
|
+
if (chosen == null)
|
|
1578
|
+
return; // Esc / Ctrl+C — leave the model unchanged
|
|
1579
|
+
ctx.config.set("model", chosen);
|
|
1580
|
+
const label = chosen ? (models.find((m) => m.id === chosen)?.label ?? chosen) : AUTO_LABEL;
|
|
1581
|
+
info(`Model changed to ${label} (applies to your next message).`);
|
|
1582
|
+
}
|
|
1583
|
+
// ── Live memory markers ──────────────────────────────────────────────────────
|
|
1584
|
+
// The engine writes snapshots/restructures AFTER a turn returns (measured at
|
|
1585
|
+
// ~6s), so the chat response cannot carry them. The CLI keeps no local
|
|
1586
|
+
// transcript — thin client, backend owns conversation state — so the only way
|
|
1587
|
+
// to notice one is to ask. One lightweight fetch per turn, off the render path.
|
|
1588
|
+
/** Markers already shown, per session, for this process. */
|
|
1589
|
+
const seenMarkers = new Map();
|
|
1590
|
+
/** How long to wait for the engine to finish writing before looking. */
|
|
1591
|
+
const MARKER_SETTLE_MS = 1500;
|
|
1592
|
+
/**
|
|
1593
|
+
* Show any memory markers created by the turn that just finished.
|
|
1594
|
+
*
|
|
1595
|
+
* The first sighting of a session only records a baseline — resuming a
|
|
1596
|
+
* conversation with twelve existing markers must not dump all twelve into the
|
|
1597
|
+
* transcript. Everything is best-effort: a failure here must never touch the
|
|
1598
|
+
* answer the user already has.
|
|
1599
|
+
*/
|
|
1600
|
+
async function showNewMemoryMarkers(ctx, client, sessionId) {
|
|
1601
|
+
try {
|
|
1602
|
+
await sleep(MARKER_SETTLE_MS);
|
|
1603
|
+
const { messages } = await client.sessionMessages(sessionId);
|
|
1604
|
+
const markers = messages.filter(isMemoryMarker);
|
|
1605
|
+
// Numbering must match /history — position among ALL markers, 1-based — so
|
|
1606
|
+
// `/memory <n>` resolves the same way from either place.
|
|
1607
|
+
ctx.config.set("memoryArtifactIds", markers.map((m) => m.artifact_id ?? ""));
|
|
1608
|
+
const seen = seenMarkers.get(sessionId);
|
|
1609
|
+
seenMarkers.set(sessionId, markers.length);
|
|
1610
|
+
if (seen === undefined)
|
|
1611
|
+
return; // baseline only — nothing is "new" yet
|
|
1612
|
+
for (let i = seen; i < markers.length; i++) {
|
|
1613
|
+
line();
|
|
1614
|
+
line(memoryMarkerLine({ ...markers[i], index: i + 1 }));
|
|
1615
|
+
}
|
|
1616
|
+
if (markers.length > seen)
|
|
1617
|
+
line();
|
|
1618
|
+
}
|
|
1619
|
+
catch {
|
|
1620
|
+
/* the turn already succeeded — never surface a failure from this */
|
|
1621
|
+
}
|
|
1622
|
+
}
|