Merge f-split-qa3 (283258664) into f-split-int: web search back-off and Bing fallback, turn guard with a final message, /loop stops by count/time/condition, Anthropic base URL without /v1
This commit is contained in:
commit
7f7bfa962b
41 files changed
+1560
-135
No files matched your search
@@ -68,7 +68,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha
|
||||
What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs.
|
||||
|
||||
- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off.
|
||||
- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`): a browser User-Agent, one request at a time at least 1.5 s apart, at most 20 a minute, a 10 minute cache per query, a 15 s limit, the lite page as a fallback, and a plain message when DuckDuckGo asks for a human check ("limiting searches from this computer"). **The results come from DuckDuckGo**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous.
|
||||
- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast (a real box: two searches in 1.2 s answered, the third got HTTP 202 and every DuckDuckGo page refused for many minutes): a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous.
|
||||
- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found.
|
||||
- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart.
|
||||
- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server).
|
||||
@@ -121,3 +121,13 @@ A model on OpenRouter whose model list names `reasoning` in `supported_parameter
|
||||
## Pictures
|
||||
|
||||
Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag.
|
||||
|
||||
## Turn guard (`turn-guard.mjs`)
|
||||
|
||||
A turn that keeps failing the same way is stopped by the app, never left to the model. Seen on a search-heavy `/plan`: every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%, then the turn ended with no answer and no message.
|
||||
|
||||
- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up).
|
||||
- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step.
|
||||
- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged.
|
||||
- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded.
|
||||
- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network).
|
||||
@@ -28,6 +28,7 @@ import { ChildProjector } from './children.mjs';
|
||||
import { nearestBudget } from './llm-shape.mjs';
|
||||
import { DeliverableTracker, ActivityGroups } from './deliverables.mjs';
|
||||
import { SkillsUsed, skillInfoFrom } from './skills-used.mjs';
|
||||
import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs';
|
||||
import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs';
|
||||
|
||||
/**
|
||||
@@ -90,7 +91,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve
|
||||
* @param {string} [options.nodePath] the Node runtime that runs the Harness
|
||||
* @param {(line:string)=>void} [options.log]
|
||||
*/
|
||||
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
|
||||
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
|
||||
const root = join(dataDir, 'agent');
|
||||
const home = join(root, 'home');
|
||||
const sessionsFile = join(root, 'sessions.json');
|
||||
@@ -146,7 +147,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
/** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */
|
||||
let shapeTargets = {};
|
||||
function buildProfileNow() {
|
||||
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase });
|
||||
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock });
|
||||
shapeTargets = profile.shapeTargets ?? {};
|
||||
return profile;
|
||||
}
|
||||
@@ -311,6 +312,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true });
|
||||
// What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary.
|
||||
const written = { all: '', step: '' };
|
||||
// The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known.
|
||||
let guard = null;
|
||||
const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } };
|
||||
// What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends.
|
||||
const tracker = new DeliverableTracker(workspacePath, trackerFolders());
|
||||
@@ -319,7 +322,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
const groups = new ActivityGroups({ emit: raw });
|
||||
const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) });
|
||||
const emit = frame => {
|
||||
if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; }
|
||||
if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; }
|
||||
if (frame.own) { const { own, ...rest } = frame; frame = rest; }
|
||||
if (frame.type === 'delta' && frame.text) groups.text();
|
||||
if (frame.type === 'agent-tool' && frame.tool) {
|
||||
@@ -328,6 +331,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } }
|
||||
raw(frame);
|
||||
if (made) raw(made);
|
||||
if (guard) trip(guard.card(frame.tool));
|
||||
groups.card(frame.tool, made);
|
||||
skills.card(frame.tool);
|
||||
return;
|
||||
@@ -370,6 +374,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
await applyMode(runtime, sessionId, appliedMode);
|
||||
|
||||
const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval });
|
||||
if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess
|
||||
projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); };
|
||||
const turn = {
|
||||
sessionId, projector, route, requestId, live: false, lastSeq: -1,
|
||||
@@ -406,13 +411,19 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
clearInterval(turn.watchdog);
|
||||
turn.follow?.close();
|
||||
for (const child of turn.children.values()) child.follow?.close();
|
||||
if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };
|
||||
if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } };
|
||||
reporter.clear();
|
||||
const extra = [];
|
||||
try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
|
||||
groups.end();
|
||||
if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); }
|
||||
try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ }
|
||||
// The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself).
|
||||
let noteReason = turn.guard ?? null;
|
||||
if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) {
|
||||
noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens });
|
||||
}
|
||||
if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); }
|
||||
for (const f of extra) emit(f);
|
||||
const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow });
|
||||
for (const f of frames.slice(0, -1)) emit(f);
|
||||
@@ -425,6 +436,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
c.turn = null;
|
||||
turn.ended.resolve({ reason: projector.ended, failure: failure ?? null });
|
||||
notifyIdle();
|
||||
// A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room.
|
||||
if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId);
|
||||
}
|
||||
|
||||
emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) });
|
||||
@@ -442,6 +455,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
onError: e => finishTurn(`The agent lost the session stream: ${e.message}`),
|
||||
});
|
||||
|
||||
/** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */
|
||||
function trip(reason) {
|
||||
if (!reason || turn.guard || turn.finished || turn.stopping) return;
|
||||
turn.guard = reason;
|
||||
log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`);
|
||||
void stop(chatId).catch(() => {});
|
||||
}
|
||||
|
||||
function handle(item) {
|
||||
if (turn.finished) return;
|
||||
turn.lastActivity = Date.now();
|
||||
@@ -457,6 +478,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
}
|
||||
} else if (!turn.live) return;
|
||||
for (const f of projector.consume(item)) emit(f);
|
||||
if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens));
|
||||
if (item.type === 'event') watchParent(item.event);
|
||||
}
|
||||
|
||||
@@ -566,10 +588,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
/** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */
|
||||
function settlePlan(failure) {
|
||||
if (planTask) {
|
||||
if (failure || turn.stopping) return [];
|
||||
if (failure || (turn.stopping && !turn.guard)) return [];
|
||||
const parsed = parsePlan(written.all, planTask);
|
||||
if (!parsed) return [];
|
||||
const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask });
|
||||
const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) });
|
||||
return [publishPlan('proposed', plan)];
|
||||
}
|
||||
const run = turn.plan;
|
||||
@@ -1094,6 +1116,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
* Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the
|
||||
* Harness acknowledges a cancel as admitted, not as done.
|
||||
*/
|
||||
/** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */
|
||||
async function compactSession(runtime, sessionId) {
|
||||
try {
|
||||
const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] });
|
||||
log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`);
|
||||
} catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); }
|
||||
}
|
||||
|
||||
async function stop(chatId, { waitMs = 20_000 } = {}) {
|
||||
const c = chats.get(chatId);
|
||||
const turn = c?.turn;
|
||||
|
||||
@@ -193,9 +193,9 @@ export class PlanStore {
|
||||
} catch { /* the plan still lives in memory */ }
|
||||
}
|
||||
get(chatId) { return this.plans.get(chatId) ?? null; }
|
||||
create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed' }) {
|
||||
create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed', caution = null }) {
|
||||
const now = new Date().toISOString();
|
||||
const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false };
|
||||
const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false, ...(caution ? { caution } : {}) };
|
||||
this.plans.set(chatId, plan); this.#save();
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,10 @@ export const inject = ['web'];
|
||||
|
||||
export function apply(ctx, config = {}) {
|
||||
const keyOf = () => (config.keyEnv ? process.env[config.keyEnv] ?? '' : '');
|
||||
const provider = config.provider === 'exa' ? createExaSearch({ key: keyOf })
|
||||
// Tests only (the bridge option `searchMock`): the same search code on a pretend web, so nothing leaves the machine.
|
||||
const pretend = config.mock === 'limited' ? { fetch: async url => new Response('<html>please verify you are human: captcha</html>', { status: /duckduckgo/.test(String(url)) ? 202 : 429 }) } : null;
|
||||
const provider = pretend ? createDuckDuckGoSearch(pretend)
|
||||
: config.provider === 'exa' ? createExaSearch({ key: keyOf })
|
||||
: config.provider === 'perplexity' ? createPerplexitySearch({ key: keyOf })
|
||||
: createDuckDuckGoSearch();
|
||||
ctx.web.registerSearchProvider(provider);
|
||||
|
||||
@@ -163,7 +163,7 @@ export function outputBudget(context, maxOutput = null) {
|
||||
/** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */
|
||||
const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } };
|
||||
|
||||
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) {
|
||||
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null }) {
|
||||
const providers = {};
|
||||
const env = {};
|
||||
const routes = [];
|
||||
@@ -271,7 +271,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
|
||||
const webRows = !searchOn ? [] : keyed === 'deepseek'
|
||||
? [{ id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } }, { id: 'web-search-deepseek', config: { apiKeyEnv: 'STRATA_SEARCH_KEY' } }]
|
||||
: [{ id: 'web', config: { searchProvider: keyed ?? DDG_PROVIDER_ID, fetchProvider: 'http' } }, { id: 'web-search-deepseek', disabled: true },
|
||||
{ insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY' } }] }];
|
||||
{ insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY', ...(searchMock ? { mock: searchMock } : {}) } }] }];
|
||||
/** The models a helper agent may be started on: the table the model-choice plugin and the Harness's allow-list are written from. */
|
||||
const subagentRoutes = routes.map(r => ({ provider: r.route, model: r.modelId, name: r.name, connection: r.connectionName, local: r.kind === 'local' }));
|
||||
const entries = [
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* The turn guard: a turn that keeps failing the same way, or keeps rewriting the same thing, is stopped by the app and ends with a plain message.
|
||||
* Pure (no I/O); the bridge feeds it what the turn shows and acts on what it answers.
|
||||
*
|
||||
* Why: a search-heavy /plan on a small model searched again after every refusal and rewrote its plan after every search until the context
|
||||
* reached 100%, then the turn ended with no answer and no message. Nothing here relies on the model behaving: the app counts.
|
||||
*
|
||||
* searches-failed this many web searches in a row failed (web search was limited, or could not be reached)
|
||||
* searches this many searches in one turn (a plan or an ordinary answer needs a handful, not dozens)
|
||||
* rewrites a plan turn wrote its numbered plan from "1." again this many times
|
||||
* context the context is nearly full: the Harness compaction did not keep up
|
||||
*
|
||||
* What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all eight languages (the page
|
||||
* translates a `delta` frame that carries `key`). Each says what happened and gives one next step.
|
||||
*/
|
||||
|
||||
export const GUARD_LIMITS = Object.freeze({
|
||||
failedSearches: 3,
|
||||
searchesPlan: 10,
|
||||
searchesTurn: 25,
|
||||
planRewrites: 4,
|
||||
contextFraction: 0.93,
|
||||
/** A turn that ends with no words at all and a context this full is "out of room", not "nothing to say". */
|
||||
contextEmptyFraction: 0.85,
|
||||
});
|
||||
|
||||
const SEARCH_TOOLS = new Set(['web_search']);
|
||||
const SEARCH_FAILED = /web search is limited|search could not reach|could not reach the internet|WEB_RATE_LIMITED|WEB_PROVIDER_ERROR|did not accept the key|too many searches/i;
|
||||
|
||||
/** The plain sentences, keyed by reason. `values` are the slots the page fills in. */
|
||||
const NOTES = {
|
||||
'searches-failed': 'Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.',
|
||||
searches: 'I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.',
|
||||
rewrites: 'I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.',
|
||||
context: 'I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.',
|
||||
empty: 'I stopped without writing an answer. Send your message again, or say “continue”.',
|
||||
};
|
||||
export const GUARD_NOTES = Object.freeze({ ...NOTES });
|
||||
|
||||
/** A `delta` frame the page shows as ordinary assistant text and translates (`key` is the English sentence). */
|
||||
export function guardNote(reason) {
|
||||
const text = NOTES[reason];
|
||||
return text ? { type: 'delta', own: true, text: `\n\n${text}`, key: text, noteReason: reason } : null;
|
||||
}
|
||||
|
||||
export class TurnGuard {
|
||||
/**
|
||||
* @param {{plan?: boolean, contextMax?: number, limits?: Partial<typeof GUARD_LIMITS>}} [options]
|
||||
*/
|
||||
constructor({ plan = false, contextMax = 0, limits = {} } = {}) {
|
||||
this.plan = plan; this.contextMax = Number(contextMax) || 0;
|
||||
this.limits = { ...GUARD_LIMITS, ...limits };
|
||||
this.seen = new Set();
|
||||
this.searches = 0; this.failedInARow = 0; this.failedTotal = 0;
|
||||
this.rewrites = 0; this.written = '';
|
||||
this.reason = null;
|
||||
}
|
||||
|
||||
#fire(reason) { this.reason ??= reason; return this.reason; }
|
||||
|
||||
/** A tool card frame (`agent-tool`). Counts a search once, when it has finished. Returns the reason to stop, or null. */
|
||||
card(tool) {
|
||||
if (this.reason || !tool || !SEARCH_TOOLS.has(tool.name)) return this.reason;
|
||||
const done = tool.state === 'done' || tool.state === 'error' || tool.state === 'denied';
|
||||
if (!done || this.seen.has(tool.id)) return this.reason;
|
||||
this.seen.add(tool.id);
|
||||
this.searches += 1;
|
||||
const failed = tool.state === 'error' || SEARCH_FAILED.test(String(tool.result ?? ''));
|
||||
if (failed) { this.failedInARow += 1; this.failedTotal += 1; } else this.failedInARow = 0;
|
||||
if (this.failedInARow >= this.limits.failedSearches) return this.#fire('searches-failed');
|
||||
if (this.searches >= (this.plan ? this.limits.searchesPlan : this.limits.searchesTurn)) return this.#fire(this.failedTotal >= this.searches / 2 ? 'searches-failed' : 'searches');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/** Text the assistant wrote (not our own lines). A plan turn that starts its numbered list again and again is rewriting. */
|
||||
text(delta) {
|
||||
if (this.reason || !this.plan || !delta) return this.reason;
|
||||
this.written += delta;
|
||||
if (this.written.length > 200_000) this.written = this.written.slice(-100_000);
|
||||
if (!delta.includes('\n') && !/\d[.)]\s/.test(delta)) return this.reason;
|
||||
this.rewrites = (this.written.match(/(?:^|\n)[ \t]{0,3}1[.)][ \t]+\S/g) ?? []).length;
|
||||
if (this.rewrites >= this.limits.planRewrites) return this.#fire('rewrites');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/** What the context holds now (tokens of the last request). */
|
||||
context(tokens) {
|
||||
if (this.reason || !this.contextMax || !Number.isFinite(tokens)) return this.reason;
|
||||
if (tokens / this.contextMax >= this.limits.contextFraction) return this.#fire('context');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn is over. If the person has seen no words from it, which sentence do they get? `ended` is the Harness's turn end reason,
|
||||
* `wrote` whether any answer text was shown, `acted` whether tool cards were shown, `contextTokens` the last request's size. Returns a reason or null.
|
||||
*/
|
||||
silent({ ended, wrote, contextTokens, acted = false, stoppedByPerson = false }) {
|
||||
if (this.reason) return this.reason;
|
||||
if (stoppedByPerson || wrote) return null;
|
||||
const kind = ended?.kind;
|
||||
if (kind !== 'completed' && kind !== 'max-tokens') return null; // an error says why by itself; Stop is the person's own
|
||||
if (this.contextMax && Number(contextTokens) / this.contextMax >= this.limits.contextEmptyFraction) return 'context';
|
||||
return acted ? null : 'empty'; // cards of work done are an answer of a kind; no cards and no words is not
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Anthropic clients add `/v1/messages` to the base URL themselves, so the base URL they are given is the server root (no `/v1`).
|
||||
* A base URL copied from an OpenAI-style setup ends in `/v1`, and the client then posts `/v1/v1/messages`. That one path means the
|
||||
* same as the real one; nothing else is aliased (an OpenAI client never adds `/v1` on its own).
|
||||
*/
|
||||
const ALIASES = new Map([['/v1/v1/messages', '/v1/messages'], ['/v1/v1/messages/count_tokens', '/v1/messages/count_tokens']]);
|
||||
|
||||
export function apiPath(path) {
|
||||
const clean = path.length > 1 ? path.replace(/\/+$/, '') : path;
|
||||
return ALIASES.get(clean) ?? path;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ import { forbidden as acquisitionForbidden } from './acquisition.mjs';
|
||||
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { nativeGateway } from './native-gateway.mjs';
|
||||
import { proxyCompletion } from './inference.mjs';
|
||||
import { apiPath } from './api-paths.mjs';
|
||||
import { validateChatImages } from './chat-images.mjs';
|
||||
import { createTimeSkip, measureFolder, timeskipRevisionMessage, imageTypeOf } from './timeskip.mjs';
|
||||
|
||||
@@ -925,7 +926,7 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (path.startsWith('/v1/')) {
|
||||
if (storageChanging && method !== 'GET') return error(res, 409, 'Wait for the model folder check to finish.');
|
||||
return await openai(req, res, path, method);
|
||||
return await openai(req, res, apiPath(path), method);
|
||||
}
|
||||
return await staticFile(req, res, path);
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** A separate, key-protected listener for inference only. Never serves the UI or host APIs. */
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import { apiPath } from './api-paths.mjs';
|
||||
export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0.0.0.0', port = 8792 }) {
|
||||
let listener = null, active = false;
|
||||
const address = () => Object.values(os.networkInterfaces()).flat().find(n => n?.family === 'IPv4' && !n.internal)?.address ?? '127.0.0.1';
|
||||
@@ -10,7 +11,7 @@ export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0
|
||||
if (listener) throw new Error('Sharing is already starting.');
|
||||
if (!hasKey()) throw new Error('Set an API key before sharing with other devices.');
|
||||
listener = http.createServer(async (req, res) => {
|
||||
const path = new URL(req.url ?? '/', 'http://localhost').pathname;
|
||||
const path = apiPath(new URL(req.url ?? '/', 'http://localhost').pathname);
|
||||
if (!['/v1/models','/v1/chat/completions','/v1/messages'].includes(path)) { res.writeHead(404); res.end('Not found'); return; }
|
||||
try { await handle(req, res, path, req.method ?? 'GET'); }
|
||||
catch { if (!res.headersSent) res.writeHead(500); res.end('Request failed'); }
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The second keyless source for the agent's web search: Bing's plain result page, used only when DuckDuckGo refuses.
|
||||
*
|
||||
* It is read the way a browser reads it (an ordinary User-Agent, the page's own request shape, nothing hidden) and is held to the same
|
||||
* manners as DuckDuckGo (see web-search-ddg.mjs): one request at a time, spaced out, a cooldown after a refusal. Results are not ranked or
|
||||
* filtered here. Pure parsing lives in this file so it can be tested on saved pages.
|
||||
*/
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/', '#183': '·' };
|
||||
const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => {
|
||||
if (key[0] === '#') {
|
||||
const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : parseInt(key.slice(1), 10);
|
||||
return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : whole;
|
||||
}
|
||||
return ENTITIES[key.toLowerCase()] ?? whole;
|
||||
});
|
||||
const plain = html => decode(String(html).replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim();
|
||||
|
||||
export const BING_URL = 'https://www.bing.com/search';
|
||||
|
||||
/** Bing wraps every result link in its own redirect (`/ck/a?...&u=a1<base64url of the real address>`). */
|
||||
export function bingTarget(href) {
|
||||
const value = decode(href).trim();
|
||||
try {
|
||||
const url = new URL(value, 'https://www.bing.com/');
|
||||
if (/(^|\.)bing\.com$/i.test(url.hostname)) {
|
||||
const u = url.searchParams.get('u');
|
||||
if (u && /^a1/.test(u)) {
|
||||
const target = Buffer.from(u.slice(2).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
||||
const real = new URL(target);
|
||||
return /^https?:$/.test(real.protocol) ? real.href : null;
|
||||
}
|
||||
return null; // Bing's own page (images, maps, "more results")
|
||||
}
|
||||
return /^https?:$/.test(url.protocol) ? url.href : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** The result list of the page. Tolerant: a result needs a link and a title; the snippet is optional. */
|
||||
export function parseBingResults(html) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const blocks = String(html).split(/<li\b[^>]*\bclass="[^"]*\bb_algo\b[^"]*"/i).slice(1);
|
||||
for (const block of blocks) {
|
||||
const end = block.search(/<li\b[^>]*\bclass="[^"]*\bb_(?:algo|ans|ad|pag)\b/i);
|
||||
const body = end > 0 ? block.slice(0, end) : block;
|
||||
const h2 = /<h2\b[^>]*>\s*<a\b([^>]*)>([\s\S]*?)<\/a>/i.exec(body);
|
||||
if (!h2) continue;
|
||||
const href = /\bhref="([^"]*)"/i.exec(h2[1])?.[1];
|
||||
const url = href ? bingTarget(href) : null;
|
||||
const title = plain(h2[2]);
|
||||
if (!url || !title || seen.has(url)) continue;
|
||||
const snippetMatch = /<p\b[^>]*class="[^"]*\bb_lineclamp\d*\b[^"]*"[^>]*>([\s\S]*?)<\/p>/i.exec(body)
|
||||
?? /<div\b[^>]*class="[^"]*\bb_caption\b[^"]*"[^>]*>[\s\S]*?<p\b[^>]*>([\s\S]*?)<\/p>/i.exec(body);
|
||||
const snippet = snippetMatch ? plain(snippetMatch[1]) : '';
|
||||
seen.add(url);
|
||||
out.push({ url, title, ...(snippet ? { snippet } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bing serves a challenge page, or a refusal, instead of results. A page with results is never "blocked". */
|
||||
export function bingLooksBlocked(status, html) {
|
||||
if (status === 403 || status === 429 || status === 503) return true;
|
||||
const text = String(html).slice(0, 80000);
|
||||
if (/\bclass="[^"]*\bb_algo\b/.test(text)) return false;
|
||||
return /captcha|unusual traffic|are you a robot|verify you are (?:a )?human|\bcf-chl|challenge-platform/i.test(text);
|
||||
}
|
||||
@@ -1,28 +1,39 @@
|
||||
/**
|
||||
* Web search with no account and no key: DuckDuckGo's own web-page search results.
|
||||
* Web search with no account and no key: DuckDuckGo's own web-page search results, with Bing's plain result page as the second source.
|
||||
*
|
||||
* The Harness has three search backends and all of them need a paid service key. This is the fourth: it asks DuckDuckGo's plain
|
||||
* HTML search page the way a browser does and reads the result list out of the page. It is the default for the agent's
|
||||
* `web_search` tool; the person can switch to a keyed service in Settings -> Tools.
|
||||
*
|
||||
* Being polite is part of the design:
|
||||
* - an ordinary browser User-Agent and the page's own request shape (nothing hidden, nothing faked beyond the User-Agent);
|
||||
* - at most one request every 1.5 s and 20 a minute from this program, with the same query answered from a 10 minute cache;
|
||||
* - a 15 s time limit, no retries in a loop; when DuckDuckGo asks for a human check or refuses, the answer says so in plain
|
||||
* words and the model is told to carry on without search.
|
||||
* Results come from DuckDuckGo; they are not ranked or filtered here.
|
||||
* Being polite is part of the design, because DuckDuckGo refuses a program that asks too fast (2026-10-18, a Linux box: two searches in
|
||||
* 1.2 s were answered, the third got HTTP 202 "anomaly" and every DuckDuckGo page then refused for minutes):
|
||||
* - an ordinary browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*; nothing hidden);
|
||||
* - one request at a time per source, 2.5 to 4 s apart (random, so it does not look like a clock), at most 8 a minute;
|
||||
* - the same question is answered from a session cache (30 minutes), so a model that repeats itself costs nothing;
|
||||
* - when a source refuses (HTTP 202/403/429 or a challenge page) it is left alone for a cooldown that doubles every time it refuses
|
||||
* again (1, 2, 4 ... up to 10 minutes; a Retry-After header is honoured) instead of being asked again, which only extends a block;
|
||||
* - a refused DuckDuckGo page is not followed by the lite page (same refusal, one more strike): the next source is tried instead;
|
||||
* - a timeout or a server error gets one retry after a short pause, then the next source;
|
||||
* - when every source refuses the answer is one plain sentence that also tells the model not to retry (see LIMITED_MESSAGE).
|
||||
* Results come from DuckDuckGo or Bing; they are not ranked or filtered here.
|
||||
*
|
||||
* Nothing in this file touches the Harness, so it can be tested alone. `strata-search.mjs` is the plugin that registers it.
|
||||
*/
|
||||
import { BING_URL, bingLooksBlocked, parseBingResults } from './web-search-bing.mjs';
|
||||
|
||||
export const DDG_PROVIDER_ID = 'strata-duckduckgo';
|
||||
|
||||
const HTML_URL = 'https://html.duckduckgo.com/html/';
|
||||
const LITE_URL = 'https://lite.duckduckgo.com/lite/';
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36';
|
||||
const CACHE_MS = 10 * 60 * 1000;
|
||||
const MIN_GAP_MS = 1500;
|
||||
const PER_MINUTE = 20;
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
|
||||
const CACHE_MS = 30 * 60 * 1000;
|
||||
const CACHE_SIZE = 120;
|
||||
const GAP_MS = 2500;
|
||||
const JITTER_MS = 1500;
|
||||
const PER_MINUTE = 8;
|
||||
const COOLDOWN_MS = 60_000;
|
||||
const COOLDOWN_MAX_MS = 10 * 60_000;
|
||||
const RETRY_PAUSE_MS = 1500;
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/' };
|
||||
const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => {
|
||||
@@ -106,83 +117,148 @@ export function looksBlocked(status, html) {
|
||||
&& !/class="[^"]*\bresult__a\b/.test(html);
|
||||
}
|
||||
|
||||
|
||||
export class SearchUnavailable extends Error {
|
||||
constructor(message, code = 'WEB_PROVIDER_ERROR', options) { super(message, options); this.name = 'WebError'; this.code = code; }
|
||||
}
|
||||
|
||||
export const BLOCKED_MESSAGE = 'DuckDuckGo is limiting searches from this computer right now. Try again in a few minutes, or add a search key in Settings, Tools.';
|
||||
/** The one plain sentence for the person. The words "Settings → Tools → Web search" are where the key goes in the app. */
|
||||
export const LIMITED_SENTENCE = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search.';
|
||||
/** What the tool answers: the sentence, then what the model should do (it must not keep searching). */
|
||||
export const BLOCKED_MESSAGE = `${LIMITED_SENTENCE} Do not retry this search: go on with what you know and tell the person, in one plain sentence, that web search was limited.`;
|
||||
export const UNREACHABLE_MESSAGE = 'The search could not reach the internet. Check the connection and try again. Do not retry this search now: go on with what you know and say that search was unavailable.';
|
||||
|
||||
/**
|
||||
* @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise<void>}} [deps]
|
||||
*/
|
||||
export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) {
|
||||
const cache = new Map();
|
||||
const starts = [];
|
||||
let last = 0;
|
||||
let chain = Promise.resolve();
|
||||
|
||||
/** One request at a time, spaced out, and at most PER_MINUTE a minute. */
|
||||
function turn(signal) {
|
||||
const run = chain.then(async () => {
|
||||
/** One request at a time, spaced out with a little randomness, and at most PER_MINUTE a minute. */
|
||||
class Pacer {
|
||||
constructor({ now, sleep, random, gap = GAP_MS, jitter = JITTER_MS, perMinute = PER_MINUTE }) {
|
||||
Object.assign(this, { now, sleep, random, gap, jitter, perMinute });
|
||||
this.starts = []; this.last = 0; this.chain = Promise.resolve();
|
||||
}
|
||||
turn(signal) {
|
||||
const run = this.chain.then(async () => {
|
||||
const spacing = this.gap + Math.floor(this.random() * this.jitter);
|
||||
for (;;) {
|
||||
signal?.throwIfAborted();
|
||||
const t = now();
|
||||
while (starts.length && t - starts[0] > 60_000) starts.shift();
|
||||
const wait = Math.max(MIN_GAP_MS - (t - last), starts.length >= PER_MINUTE ? 60_000 - (t - starts[0]) : 0);
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED');
|
||||
const t = this.now();
|
||||
while (this.starts.length && t - this.starts[0] > 60_000) this.starts.shift();
|
||||
const wait = this.last ? Math.max(spacing - (t - this.last), this.starts.length >= this.perMinute ? 60_000 - (t - this.starts[0]) : 0) : 0;
|
||||
if (wait <= 0) break;
|
||||
if (wait > 30_000) throw new SearchUnavailable('Too many searches in a short time. Try again in a minute.', 'WEB_RATE_LIMITED');
|
||||
await sleep(wait);
|
||||
if (wait > 30_000) throw new SearchUnavailable(LIMITED_SENTENCE, 'WEB_RATE_LIMITED');
|
||||
await this.sleep(wait);
|
||||
}
|
||||
last = now();
|
||||
starts.push(last);
|
||||
this.last = this.now();
|
||||
this.starts.push(this.last);
|
||||
});
|
||||
chain = run.catch(() => {});
|
||||
this.chain = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
}
|
||||
|
||||
async function ask(url, query, signal) {
|
||||
const REFUSED = Symbol('refused');
|
||||
const retryAfterMs = res => {
|
||||
const v = Number(res?.headers?.get?.('retry-after'));
|
||||
return Number.isFinite(v) && v > 0 ? Math.min(v * 1000, COOLDOWN_MAX_MS) : 0;
|
||||
};
|
||||
const serverError = status => status >= 500 && status < 600;
|
||||
const queryKey = query => query.toLowerCase().replace(/\s+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise<void>, random?: () => number}} [deps]
|
||||
*/
|
||||
export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), random = Math.random } = {}) {
|
||||
const cache = new Map();
|
||||
|
||||
/** A source: its pacing, and what to do after it refuses. */
|
||||
const source = (id, name) => ({ id, name, pacer: new Pacer({ now, sleep, random }), blockedUntil: 0, strikes: 0, refusals: 0 });
|
||||
const ddg = source('duckduckgo', 'DuckDuckGo');
|
||||
const bing = source('bing', 'Bing');
|
||||
const refuse = (s, res) => {
|
||||
s.strikes += 1; s.refusals += 1;
|
||||
s.blockedUntil = now() + Math.max(retryAfterMs(res), Math.min(COOLDOWN_MS * 2 ** (s.strikes - 1), COOLDOWN_MAX_MS));
|
||||
};
|
||||
const accepted = s => { s.strikes = 0; s.blockedUntil = 0; };
|
||||
|
||||
const headers = (origin, extra = {}) => ({
|
||||
'user-agent': USER_AGENT, accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.9',
|
||||
'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1',
|
||||
...(origin ? { referer: `${origin}/`, origin } : {}), ...extra,
|
||||
});
|
||||
|
||||
async function get(url, init, signal) {
|
||||
const timeout = AbortSignal.timeout(15_000);
|
||||
const res = await fetchImpl(url, {
|
||||
method: 'POST', redirect: 'follow',
|
||||
headers: { 'user-agent': USER_AGENT, 'content-type': 'application/x-www-form-urlencoded', accept: 'text/html,application/xhtml+xml', 'accept-language': 'en-US,en;q=0.8' },
|
||||
body: new URLSearchParams({ q: query, b: '' }).toString(),
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
});
|
||||
const html = await res.text();
|
||||
return { status: res.status, html };
|
||||
const res = await fetchImpl(url, { redirect: 'follow', ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
|
||||
return { res, status: res.status, html: await res.text() };
|
||||
}
|
||||
|
||||
/** One page request with one retry after a pause for a timeout, a network error or a server error. Throws SearchUnavailable only for cancel. */
|
||||
async function ask(s, makeRequest, signal) {
|
||||
let failure;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
await s.pacer.turn(signal);
|
||||
try {
|
||||
const page = await get(...makeRequest(), signal);
|
||||
if (!serverError(page.status)) return page;
|
||||
failure = new Error(`HTTP ${page.status}`);
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
|
||||
failure = error;
|
||||
}
|
||||
if (attempt === 0) await sleep(RETRY_PAUSE_MS + Math.floor(random() * 1000));
|
||||
}
|
||||
return { failure };
|
||||
}
|
||||
|
||||
async function searchDuckDuckGo(query, signal) {
|
||||
const form = new URLSearchParams({ q: query, b: '', kl: 'wt-wt', df: '' }).toString();
|
||||
const post = (url, origin) => () => [url, { method: 'POST', headers: headers(origin, { 'content-type': 'application/x-www-form-urlencoded' }), body: form }];
|
||||
let reachedOnce = false;
|
||||
for (const [url, origin, parse] of [[HTML_URL, 'https://html.duckduckgo.com', parseHtmlResults], [LITE_URL, 'https://lite.duckduckgo.com', parseLiteResults]]) {
|
||||
const page = await ask(ddg, post(url, origin), signal);
|
||||
if (page.failure) return { failure: page.failure };
|
||||
reachedOnce = true;
|
||||
// A refusal on the first page is a refusal for the whole address: the lite page would only add one more strike.
|
||||
if (looksBlocked(page.status, page.html)) { refuse(ddg, page.res); return { refused: true }; }
|
||||
const sources = parse(page.html);
|
||||
if (sources.length) { accepted(ddg); return { sources }; }
|
||||
}
|
||||
if (reachedOnce) accepted(ddg);
|
||||
return { sources: [] };
|
||||
}
|
||||
|
||||
async function searchBing(query, signal) {
|
||||
const url = `${BING_URL}?${new URLSearchParams({ q: query, setlang: 'en' })}`;
|
||||
const page = await ask(bing, () => [url, { method: 'GET', headers: headers(null) }], signal);
|
||||
if (page.failure) return { failure: page.failure };
|
||||
if (bingLooksBlocked(page.status, page.html)) { refuse(bing, page.res); return { refused: true }; }
|
||||
accepted(bing);
|
||||
return { sources: parseBingResults(page.html) };
|
||||
}
|
||||
|
||||
return {
|
||||
id: DDG_PROVIDER_ID,
|
||||
available: () => typeof fetchImpl === 'function',
|
||||
/** What happened so far, for tests and for the status line in the app's log. */
|
||||
status: () => ({ duckduckgo: { strikes: ddg.strikes, refusals: ddg.refusals, blockedForMs: Math.max(0, ddg.blockedUntil - now()) }, bing: { strikes: bing.strikes, refusals: bing.refusals, blockedForMs: Math.max(0, bing.blockedUntil - now()) }, cached: cache.size }),
|
||||
async search(request, signal) {
|
||||
const query = String(request.query ?? '').trim().slice(0, 400);
|
||||
if (!query) throw new SearchUnavailable('Type what to search for.', 'WEB_PROVIDER_ERROR');
|
||||
const key = query.toLowerCase();
|
||||
const key = queryKey(query);
|
||||
const want = request.maxResults ?? 10;
|
||||
const hit = cache.get(key);
|
||||
if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, request.maxResults ?? 10), truncated: false };
|
||||
let sources = [];
|
||||
let blocked = false;
|
||||
for (const [url, parse] of [[HTML_URL, parseHtmlResults], [LITE_URL, parseLiteResults]]) {
|
||||
await turn(signal);
|
||||
let page;
|
||||
try { page = await ask(url, query, signal); }
|
||||
catch (error) {
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
|
||||
if (error?.name === 'TimeoutError') throw new SearchUnavailable('The search took too long. Try again.', 'WEB_TIMEOUT', { cause: error });
|
||||
throw new SearchUnavailable('The search could not reach DuckDuckGo. Check the internet connection and try again.', 'WEB_PROVIDER_ERROR', { cause: error });
|
||||
}
|
||||
if (looksBlocked(page.status, page.html)) { blocked = true; continue; }
|
||||
sources = parse(page.html);
|
||||
if (sources.length) { blocked = false; break; }
|
||||
if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, want), truncated: false };
|
||||
let limited = false, unreachable = false;
|
||||
for (const [s, run] of [[ddg, searchDuckDuckGo], [bing, searchBing]]) {
|
||||
if (s.blockedUntil > now()) { limited = true; continue; } // asked again too soon: that only extends a block
|
||||
const result = await run(query, signal);
|
||||
if (result.refused) { limited = true; continue; }
|
||||
if (result.failure) { unreachable = true; continue; }
|
||||
if (!result.sources.length) return { sources: [], truncated: false }; // a real search with no results is an answer, not an error
|
||||
cache.set(key, { at: now(), sources: result.sources });
|
||||
if (cache.size > CACHE_SIZE) cache.delete(cache.keys().next().value);
|
||||
return { sources: result.sources.slice(0, want), truncated: false };
|
||||
}
|
||||
if (!sources.length) {
|
||||
if (blocked) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED');
|
||||
return { sources: [], truncated: false }; // a real search with no results is an answer, not an error
|
||||
}
|
||||
cache.set(key, { at: now(), sources });
|
||||
if (cache.size > 60) cache.delete(cache.keys().next().value);
|
||||
return { sources: sources.slice(0, request.maxResults ?? 10), truncated: false };
|
||||
if (limited) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED');
|
||||
throw new SearchUnavailable(unreachable ? UNREACHABLE_MESSAGE : BLOCKED_MESSAGE, unreachable ? 'WEB_PROVIDER_ERROR' : 'WEB_RATE_LIMITED');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -59,6 +59,7 @@ export function PlanCard({ chatId, planId }: { chatId: string | null | undefined
|
||||
return <section className="plan" data-state={plan.state} aria-label={tr("Plan")}>
|
||||
<div className="plan__head"><b>{tr("Plan")}</b><span>{planCount(plan)}</span></div>
|
||||
<PlanSteps plan={plan}/>
|
||||
{plan.caution ? <p className="plan__note" role="status">{tr(plan.caution)}</p> : null}
|
||||
{proposed ? <p className="plan__note">{tr("Nothing runs until you approve.")}</p> : null}
|
||||
{proposed ? <div className="plan__acts">
|
||||
<Btn size="sm" variant="primary" icon="check" disabled={busy || streaming} onClick={() => void run(() => approvePlan(chatId, plan.id))}>{tr("Approve")}</Btn>
|
||||
|
||||
@@ -130,7 +130,7 @@ export function SettingsTools({ preview }: { preview?: ToolsState }) {
|
||||
<section className="settings-section">
|
||||
<h2 className="h4" style={{ marginBottom: 10 }}>{tr('Web search')}</h2>
|
||||
<div className="st-card st-card--flush">
|
||||
<Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo. You do not need an account or a key.')}>
|
||||
<Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.')}>
|
||||
<Select ariaLabel={tr('Where results come from')} value={state.search.provider} options={SEARCH_CHOICES} onChange={value => { setKey(''); void save({ search: { provider: value } }); }} />
|
||||
</Field>
|
||||
{keyed ? <Field label={tr('Your key')} hint={tr(state.search.keySet ? 'A key is saved on this computer. Enter a new one to replace it.' : 'Saved on this computer only. Strata never shows it again.')}>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* The address an app is given depends on who builds the final request URL.
|
||||
*
|
||||
* OpenAI-style clients (Chat Completions, Responses) are given the base that ends in /v1 and add /chat/completions or /responses.
|
||||
* Anthropic-style clients (Claude Code, the Anthropic SDKs) add /v1/messages themselves, so they are given the server root. With
|
||||
* the /v1 base they post /v1/v1/messages.
|
||||
*/
|
||||
export type ConnectProtocol = 'openai' | 'responses' | 'anthropic';
|
||||
|
||||
/** The server root: the base address without its trailing /v1. */
|
||||
export function serverRoot(baseUrl: string): string {
|
||||
return String(baseUrl ?? '').trim().replace(/\/+$/, '').replace(/\/v1$/i, '');
|
||||
}
|
||||
|
||||
/** The address to type into an app that speaks this protocol. */
|
||||
export function appBaseUrl(baseUrl: string, protocol: ConnectProtocol): string {
|
||||
return protocol === 'anthropic' ? serverRoot(baseUrl) : String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { tr } from './i18n';
|
||||
import { LOOP_MAX_FAILURES, LOOP_MAX_RUNS, judgeAnswer, loopEndNote, loopEvery, loopLimitNote, withStopRule, type LoopLimits, type LoopStop } from './loop';
|
||||
|
||||
/**
|
||||
* The /loop scheduler. It owns the timer, the count, the time limit and the "the answer says it is done" rule, so a stop condition
|
||||
* is enforced here, in the app, and never left to the model: once a loop has ended nothing is sent again.
|
||||
*
|
||||
* Everything outside (sending the message, reading the answer, adding a line to the chat, the clock) is passed in, so the same code
|
||||
* runs in the app (store.ts) and in the tests with a scripted model and a fake clock.
|
||||
*/
|
||||
export interface LoopHost {
|
||||
/** Send the message as an ordinary chat turn and resolve when the answer is complete. `answered` is false when nothing was sent (the chat was busy). */
|
||||
send(sessionId: string, message: { text: string; shown: string }): Promise<{ answered: boolean; text: string; failed: boolean }>;
|
||||
/** A line from the app itself in the chat (never sent to the model). */
|
||||
note(sessionId: string, text: string): void;
|
||||
/** False when the chat was deleted: the loop ends quietly. */
|
||||
exists(sessionId: string): boolean;
|
||||
/** True when this chat is open and nothing is being answered. */
|
||||
ready(sessionId: string): boolean;
|
||||
now(): number;
|
||||
setTimer(fn: () => void, ms: number): unknown;
|
||||
clearTimer(handle: unknown): void;
|
||||
}
|
||||
|
||||
export interface LoopStart extends LoopLimits { everyMs: number; prompt: string }
|
||||
|
||||
interface LoopState extends LoopStart {
|
||||
answers: number;
|
||||
failures: number;
|
||||
startedAt: number;
|
||||
timer: unknown;
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
export class LoopScheduler {
|
||||
private readonly loops = new Map<string, LoopState>();
|
||||
/** How long to wait before looking again when the chat is busy or not open. */
|
||||
busyRetryMs = 15_000;
|
||||
|
||||
constructor(private readonly host: LoopHost) {}
|
||||
|
||||
isRunning(sessionId: string | null): boolean { return !!sessionId && this.loops.has(sessionId); }
|
||||
|
||||
/** What the person is told for /loop with nothing after it. */
|
||||
describe(sessionId: string): string | null {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return null;
|
||||
const limit = loopLimitNote(loop);
|
||||
return tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : '');
|
||||
}
|
||||
|
||||
stop(sessionId: string): boolean {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return false;
|
||||
if (loop.timer) this.host.clearTimer(loop.timer);
|
||||
this.loops.delete(sessionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Start a loop and send its first message now. Returns false (and says why in the chat) when the chat already has one. */
|
||||
async start(sessionId: string, command: LoopStart): Promise<boolean> {
|
||||
if (this.loops.has(sessionId)) { this.host.note(sessionId, tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return false; }
|
||||
const loop: LoopState = { ...command, answers: 0, failures: 0, startedAt: this.host.now(), timer: null, running: false };
|
||||
this.loops.set(sessionId, loop);
|
||||
const limit = loopLimitNote(loop);
|
||||
this.host.note(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : ''));
|
||||
await this.run(sessionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Send once, judge the answer, then either end the loop with a plain note or wait for the next time. */
|
||||
private async run(sessionId: string): Promise<void> {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop || loop.running) return;
|
||||
loop.running = true;
|
||||
let why: LoopStop | null = null;
|
||||
try {
|
||||
const result = await this.host.send(sessionId, { text: withStopRule(loop.prompt, loop.stopWhen), shown: loop.prompt });
|
||||
// The person may have typed /loop stop while the answer was coming: nothing more happens then.
|
||||
if (this.loops.get(sessionId) !== loop) return;
|
||||
if (result.answered) {
|
||||
if (result.failed) loop.failures += 1; else { loop.failures = 0; loop.answers += 1; }
|
||||
why = judgeAnswer(loop, loop, result, this.host.now());
|
||||
}
|
||||
} catch {
|
||||
if (this.loops.get(sessionId) !== loop) return;
|
||||
loop.failures += 1;
|
||||
if (loop.failures >= LOOP_MAX_FAILURES) why = 'failures';
|
||||
} finally {
|
||||
loop.running = false;
|
||||
}
|
||||
if (why) { this.finish(sessionId, loop, why); return; }
|
||||
this.schedule(sessionId, loop.everyMs);
|
||||
}
|
||||
|
||||
private finish(sessionId: string, loop: LoopState, why: LoopStop) {
|
||||
this.stop(sessionId);
|
||||
this.host.note(sessionId, loopEndNote(why, loop.answers));
|
||||
}
|
||||
|
||||
private schedule(sessionId: string, ms: number) {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = this.host.setTimer(() => void this.tick(sessionId), ms);
|
||||
}
|
||||
|
||||
private async tick(sessionId: string): Promise<void> {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = null;
|
||||
if (!this.host.exists(sessionId)) { this.stop(sessionId); return; }
|
||||
// The time is up, or the count is reached: never fire again, even if the last answer was not judged (a busy chat).
|
||||
if (loop.maxMs !== undefined && this.host.now() - loop.startedAt >= loop.maxMs) { this.finish(sessionId, loop, 'time'); return; }
|
||||
if (loop.maxRuns !== undefined && loop.answers >= loop.maxRuns) { this.finish(sessionId, loop, 'count'); return; }
|
||||
if (loop.answers >= LOOP_MAX_RUNS) { this.finish(sessionId, loop, 'cap'); return; }
|
||||
// Wait for a quiet moment: this chat is open and nothing is being answered.
|
||||
if (!this.host.ready(sessionId)) { this.schedule(sessionId, this.busyRetryMs); return; }
|
||||
await this.run(sessionId);
|
||||
}
|
||||
}
|
||||
+128
-6
@@ -3,20 +3,29 @@ import { tr } from './i18n';
|
||||
/**
|
||||
* /loop: send the same message again and again, every few minutes, while this chat is open.
|
||||
*
|
||||
* /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)
|
||||
* /loop stop stop
|
||||
* /loop say whether a loop is running
|
||||
* /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)
|
||||
* /loop 5m say hi, stop after 3 answers stops by itself after the 3rd answer (a count in words works too)
|
||||
* /loop 10m check the build for the next 2 hours stops by itself when the time is up
|
||||
* /loop 5m check the build, stop when it passes stops when the answer says it is done
|
||||
* /loop stop stop
|
||||
* /loop say whether a loop is running
|
||||
*
|
||||
* The loop lives in the app window: it waits for the chat to be idle, and it stops when the window closes.
|
||||
* For work that must go on with the app closed, a task on the Tasks screen is the right tool.
|
||||
*
|
||||
* A stop condition is the scheduler's job, not the model's: the count and the time are read when the loop is created and are
|
||||
* enforced by the scheduler (loop-runner.ts), and the scheduler also ends the loop when an answer says the work is done or stopped.
|
||||
* The model is never left to keep answering "stopped" every minute.
|
||||
*/
|
||||
|
||||
export const LOOP_MIN_MS = 60_000;
|
||||
export const LOOP_MAX_MS = 24 * 3_600_000;
|
||||
export const LOOP_MAX_RUNS = 100;
|
||||
/** This many answers in a row that failed (no model, an error) end the loop, so it does not retry a broken thing all day. */
|
||||
export const LOOP_MAX_FAILURES = 3;
|
||||
|
||||
export type LoopCommand =
|
||||
| { kind: 'start'; everyMs: number; prompt: string }
|
||||
| { kind: 'start'; everyMs: number; prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
| { kind: 'stop' }
|
||||
| { kind: 'status' }
|
||||
| { kind: 'help'; problem: string };
|
||||
@@ -24,7 +33,53 @@ export type LoopCommand =
|
||||
const UNITS: Record<string, number> = { s: 1000, sec: 1000, second: 1000, seconds: 1000, m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000, h: 3_600_000, hr: 3_600_000, hour: 3_600_000, hours: 3_600_000 };
|
||||
|
||||
/** The words shown when a /loop line is not understood. */
|
||||
export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Use /loop stop to stop.';
|
||||
export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add "stop after 3 answers" to end it by itself. Use /loop stop to stop.';
|
||||
|
||||
const NUMBER_WORDS: Record<string, number> = { a: 1, an: 1, one: 1, once: 1, two: 2, twice: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, fifteen: 15, twenty: 20, thirty: 30, fifty: 50 };
|
||||
const NUM = '(\\d{1,4}|[a-z]+)';
|
||||
const THINGS = '(?:answers?|repl(?:y|ies)|responses?|runs?|times?|messages?|rounds?|checks?|iterations?|turns?|updates?|reports?|passes|tries|attempts?|loops?)';
|
||||
const STOP_VERB = '(?:stop|end|quit|finish|halt|cancel|exit)';
|
||||
const number = (word: string): number | null => {
|
||||
const n = /^\d+$/.test(word) ? Number(word) : NUMBER_WORDS[word.toLowerCase()];
|
||||
return Number.isFinite(n) && n >= 1 ? n : null;
|
||||
};
|
||||
/** A clause with its comma or "and" in front and its full stop behind, so removing it leaves a clean sentence. */
|
||||
const clause = (body: string) => new RegExp(`(?:[,;.]\\s*|\\s+(?:and|then)\\s+|\\s+)?(?:please\\s+)?${body}(?=\\s*[,;.!]|\\s+(?:and|then)\\b|\\s*$)[,;.!]?`, 'i');
|
||||
|
||||
interface Limits { prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
|
||||
/** The count, the time and the condition the person put in words, with those words taken out of the message the model gets. */
|
||||
export function readLimits(text: string): Limits {
|
||||
let prompt = text.trim();
|
||||
let maxRuns: number | undefined;
|
||||
let maxMs: number | undefined;
|
||||
let stopWhen: string | undefined;
|
||||
const take = (re: RegExp, use: (m: RegExpMatchArray) => boolean) => {
|
||||
const m = prompt.match(re);
|
||||
if (!m || !use(m)) return;
|
||||
prompt = (prompt.slice(0, m.index) + ' ' + prompt.slice((m.index ?? 0) + m[0].length)).replace(/\s+/g, ' ').replace(/\s+([,.;!])/g, '$1').replace(/^[\s,;.]+|[\s,;]+$/g, '').trim();
|
||||
};
|
||||
const setRuns = (n: number | null) => { if (n === null) return false; maxRuns = Math.min(n, LOOP_MAX_RUNS); return true; };
|
||||
// "stop after 3 answers", "stop the loop after three replies", "stop after the 3rd run", "end after 5 more checks"
|
||||
take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|looping|it|this|all))?\\s+after\\s+(?:the\\s+)?${NUM}(?:st|nd|rd|th)?\\s+(?:more\\s+)?${THINGS}`), m => setRuns(number(m[1])));
|
||||
// "only 3 times", "just 3 answers", "3 times only", "3 times", "for 3 answers", "up to 3 runs", "at most 3 times", "max 3 runs", "run it 3 times"
|
||||
if (maxRuns === undefined) take(clause(`(?:only|just|exactly|up\\s+to|at\\s+most|no\\s+more\\s+than|max(?:imum)?(?:\\s+of)?|for|do\\s+this|do\\s+it|repeat(?:\\s+this|\\s+it)?|run(?:\\s+this|\\s+it)?|send(?:\\s+this|\\s+it)?|ask(?:\\s+me)?)\\s+${NUM}\\s+${THINGS}(?:\\s+only)?`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`${NUM}\\s+${THINGS}\\s+(?:only|in\\s+total|total|at\\s+most)`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`${NUM}\\s+times`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`(?:${STOP_VERB}\\s+)?(?:for\\s+)?(?:the\\s+)?(?:first|next)\\s+${NUM}\\s+${THINGS}`), m => setRuns(number(m[1])));
|
||||
// "for the next 2 hours", "for 30 minutes", "stop after 2 hours", "for an hour"
|
||||
const span = (m: RegExpMatchArray) => {
|
||||
const n = number(m[1]); const unit = UNITS[m[2].toLowerCase()];
|
||||
if (n === null || !unit || unit < 60_000) return false;
|
||||
maxMs = Math.min(n * unit, LOOP_MAX_MS);
|
||||
return true;
|
||||
};
|
||||
take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|it|this))?\\s+after\\s+(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?|[mh])\\b`), span);
|
||||
if (maxMs === undefined) take(clause(`(?:for|over)\\s+(?:the\\s+)?(?:next\\s+)?(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?)\\b`), span);
|
||||
// "stop when the build passes", "stop once it is green", "until the file exists": the model judges it; the scheduler stops on its word
|
||||
take(clause(`(?:${STOP_VERB}\\s+(?:the\\s+loop\\s+)?(?:when|once|as\\s+soon\\s+as|if|the\\s+moment)|until)\\s+([^.;!]{3,160})`), m => { stopWhen = m[1].trim(); return true; });
|
||||
return { prompt, ...(maxRuns !== undefined ? { maxRuns } : {}), ...(maxMs !== undefined ? { maxMs } : {}), ...(stopWhen ? { stopWhen } : {}) };
|
||||
}
|
||||
|
||||
/** null means the text is an ordinary message. */
|
||||
export function parseLoop(text: string): LoopCommand | null {
|
||||
@@ -39,7 +94,9 @@ export function parseLoop(text: string): LoopCommand | null {
|
||||
const everyMs = Math.round(Number(timed[1]) * unit);
|
||||
if (everyMs < LOOP_MIN_MS) return { kind: 'help', problem: 'The shortest time between runs is 1 minute, so the model has time to finish each one.' };
|
||||
if (everyMs > LOOP_MAX_MS) return { kind: 'help', problem: 'The longest time between runs is 24 hours. For longer waits, use a task on the Tasks screen.' };
|
||||
return { kind: 'start', everyMs, prompt: timed[3].trim() };
|
||||
const limits = readLimits(timed[3]);
|
||||
if (!limits.prompt) return { kind: 'help', problem: 'Say what to do each time, not only when to stop.' };
|
||||
return { kind: 'start', everyMs, ...limits };
|
||||
}
|
||||
|
||||
/** "every 10 minutes", "every hour". */
|
||||
@@ -48,3 +105,68 @@ export function loopEvery(ms: number): string {
|
||||
const m = Math.round(ms / 60_000);
|
||||
return m === 1 ? tr('every minute') : tr('every {0} minutes', [m]);
|
||||
}
|
||||
|
||||
/** The line added to a message that carries a stop condition in words, so the model can say it is met (it is not shown in the chat). */
|
||||
export const LOOP_DONE_WORD = 'DONE';
|
||||
export function withStopRule(prompt: string, stopWhen?: string): string {
|
||||
return stopWhen ? `${prompt}\n\n(This repeats on a timer. If this is finished or "${stopWhen}" is true, begin your reply with the word ${LOOP_DONE_WORD} and say so in one sentence. Otherwise just answer.)` : prompt;
|
||||
}
|
||||
|
||||
const plain = (text: string) => text.replace(/[*_`#>~]/g, '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* Does this reply say the work is finished or stopped? The scheduler ends the loop on it.
|
||||
*
|
||||
* Always: the model's own marker ("DONE ...", "LOOP DONE", "LOOP STOPPED") or a reply that is only "stopped" / "done" / "finished".
|
||||
* When the person stated a stop condition (a count, a time or a condition in words), also the short ways a model closes the job:
|
||||
* "Stopped.", "The loop is stopped.", "I have stopped as requested.", "Done, the build passes."
|
||||
*/
|
||||
export function replySaysDone(reply: string, stated: boolean): boolean {
|
||||
const text = plain(reply);
|
||||
if (!text) return false;
|
||||
if (/\bLOOP[ _-]?(?:DONE|STOPPED|STOP|COMPLETE|FINISHED|ENDED)\b/i.test(text)) return true;
|
||||
if (new RegExp(`^${LOOP_DONE_WORD}\\b`).test(text)) return true;
|
||||
const bare = text.replace(/[.!\s]+$/g, '').toLowerCase();
|
||||
if (/^(?:ok(?:ay)?[,. ]+)?(?:stopped|done|finished|complete|completed|all done|ended|stopping)$/.test(bare)) return true;
|
||||
if (!stated || text.length > 280) return false;
|
||||
return /^(?:ok(?:ay)?[,. ]+|sure[,. ]+|yes[,. ]+)?(?:the\s+)?(?:loop\s+(?:is\s+|has\s+)?(?:now\s+)?)?(?:stopped|done|finished|complete(?:d)?|ended|stopping|all done)\b/i.test(text)
|
||||
|| /\b(?:loop|repeat\w*|schedule\w*)\s+(?:is\s+|has\s+been\s+|was\s+)?(?:now\s+)?(?:stopped|finished|complete(?:d)?|ended|over|done)\b/i.test(text)
|
||||
|| /\bi(?:'ve|\s+have|'m|\s+am)?\s+(?:now\s+)?(?:stopped|stopping|done|finished)\b/i.test(text)
|
||||
|| /\b(?:stop|end)\s+condition\s+(?:is\s+|has\s+been\s+)?met\b/i.test(text)
|
||||
|| /\bnothing\s+(?:more|else|left)\s+to\s+(?:do|check|report)\b/i.test(text);
|
||||
}
|
||||
|
||||
export interface LoopLimits { maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
export interface LoopProgress { answers: number; failures: number; startedAt: number }
|
||||
export type LoopStop = 'count' | 'said-done' | 'time' | 'failures' | 'cap';
|
||||
|
||||
/** After an answer: should the loop end, and why? `reply` is the model's text of that run; `failed` is an answer that did not work. */
|
||||
export function judgeAnswer(limits: LoopLimits, progress: LoopProgress, reply: { text: string; failed: boolean }, now: number): LoopStop | null {
|
||||
if (reply.failed) return progress.failures >= LOOP_MAX_FAILURES ? 'failures' : null;
|
||||
const stated = limits.maxRuns !== undefined || limits.maxMs !== undefined || !!limits.stopWhen;
|
||||
if (replySaysDone(reply.text, stated)) return 'said-done';
|
||||
if (limits.maxRuns !== undefined && progress.answers >= limits.maxRuns) return 'count';
|
||||
if (limits.maxMs !== undefined && now - progress.startedAt >= limits.maxMs) return 'time';
|
||||
if (progress.answers >= LOOP_MAX_RUNS) return 'cap';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Plain words for the person when a loop ends by itself. */
|
||||
export function loopEndNote(why: LoopStop, answers: number): string {
|
||||
switch (why) {
|
||||
case 'count': return tr('The loop is done: it ran {0} times, as you asked. Type /loop to start another.', [answers]);
|
||||
case 'said-done': return tr('The loop stopped because the last answer said the work is done. Type /loop to start another.');
|
||||
case 'time': return tr('The loop stopped because the time you set is up. Type /loop to start another.');
|
||||
case 'failures': return tr('The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.', [LOOP_MAX_FAILURES]);
|
||||
default: return tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS]);
|
||||
}
|
||||
}
|
||||
|
||||
/** The part of the "Loop started" note that says how it ends by itself ('' when it only ends when the person stops it). */
|
||||
export function loopLimitNote(limits: LoopLimits): string {
|
||||
const parts: string[] = [];
|
||||
if (limits.maxRuns !== undefined) parts.push(limits.maxRuns === 1 ? tr('It stops by itself after the first answer.') : tr('It stops by itself after {0} answers.', [limits.maxRuns]));
|
||||
if (limits.maxMs !== undefined) parts.push(tr('It stops by itself after {0} minutes.', [Math.max(1, Math.round(limits.maxMs / 60_000))]));
|
||||
if (limits.stopWhen) parts.push(tr('It stops by itself when an answer says the work is done.'));
|
||||
return parts.join(' ');
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { api, ApiError } from './client';
|
||||
export type PlanState = 'proposed' | 'approved' | 'rejected' | 'running' | 'paused' | 'done' | 'stopped';
|
||||
export type StepState = 'pending' | 'running' | 'done' | 'failed' | 'skipped';
|
||||
export interface PlanStep { id: string; text: string; detail?: string; summary?: string; state: StepState }
|
||||
export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[] }
|
||||
export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[]; /** A plain sentence (an interface string) when the app stopped the planning turn early. */ caution?: string }
|
||||
export interface QueuedMessage { id: string; text: string; deliverAt: 'step' | 'end' }
|
||||
|
||||
const PLAN_STATES = ['proposed', 'approved', 'rejected', 'running', 'paused', 'done', 'stopped'];
|
||||
|
||||
+26
-40
@@ -1,7 +1,8 @@
|
||||
import { plainFailure, plainFailureText } from './plain-errors';
|
||||
import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';
|
||||
import { updateAgent } from './agents';
|
||||
import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop';
|
||||
import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop';
|
||||
import { LoopScheduler } from './loop-runner';
|
||||
import { applyStatusFrame, clearStatus } from './live-status';
|
||||
import { applyGoalFrame } from './goal';
|
||||
import { tidyAnswer } from './answer-text';
|
||||
@@ -1445,9 +1446,8 @@ export function exportConversation() {
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- /loop
|
||||
The same message, again and again, while the chat is open. See lib/loop.ts. */
|
||||
interface LoopState { everyMs: number; prompt: string; runs: number; timer: ReturnType<typeof setTimeout> | null }
|
||||
const loops = new Map<string, LoopState>();
|
||||
The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is
|
||||
lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */
|
||||
|
||||
/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */
|
||||
function addNote(sessionId: string, content: string) {
|
||||
@@ -1455,50 +1455,34 @@ function addNote(sessionId: string, content: string) {
|
||||
patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] }));
|
||||
}
|
||||
|
||||
export function loopIsRunning(sessionId: string | null): boolean { return !!sessionId && loops.has(sessionId); }
|
||||
const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local);
|
||||
|
||||
function stopLoop(sessionId: string): boolean {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return false;
|
||||
if (loop.timer) clearTimeout(loop.timer);
|
||||
loops.delete(sessionId);
|
||||
return true;
|
||||
}
|
||||
const loopScheduler = new LoopScheduler({
|
||||
async send(sessionId, { text, shown }) {
|
||||
const before = lastAnswer(sessionId)?.id;
|
||||
await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown });
|
||||
const answer = lastAnswer(sessionId);
|
||||
if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false };
|
||||
return { answered: true, text: answer.content ?? '', failed: !!answer.error };
|
||||
},
|
||||
note: addNote,
|
||||
exists: sessionId => state.sessions.some(s => s.id === sessionId),
|
||||
ready: sessionId => state.activeSession === sessionId && !state.streaming,
|
||||
now: () => Date.now(),
|
||||
setTimer: (fn, ms) => setTimeout(fn, ms),
|
||||
clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
});
|
||||
|
||||
function scheduleLoop(sessionId: string) {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = setTimeout(() => void tickLoop(sessionId), loop.everyMs);
|
||||
}
|
||||
|
||||
async function tickLoop(sessionId: string) {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
if (!state.sessions.some(s => s.id === sessionId)) { stopLoop(sessionId); return; }
|
||||
// Wait for a quiet moment: this chat is open and nothing is being answered.
|
||||
if (state.activeSession !== sessionId || state.streaming) { loop.timer = setTimeout(() => void tickLoop(sessionId), 15_000); return; }
|
||||
loop.runs += 1;
|
||||
if (loop.runs > LOOP_MAX_RUNS) { stopLoop(sessionId); addNote(sessionId, tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS])); return; }
|
||||
await sendMessage(loop.prompt, { fromLoop: true });
|
||||
scheduleLoop(sessionId);
|
||||
}
|
||||
export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); }
|
||||
|
||||
async function runLoopCommand(command: LoopCommand) {
|
||||
const sessionId = state.activeSession ?? newSession().id;
|
||||
const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); };
|
||||
if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; }
|
||||
if (command.kind === 'status') {
|
||||
const loop = loops.get(sessionId);
|
||||
say(loop ? tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) : tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE));
|
||||
return;
|
||||
}
|
||||
if (command.kind === 'stop') { say(stopLoop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }
|
||||
if (loops.has(sessionId)) { say(tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return; }
|
||||
loops.set(sessionId, { everyMs: command.everyMs, prompt: command.prompt, runs: 1, timer: null });
|
||||
addNote(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [command.prompt, loopEvery(command.everyMs)]));
|
||||
if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; }
|
||||
if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }
|
||||
go('chat', sessionId);
|
||||
await sendMessage(command.prompt, { fromLoop: true });
|
||||
scheduleLoop(sessionId);
|
||||
await loopScheduler.start(sessionId, command);
|
||||
}
|
||||
|
||||
/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */
|
||||
@@ -1620,6 +1604,8 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g
|
||||
workspaceId: state.activeWorkspace,
|
||||
},
|
||||
(frame) => {
|
||||
// A line from the app itself carries `key` (the English sentence): shown in the person's language.
|
||||
if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) };
|
||||
const type = frame.type as string;
|
||||
if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; }
|
||||
if (type === 'queued') {
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Die Ergebnisse kommen von DuckDuckGo, oder von Bing, wenn DuckDuckGo ausgelastet ist. Sie brauchen kein Konto und keinen Schlüssel.",
|
||||
"s7321": "Die Websuche ist gerade eingeschränkt, deshalb habe ich die Suche beendet und mit dem weitergemacht, was ich habe. Versuchen Sie es in einer Minute erneut oder fügen Sie unter Einstellungen → Tools → Websuche einen Suchschlüssel hinzu.",
|
||||
"s7322": "Ich habe viel gesucht und aufgehört, damit dieser Chat nicht überläuft. Das ist mein Stand bisher. Sagen Sie mir, was ich als Nächstes nachschlagen soll.",
|
||||
"s7323": "Ich habe den Plan immer wieder umgeschrieben und höre hier mit der letzten Fassung auf. Sagen Sie mir, was ich ändern soll, oder genehmigen Sie ihn.",
|
||||
"s7324": "In diesem Chat ist mir der Platz ausgegangen, deshalb habe ich angehalten. Strata fasst die älteren Nachrichten zusammen, um Platz zu schaffen. Schreiben Sie „weiter“, um fortzufahren, oder starten Sie einen neuen Chat.",
|
||||
"s7325": "Ich habe angehalten, ohne eine Antwort zu schreiben. Senden Sie Ihre Nachricht erneut oder schreiben Sie „weiter“.",
|
||||
"s7301": "Tippen Sie /loop, wie oft und dann, was zu tun ist. Zum Beispiel: /loop 10m prüfe, ob der Build besteht. Mit „stop after 3 answers“ endet es von selbst. Mit /loop stop halten Sie es an.",
|
||||
"s7302": "Sagen Sie, was jedes Mal zu tun ist, nicht nur, wann es endet.",
|
||||
"s7303": "Die Schleife ist fertig: Sie lief {0}-mal, wie gewünscht. Mit /loop starten Sie eine neue.",
|
||||
"s7304": "Die Schleife wurde beendet, weil die letzte Antwort sagte, dass die Arbeit erledigt ist. Mit /loop starten Sie eine neue.",
|
||||
"s7305": "Die Schleife wurde beendet, weil die von Ihnen gesetzte Zeit abgelaufen ist. Mit /loop starten Sie eine neue.",
|
||||
"s7306": "Die Schleife wurde beendet, weil {0} Durchläufe hintereinander nicht funktioniert haben. Prüfen Sie das Modell und starten Sie sie mit /loop neu.",
|
||||
"s7307": "Es endet von selbst nach der ersten Antwort.",
|
||||
"s7308": "Es endet von selbst nach {0} Antworten.",
|
||||
"s7309": "Es endet von selbst nach {0} Minuten.",
|
||||
"s7310": "Es endet von selbst, wenn eine Antwort sagt, dass die Arbeit erledigt ist.",
|
||||
"s7311": "Anthropic-Apps hängen /v1/messages selbst an, deshalb steht am Ende dieser Adresse kein /v1. In Claude Code setzen Sie ANTHROPIC_BASE_URL darauf.",
|
||||
"s0002": "(optional)",
|
||||
"s0003": ", Kontextcache passt nicht in den Speicher",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.",
|
||||
"s7321": "Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.",
|
||||
"s7322": "I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.",
|
||||
"s7323": "I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.",
|
||||
"s7324": "I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.",
|
||||
"s7325": "I stopped without writing an answer. Send your message again, or say “continue”.",
|
||||
"s7301": "Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add \"stop after 3 answers\" to end it by itself. Use /loop stop to stop.",
|
||||
"s7302": "Say what to do each time, not only when to stop.",
|
||||
"s7303": "The loop is done: it ran {0} times, as you asked. Type /loop to start another.",
|
||||
"s7304": "The loop stopped because the last answer said the work is done. Type /loop to start another.",
|
||||
"s7305": "The loop stopped because the time you set is up. Type /loop to start another.",
|
||||
"s7306": "The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.",
|
||||
"s7307": "It stops by itself after the first answer.",
|
||||
"s7308": "It stops by itself after {0} answers.",
|
||||
"s7309": "It stops by itself after {0} minutes.",
|
||||
"s7310": "It stops by itself when an answer says the work is done.",
|
||||
"s7311": "Anthropic apps add /v1/messages themselves, so this address has no /v1 at the end. In Claude Code, set ANTHROPIC_BASE_URL to it.",
|
||||
"s0002": "(optional)",
|
||||
"s0003": ", context cache does not fit",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Los resultados vienen de DuckDuckGo, o de Bing cuando DuckDuckGo está ocupado. No necesitas cuenta ni clave.",
|
||||
"s7321": "La búsqueda web está limitada ahora mismo, así que dejé de buscar y seguí con lo que tengo. Inténtalo de nuevo en un minuto o añade una clave de búsqueda en Ajustes → Herramientas → Búsqueda web.",
|
||||
"s7322": "Busqué mucho y me detuve para que este chat no se llene. Esto es lo que tengo hasta ahora. Dime qué quieres que investigue después.",
|
||||
"s7323": "Seguí reescribiendo el plan, así que me detuve aquí con la última versión. Dime qué cambiar o apruébalo.",
|
||||
"s7324": "Me quedé sin espacio en este chat, así que me detuve. Strata está resumiendo los mensajes antiguos para liberar espacio. Escribe “continúa” para seguir o empieza un chat nuevo.",
|
||||
"s7325": "Me detuve sin escribir una respuesta. Envía tu mensaje de nuevo o escribe “continúa”.",
|
||||
"s7301": "Escribe /loop, cada cuánto y luego qué hacer. Por ejemplo: /loop 10m comprueba si la compilación pasa. Añade \"stop after 3 answers\" para que termine solo. Usa /loop stop para pararlo.",
|
||||
"s7302": "Indica qué hacer cada vez, no solo cuándo parar.",
|
||||
"s7303": "El bucle terminó: se ejecutó {0} veces, como pediste. Escribe /loop para iniciar otro.",
|
||||
"s7304": "El bucle se detuvo porque la última respuesta dijo que el trabajo está terminado. Escribe /loop para iniciar otro.",
|
||||
"s7305": "El bucle se detuvo porque se acabó el tiempo que indicaste. Escribe /loop para iniciar otro.",
|
||||
"s7306": "El bucle se detuvo porque {0} ejecuciones seguidas no funcionaron. Revisa el modelo y escribe /loop para iniciarlo de nuevo.",
|
||||
"s7307": "Se detiene solo después de la primera respuesta.",
|
||||
"s7308": "Se detiene solo después de {0} respuestas.",
|
||||
"s7309": "Se detiene solo después de {0} minutos.",
|
||||
"s7310": "Se detiene solo cuando una respuesta dice que el trabajo está terminado.",
|
||||
"s7311": "Las apps de Anthropic añaden /v1/messages por sí mismas, así que esta dirección no termina en /v1. En Claude Code, pon esta dirección en ANTHROPIC_BASE_URL.",
|
||||
"s0002": "(opcional)",
|
||||
"s0003": ", la caché de contexto no cabe",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "結果は DuckDuckGo から取得し、DuckDuckGo が混み合っているときは Bing から取得します。アカウントもキーも不要です。",
|
||||
"s7321": "ウェブ検索が現在制限されているため、検索をやめて手元の情報で進めました。1分ほど待ってからもう一度試すか、「設定 → ツール → ウェブ検索」で検索キーを追加してください。",
|
||||
"s7322": "検索を重ねたため、このチャットがいっぱいにならないよう止めました。ここまでの内容は以上です。次に調べることを教えてください。",
|
||||
"s7323": "計画を何度も書き直していたため、最新の版でここで止めました。変更したい点を教えるか、承認してください。",
|
||||
"s7324": "このチャットの空きがなくなったため、止めました。Strata が古いメッセージを要約して空きを作っています。続けるには「続けて」と送るか、新しいチャットを始めてください。",
|
||||
"s7325": "回答を書かずに止まってしまいました。もう一度メッセージを送るか、「続けて」と送ってください。",
|
||||
"s7301": "/loop、間隔、やることの順に入力します。例:/loop 10m ビルドが通るか確認する。「stop after 3 answers」を付けると自動で止まります。止めるときは /loop stop。",
|
||||
"s7302": "止める条件だけでなく、毎回やることも書いてください。",
|
||||
"s7303": "ループが終わりました。ご指定どおり {0} 回実行しました。もう一度始めるには /loop と入力します。",
|
||||
"s7304": "直前の回答が作業の完了を伝えたため、ループを止めました。もう一度始めるには /loop と入力します。",
|
||||
"s7305": "設定した時間になったため、ループを止めました。もう一度始めるには /loop と入力します。",
|
||||
"s7306": "{0} 回続けて失敗したため、ループを止めました。モデルを確認してから /loop と入力してやり直してください。",
|
||||
"s7307": "最初の回答のあとで自動的に止まります。",
|
||||
"s7308": "{0} 回答えたあとで自動的に止まります。",
|
||||
"s7309": "{0} 分後に自動的に止まります。",
|
||||
"s7310": "回答が作業の完了を伝えたときに自動的に止まります。",
|
||||
"s7311": "Anthropic 系のアプリは /v1/messages を自分で付け足すため、このアドレスの末尾に /v1 はありません。Claude Code では ANTHROPIC_BASE_URL にこのアドレスを設定します。",
|
||||
"s0002": "(任意)",
|
||||
"s0003": "、コンテキストキャッシュが収まりません",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "결과는 DuckDuckGo에서 가져오며, DuckDuckGo가 바쁠 때는 Bing에서 가져옵니다. 계정이나 키는 필요하지 않습니다.",
|
||||
"s7321": "웹 검색이 지금 제한되어 있어서 검색을 멈추고 가진 정보로 이어갔습니다. 1분 뒤에 다시 시도하거나 설정 → 도구 → 웹 검색에서 검색 키를 추가하세요.",
|
||||
"s7322": "검색을 많이 해서 이 대화가 가득 차지 않도록 멈췄습니다. 지금까지 알아낸 내용입니다. 다음에 무엇을 찾아볼지 알려 주세요.",
|
||||
"s7323": "계획을 계속 다시 쓰고 있어서 최신 버전으로 여기서 멈췄습니다. 바꿀 부분을 알려 주시거나 승인해 주세요.",
|
||||
"s7324": "이 대화의 공간이 다 차서 멈췄습니다. Strata가 오래된 메시지를 요약해 공간을 만들고 있습니다. 계속하려면 “계속해”라고 보내거나 새 대화를 시작하세요.",
|
||||
"s7325": "답변을 쓰지 못하고 멈췄습니다. 메시지를 다시 보내거나 “계속해”라고 보내 주세요.",
|
||||
"s7301": "/loop, 얼마나 자주, 그리고 할 일을 순서대로 입력하세요. 예: /loop 10m 빌드가 통과하는지 확인. \"stop after 3 answers\"를 붙이면 저절로 끝납니다. 멈추려면 /loop stop.",
|
||||
"s7302": "멈출 때만이 아니라 매번 할 일도 적어 주세요.",
|
||||
"s7303": "반복이 끝났습니다. 요청하신 대로 {0}번 실행했습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7304": "마지막 답변에서 작업이 끝났다고 해서 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7305": "설정한 시간이 다 되어 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7306": "{0}번 연속으로 실행이 되지 않아 반복을 멈췄습니다. 모델을 확인한 뒤 /loop를 입력해 다시 시작하세요.",
|
||||
"s7307": "첫 번째 답변 뒤에 저절로 멈춥니다.",
|
||||
"s7308": "답변이 {0}번 나온 뒤에 저절로 멈춥니다.",
|
||||
"s7309": "{0}분 뒤에 저절로 멈춥니다.",
|
||||
"s7310": "답변에서 작업이 끝났다고 하면 저절로 멈춥니다.",
|
||||
"s7311": "Anthropic 앱은 /v1/messages를 스스로 붙이므로 이 주소 끝에는 /v1이 없습니다. Claude Code에서는 ANTHROPIC_BASE_URL에 이 주소를 넣으세요.",
|
||||
"s0002": "(선택 사항)",
|
||||
"s0003": ", 컨텍스트 캐시를 저장할 공간이 부족함",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Os resultados vêm do DuckDuckGo, ou do Bing quando o DuckDuckGo está ocupado. Você não precisa de conta nem de chave.",
|
||||
"s7321": "A pesquisa na web está limitada agora, então parei de pesquisar e segui com o que tenho. Tente de novo em um minuto ou adicione uma chave de pesquisa em Configurações → Ferramentas → Pesquisa na web.",
|
||||
"s7322": "Pesquisei bastante e parei para que este chat não encha. Isto é o que tenho até agora. Diga o que devo investigar em seguida.",
|
||||
"s7323": "Fiquei reescrevendo o plano, então parei aqui com a versão mais recente. Diga o que mudar ou aprove.",
|
||||
"s7324": "Fiquei sem espaço neste chat, então parei. O Strata está resumindo as mensagens antigas para abrir espaço. Diga “continue” para seguir ou comece um chat novo.",
|
||||
"s7325": "Parei sem escrever uma resposta. Envie sua mensagem de novo ou diga “continue”.",
|
||||
"s7301": "Digite /loop, com que frequência e depois o que fazer. Por exemplo: /loop 10m verifique se a compilação passa. Acrescente \"stop after 3 answers\" para terminar sozinho. Use /loop stop para parar.",
|
||||
"s7302": "Diga o que fazer a cada vez, não só quando parar.",
|
||||
"s7303": "O loop terminou: rodou {0} vezes, como você pediu. Digite /loop para iniciar outro.",
|
||||
"s7304": "O loop parou porque a última resposta disse que o trabalho está concluído. Digite /loop para iniciar outro.",
|
||||
"s7305": "O loop parou porque o tempo que você definiu acabou. Digite /loop para iniciar outro.",
|
||||
"s7306": "O loop parou porque {0} execuções seguidas não funcionaram. Verifique o modelo e digite /loop para iniciar de novo.",
|
||||
"s7307": "Ele para sozinho depois da primeira resposta.",
|
||||
"s7308": "Ele para sozinho depois de {0} respostas.",
|
||||
"s7309": "Ele para sozinho depois de {0} minutos.",
|
||||
"s7310": "Ele para sozinho quando uma resposta disser que o trabalho está concluído.",
|
||||
"s7311": "Os apps da Anthropic acrescentam /v1/messages sozinhos, por isso este endereço não termina em /v1. No Claude Code, defina ANTHROPIC_BASE_URL com ele.",
|
||||
"s0002": "(opcional)",
|
||||
"s0003": ", o cache de contexto não cabe",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Результаты берутся из DuckDuckGo, а когда он перегружен, из Bing. Учётная запись и ключ не нужны.",
|
||||
"s7321": "Веб-поиск сейчас ограничен, поэтому я прекратил поиск и продолжил с тем, что есть. Повторите через минуту или добавьте ключ поиска в Настройки → Инструменты → Поиск в интернете.",
|
||||
"s7322": "Я много искал и остановился, чтобы этот чат не переполнился. Вот что у меня есть на данный момент. Скажите, что искать дальше.",
|
||||
"s7323": "Я всё время переписывал план, поэтому остановился на последней версии. Скажите, что изменить, или одобрите его.",
|
||||
"s7324": "В этом чате закончилось место, поэтому я остановился. Strata сжимает старые сообщения, чтобы освободить место. Напишите «продолжай», чтобы идти дальше, или начните новый чат.",
|
||||
"s7325": "Я остановился, не написав ответ. Отправьте сообщение ещё раз или напишите «продолжай».",
|
||||
"s7301": "Введите /loop, как часто и что делать. Например: /loop 10m проверь, проходит ли сборка. Добавьте «stop after 3 answers», чтобы цикл закончился сам. Чтобы остановить, введите /loop stop.",
|
||||
"s7302": "Напишите, что делать каждый раз, а не только когда остановиться.",
|
||||
"s7303": "Цикл завершён: он выполнился {0} раз, как вы просили. Введите /loop, чтобы запустить новый.",
|
||||
"s7304": "Цикл остановлен: в последнем ответе сказано, что работа закончена. Введите /loop, чтобы запустить новый.",
|
||||
"s7305": "Цикл остановлен: заданное вами время вышло. Введите /loop, чтобы запустить новый.",
|
||||
"s7306": "Цикл остановлен: {0} запусков подряд не удались. Проверьте модель и введите /loop, чтобы начать заново.",
|
||||
"s7307": "Он остановится сам после первого ответа.",
|
||||
"s7308": "Он остановится сам после {0} ответов.",
|
||||
"s7309": "Он остановится сам через {0} мин.",
|
||||
"s7310": "Он остановится сам, когда в ответе будет сказано, что работа закончена.",
|
||||
"s7311": "Приложения Anthropic сами добавляют /v1/messages, поэтому в конце этого адреса нет /v1. В Claude Code укажите его в ANTHROPIC_BASE_URL.",
|
||||
"s0002": "(необязательно)",
|
||||
"s0003": ", кеш контекста не помещается",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "结果来自 DuckDuckGo;DuckDuckGo 繁忙时来自 Bing。不需要账号或密钥。",
|
||||
"s7321": "网络搜索目前受到限制,所以我停止了搜索,用已有的信息继续。请一分钟后再试,或在“设置 → 工具 → 网络搜索”中添加搜索密钥。",
|
||||
"s7322": "我搜索了很多次,为了不让这次对话被占满而停下了。以上是目前的结果。请告诉我接下来要查什么。",
|
||||
"s7323": "我一直在重写计划,所以停在这里,保留了最新版本。请告诉我要改什么,或直接批准。",
|
||||
"s7324": "这次对话的空间用完了,所以我停了下来。Strata 正在总结较早的消息来腾出空间。说“继续”即可接着做,或者开始新的对话。",
|
||||
"s7325": "我停了下来,但没有写出回答。请再发一次消息,或说“继续”。",
|
||||
"s7301": "输入 /loop,再写多久一次,然后写要做什么。例如:/loop 10m 检查构建是否通过。加上“stop after 3 answers”可让它自动结束。用 /loop stop 停止。",
|
||||
"s7302": "请写明每次要做什么,而不只是何时停止。",
|
||||
"s7303": "循环已完成:按你的要求运行了 {0} 次。输入 /loop 可再开始一个。",
|
||||
"s7304": "循环已停止,因为上一条回答说工作已完成。输入 /loop 可再开始一个。",
|
||||
"s7305": "循环已停止,因为你设定的时间到了。输入 /loop 可再开始一个。",
|
||||
"s7306": "循环已停止,因为连续 {0} 次运行都没有成功。请检查模型,然后输入 /loop 重新开始。",
|
||||
"s7307": "第一条回答之后会自动停止。",
|
||||
"s7308": "{0} 条回答之后会自动停止。",
|
||||
"s7309": "{0} 分钟后会自动停止。",
|
||||
"s7310": "当某条回答说工作已完成时,会自动停止。",
|
||||
"s7311": "Anthropic 类应用会自己加上 /v1/messages,所以这个地址末尾没有 /v1。在 Claude Code 中,把 ANTHROPIC_BASE_URL 设为这个地址。",
|
||||
"s0002": "(可选)",
|
||||
"s0003": ",上下文缓存无法容纳",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from '../lib/i18n';
|
||||
import { appBaseUrl } from '../lib/connect-urls';
|
||||
import { deviceLabel, instanceLabel } from '../lib/runtime-models';
|
||||
import { nativeRouting, useNative } from '../lib/native';
|
||||
/** Connection facts first. Instructions and request details open only on demand. */
|
||||
@@ -94,7 +95,7 @@ export function ServingScreen() {
|
||||
{tr(requests.length ? <div className="st-tablewrap"><table className="st-table"><thead><tr><th aria-sort={sort === 'at' ? 'descending' : 'none'}><button className="st-btn st-btn--ghost st-btn--sm" onClick={() => setSort('at')}>{tr("Time")}</button></th><th>{tr("Client / endpoint")}</th>{tr(multipleModels ? <th>{tr("Model")}</th> : null)}<th>{tr("Status")}</th><th>{tr("Tokens in / out")}</th><th aria-sort={sort === 'durationMs' ? 'descending' : 'none'}><button className="st-btn st-btn--ghost st-btn--sm" onClick={() => setSort('durationMs')}>{tr("Duration")}</button></th></tr></thead><tbody>{tr(requests.map(r => <tr key={r.id}><td><button className="st-btn st-btn--ghost st-btn--sm" aria-label={tr("View request {0}", [r.id])} onClick={() => setSelectedId(r.id)}>{tr(clockTime(r.at))}</button></td><td>{tr(r.client)}<div className="xs muted">{tr(r.endpoint)}</div></td>{tr(multipleModels ? <td><code className="xs">{r.model}</code></td> : null)}<td>{tr(<span className="request-status" data-state={r.state}>{tr(r.cancelRequested ? r.cancellable ? 'Cancelling…' : 'Cancelled' : r.state.charAt(0).toUpperCase() + r.state.slice(1))}</span>)}</td><td className="num">{tr(tokens(r.tokensIn))} / {tr(tokens(r.tokensOut))}<div className="xs muted">{tr(r.usageSource === 'demo' ? 'Simulated' : r.usageSource === 'reported' ? 'Reported by model' : 'Usage unavailable')}</div></td><td className="num">{tr(r.durationMs ? duration(r.durationMs) : '—')}</td></tr>))}</tbody></table></div> : <Empty icon="link" title={tr(serving.requests.length ? 'No matching requests' : 'No requests yet')} body={serving.requests.length ? 'Try another filter or client name.' : 'Requests appear here when a client or Strata chat uses the API.'} action={tr(serving.requests.length ? <Btn onClick={() => { setQuery(''); setFilter('all'); setModelFilter('all'); }}>{tr("Clear filters")}</Btn> : <Btn onClick={() => setGuide(true)}>{tr("Connect an app")}</Btn>)}/>)}</section>
|
||||
|
||||
{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
</div><Dialog open={guide} title={tr("Connect Strata to an app")} onClose={() => setGuide(false)} headerActions={<div className="protocol-switch"><Seg panelId="api-protocol-panel" value={protocol} ariaLabel={tr("API protocol")} options={[{ value: 'openai', label: 'Chat Completions' }, { value: 'responses', label: 'Responses' }, { value: 'anthropic', label: 'Anthropic' }]} onChange={setProtocol}/></div>} sheet><div className="stack">{tr(multipleModels ? <label className="input-field"><span>{tr("Model for this app")}</span><Select ariaLabel={tr("Connection guide model")} value={loaded?.apiModelId ?? ''} options={modelOptions} disabled={!modelOptions.length} onChange={setGuideModel}/></label> : null)}<ol><li>{tr("In your client, choose a compatible provider.")}</li><li>{tr("Set its base URL to ")}<code>{serving.baseUrl}</code>.</li><li>{tr("Use model ID ")}<code>{loaded?.apiModelId ?? 'from the Models screen after loading'}</code>.</li><li>{tr(serving.access.apiKeySet ? 'Enter your existing API key in the client.' : 'This local API has no key configured.')}</li></ol>{tr(protocol === 'responses' && (!native?.instances.some(i => i.status === 'ready') || native.capabilities.responses === false) ? <p className="small muted">{tr("Responses requires a running native model and a Strata version that supports this API. Update the native installation in Settings \u2192 About if needed.")}</p> : null)}<div id="api-protocol-panel" role="tabpanel" aria-labelledby={`api-protocol-panel-tab-${protocol}`} tabIndex={0}><div className="st-code"><div className="st-code__head"><span>{tr("curl")}</span><IconBtn name="copy" title={tr("Copy request template")} onClick={() => void navigator.clipboard.writeText(code)}/></div><pre>{code}</pre></div><p className="xs muted">{tr("Model list: ")}{tr(serving.baseUrl)}{tr(serving.endpoints.models)}{tr(". Network access depends on the host\u2019s listen address and your firewall.")}</p></div></div></Dialog>
|
||||
</div><Dialog open={guide} title={tr("Connect Strata to an app")} onClose={() => setGuide(false)} headerActions={<div className="protocol-switch"><Seg panelId="api-protocol-panel" value={protocol} ariaLabel={tr("API protocol")} options={[{ value: 'openai', label: 'Chat Completions' }, { value: 'responses', label: 'Responses' }, { value: 'anthropic', label: 'Anthropic' }]} onChange={setProtocol}/></div>} sheet><div className="stack">{tr(multipleModels ? <label className="input-field"><span>{tr("Model for this app")}</span><Select ariaLabel={tr("Connection guide model")} value={loaded?.apiModelId ?? ''} options={modelOptions} disabled={!modelOptions.length} onChange={setGuideModel}/></label> : null)}<ol><li>{tr("In your client, choose a compatible provider.")}</li><li>{tr("Set its base URL to ")}<code>{appBaseUrl(serving.baseUrl, protocol)}</code>.</li><li>{tr("Use model ID ")}<code>{loaded?.apiModelId ?? 'from the Models screen after loading'}</code>.</li><li>{tr(serving.access.apiKeySet ? 'Enter your existing API key in the client.' : 'This local API has no key configured.')}</li></ol>{tr(protocol === 'anthropic' ? <p className="small muted">{tr("Anthropic apps add /v1/messages themselves, so this address has no /v1 at the end. In Claude Code, set ANTHROPIC_BASE_URL to it.")}</p> : null)}{tr(protocol === 'responses' && (!native?.instances.some(i => i.status === 'ready') || native.capabilities.responses === false) ? <p className="small muted">{tr("Responses requires a running native model and a Strata version that supports this API. Update the native installation in Settings \u2192 About if needed.")}</p> : null)}<div id="api-protocol-panel" role="tabpanel" aria-labelledby={`api-protocol-panel-tab-${protocol}`} tabIndex={0}><div className="st-code"><div className="st-code__head"><span>{tr("curl")}</span><IconBtn name="copy" title={tr("Copy request template")} onClick={() => void navigator.clipboard.writeText(code)}/></div><pre>{code}</pre></div><p className="xs muted">{tr("Model list: ")}{tr(serving.baseUrl)}{tr(serving.endpoints.models)}{tr(". Network access depends on the host\u2019s listen address and your firewall.")}</p></div></div></Dialog>
|
||||
<Dialog open={!!selectedId} title={tr("Request details")} onClose={() => setSelectedId(null)} sheet>{tr(selected ? <><dl className="summary-list"><div><dt>{tr("ID")}</dt><dd className="mono">{tr(selected.id)}</dd></div><div><dt>{tr("State")}</dt><dd>{tr(selected.cancelRequested ? selected.cancellable ? 'Cancelling…' : 'Cancelled' : selected.state)}</dd></div><div><dt>{tr("Model")}</dt><dd>{tr(selected.model)}</dd></div><div><dt>{tr("Tokens in / out")}</dt><dd>{tr(tokens(selected.tokensIn))} / {tr(tokens(selected.tokensOut))}</dd></div><div><dt>{tr("Usage source")}</dt><dd>{tr(selected.usageSource === 'demo' ? 'Simulated' : selected.usageSource === 'reported' ? 'Reported by model' : 'Unavailable')}</dd></div><div><dt>{tr("Recorded duration")}</dt><dd>{tr(selected.durationMs ? duration(selected.durationMs) : 'Not yet available')}</dd></div></dl>{tr(selected.error ? <div ref={cancelResult} tabIndex={-1}><ErrorNotice message={selected.error} next={tr("Check the client connection and try the request again.")}/></div> : null)}<p className="small muted">{tr("Prompt content and historical queue position are not retained. This view updates while the request runs.")}</p>{tr(selected.cancellable !== false && ['queued', 'generating'].includes(selected.state) ? <Btn disabled={pending || selected.cancelRequested} onClick={() => { requestedCancel.current = selected.id; void operation(() => cancelRequest(selected.id)); }}>{tr(selected.cancelRequested ? 'Cancelling…' : 'Cancel request')}</Btn> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</> : <p>{tr("This request is no longer retained in the session log.")}</p>)}</Dialog>
|
||||
<Dialog open={sharingOpen} title={tr("Local sharing")} onClose={() => !pending && setSharingOpen(false)} actions={<><Btn disabled={pending} onClick={() => setSharingOpen(false)}>{tr("Close")}</Btn><Btn variant="primary" disabled={pending || !serving.access.apiKeySet} onClick={() => void operation(async () => { await setLocalSharing(!serving.sharing?.active); setSharingOpen(false); })}>{tr(pending ? 'Updating…' : serving.sharing?.active ? 'Stop sharing' : 'Start sharing')}</Btn></>}><div className="form-stack"><span className="dialog-feature-icon"><Icon name="link" size={28}/></span><p>{tr(serving.sharing?.active ? 'Your inference API is available to devices on this network.' : 'Let another device on your network use your loaded models.')}</p><p className="small muted">{tr("Only the inference API is shared. Clients need your API key. Use a trusted local network; this connection uses HTTP.")}</p>{tr(serving.sharing?.active ? <div className="row"><code className="key-url">{serving.sharing.url}</code><IconBtn name="copy" title={tr("Copy local network URL")} onClick={() => void navigator.clipboard.writeText(serving.sharing!.url!)}/></div> : null)}{tr(!serving.access.apiKeySet ? <Btn onClick={() => { generateKey(); setSharingOpen(false); setKeyOpen(true); }}>{tr("Create an API key first")}</Btn> : <p className="small muted"><Icon name="shield" size={16}/>{tr(" API key required")}</p>)}{tr(error ? <ErrorNotice message={error}/> : null)}</div></Dialog>
|
||||
<Dialog open={keyOpen} className="serving-key-dialog" title={tr(serving.access.apiKeySet ? 'Change API key' : 'Create an API key')} onClose={() => {
|
||||
|
||||
@@ -186,12 +186,13 @@ test('search: a human check or a refusal is told in plain words, and a real sear
|
||||
assert.equal(looksBlocked(200, '<div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too</div>'), true);
|
||||
assert.equal(looksBlocked(200, HTML), false);
|
||||
const sleeps = [];
|
||||
const blocked = createDuckDuckGoSearch({ fetch: async () => new Response('<html>captcha anomaly-modal</html>', { status: 200 }), sleep: async ms => { sleeps.push(ms); } });
|
||||
const tick = () => { let t = 1_000_000; return { now: () => t, sleep: async ms => { sleeps.push(ms); t += ms; } }; };
|
||||
const blocked = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('<html>captcha anomaly-modal</html>', { status: 200 }) });
|
||||
await assert.rejects(blocked.search({ query: 'x' }), e => e.message === BLOCKED_MESSAGE && e.code === 'WEB_RATE_LIMITED');
|
||||
const empty = createDuckDuckGoSearch({ fetch: async () => new Response('<html><body>No results.</body></html>', { status: 200 }), sleep: async () => {} });
|
||||
const empty = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('<html><body>No results.</body></html>', { status: 200 }) });
|
||||
assert.deepEqual(await empty.search({ query: 'zzzz' }), { sources: [], truncated: false });
|
||||
const offline = createDuckDuckGoSearch({ fetch: async () => { throw new TypeError('fetch failed'); }, sleep: async () => {} });
|
||||
await assert.rejects(offline.search({ query: 'x' }), /could not reach DuckDuckGo/);
|
||||
const offline = createDuckDuckGoSearch({ ...tick(), fetch: async () => { throw new TypeError('fetch failed'); } });
|
||||
await assert.rejects(offline.search({ query: 'x' }), /could not reach the internet/);
|
||||
});
|
||||
|
||||
test('search: polite by design: one request at a time, spaced out, a minute limit, and the same query is answered from a short cache', async () => {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// The turn guard: a search-heavy /plan that keeps failing searches and rewriting its plan is stopped by the app and ends with a plain message;
|
||||
// a context at 100% never ends silently. The pure counting always runs; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and
|
||||
// run the real search code on a pretend web that refuses (no network).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { TurnGuard, GUARD_LIMITS, GUARD_NOTES, guardNote } from '../server/agent/turn-guard.mjs';
|
||||
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
|
||||
import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
|
||||
import { resolveHarness } from '../server/agent/harness-runtime.mjs';
|
||||
|
||||
const HARNESS = process.env.STRATA_HARNESS_DIR;
|
||||
const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
|
||||
|
||||
const search = (id, state, result = '') => ({ id, name: 'web_search', state, result });
|
||||
const LIMITED = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search. Do not retry this search';
|
||||
|
||||
test('three failed searches in a row stop the turn; a search that worked starts the count again', () => {
|
||||
const g = new TurnGuard({ plan: true, contextMax: 32768 });
|
||||
assert.equal(g.card(search('a', 'running')), null, 'a running search is not counted yet');
|
||||
assert.equal(g.card(search('a', 'error', LIMITED)), null);
|
||||
assert.equal(g.card(search('a', 'error', LIMITED)), null, 'the same card twice is one search');
|
||||
assert.equal(g.card(search('b', 'done', 'three results')), null);
|
||||
assert.equal(g.card(search('c', 'error', LIMITED)), null);
|
||||
assert.equal(g.card(search('d', 'done', LIMITED)), null, 'a refusal that arrives as a normal result still counts');
|
||||
assert.equal(g.card(search('e', 'error', LIMITED)), 'searches-failed');
|
||||
assert.equal(g.card(search('f', 'error', LIMITED)), 'searches-failed', 'once stopped it stays stopped');
|
||||
assert.equal(g.searches, 5);
|
||||
});
|
||||
|
||||
test('other tools are not searches; too many searches in one turn stop it even when they work', () => {
|
||||
const g = new TurnGuard({ plan: true });
|
||||
for (let i = 0; i < 50; i++) assert.equal(g.card({ id: `r${i}`, name: 'read', state: 'done' }), null);
|
||||
for (let i = 0; i < GUARD_LIMITS.searchesPlan - 1; i++) assert.equal(g.card(search(`s${i}`, 'done', 'ok')), null);
|
||||
assert.equal(g.card(search('last', 'done', 'ok')), 'searches');
|
||||
const t = new TurnGuard({ plan: false });
|
||||
for (let i = 0; i < GUARD_LIMITS.searchesTurn - 1; i++) assert.equal(t.card(search(`s${i}`, 'done', 'ok')), null);
|
||||
assert.equal(t.card(search('last', 'done', 'ok')), 'searches');
|
||||
});
|
||||
|
||||
test('a plan turn that writes its numbered plan from 1. again and again is stopped; a single plan is not', () => {
|
||||
const g = new TurnGuard({ plan: true });
|
||||
const plan = '## Plan\n\n1. First\n2. Second\n3. Third\n\n';
|
||||
let reason = null;
|
||||
for (let i = 0; i < GUARD_LIMITS.planRewrites - 1; i++) reason ??= g.text(plan);
|
||||
assert.equal(reason, null, `${GUARD_LIMITS.planRewrites - 1} versions are fine`);
|
||||
assert.equal(g.text(plan), 'rewrites');
|
||||
const one = new TurnGuard({ plan: true });
|
||||
for (const piece of ['Some looking around.\n\n## Plan\n\n', '1. First\n', '2. Second\n', ' 1. a sub point\n', '3. Third\n']) assert.equal(one.text(piece), null, piece);
|
||||
const ordinary = new TurnGuard({ plan: false });
|
||||
for (let i = 0; i < 10; i++) assert.equal(ordinary.text(plan), null, 'only a plan turn counts rewrites');
|
||||
});
|
||||
|
||||
test('a nearly full context stops the turn; a normal one does not', () => {
|
||||
const g = new TurnGuard({ contextMax: 10000 });
|
||||
assert.equal(g.context(5000), null);
|
||||
assert.equal(g.context(9200), null);
|
||||
assert.equal(g.context(9300), 'context');
|
||||
assert.equal(new TurnGuard({ contextMax: 0 }).context(1e9), null, 'an unknown window is never guessed');
|
||||
});
|
||||
|
||||
test('a turn that ends with no words always gets a plain message: out of room, or nothing written', () => {
|
||||
const g = new TurnGuard({ contextMax: 10000 });
|
||||
const done = { kind: 'completed' };
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700 }), 'context');
|
||||
assert.equal(g.silent({ ended: { kind: 'max-tokens' }, wrote: false, contextTokens: 9000 }), 'context');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 3000 }), 'empty');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 3000 }), null, 'cards of finished work are an answer of a kind');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 9700 }), 'context', 'but a full context is never silent');
|
||||
assert.equal(g.silent({ ended: done, wrote: true, contextTokens: 9700 }), null, 'there are words: nothing to add');
|
||||
assert.equal(g.silent({ ended: { kind: 'error', error: { message: 'x' } }, wrote: false, contextTokens: 9700 }), null, 'an error says why by itself');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700, stoppedByPerson: true }), null, 'Stop is the person\'s own');
|
||||
});
|
||||
|
||||
test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all eight languages', () => {
|
||||
const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
|
||||
const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))]));
|
||||
const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0];
|
||||
for (const [reason, text] of Object.entries(GUARD_NOTES)) {
|
||||
const frame = guardNote(reason);
|
||||
assert.equal(frame.type, 'delta'); assert.equal(frame.key, text); assert.equal(frame.own, true);
|
||||
assert.ok(text.length < 220, reason);
|
||||
assert.match(text, /(Try again|Tell me|Say|Send|approve)/i, `${reason} gives a next step`);
|
||||
const id = idOf(text);
|
||||
assert.ok(id, `${reason} is in the English catalog`);
|
||||
for (const l of langs) assert.ok(catalogs[l][id]?.trim(), `${reason} in ${l}`);
|
||||
}
|
||||
assert.match(GUARD_NOTES.context, /ran out of room/);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ with the real Harness
|
||||
|
||||
async function rig(t, options = {}) {
|
||||
const worker = await startScriptedWorker({ chunkDelayMs: 5 });
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-guard-'));
|
||||
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
|
||||
const logs = [];
|
||||
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: options.context ?? 32768, slots: 2 }], connections: () => [],
|
||||
env: process.env, startTimeoutMs: 90_000, searchMock: 'limited', log: l => logs.push(l) });
|
||||
t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
|
||||
return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'manual', onFrame }) };
|
||||
}
|
||||
const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
|
||||
|
||||
test('a search-heavy /plan on a web that keeps refusing stops after 3 failed searches, proposes the plan it has, and says why', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const out = [];
|
||||
await r.bridge.planCommand({ ...r.base('p1', f => out.push(f)), line: 'SCRIPT:searchloop' });
|
||||
const cards = out.filter(f => f.type === 'agent-tool' && f.tool.name === 'web_search' && ['done', 'error'].includes(f.tool.state));
|
||||
assert.ok(cards.length >= 3 && cards.length <= 4, `searches stopped at the limit (${cards.length})`);
|
||||
assert.ok(cards.some(f => /Web search is limited right now/.test(f.tool.result ?? '')), 'the tool said web search is limited');
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0, 'not an error: a normal end');
|
||||
const done = out.find(f => f.type === 'done');
|
||||
assert.ok(done && !done.cancelled, 'the turn ended normally');
|
||||
const plan = out.find(f => f.type === 'plan');
|
||||
assert.equal(plan?.event, 'proposed', 'the plan it had is offered');
|
||||
assert.equal(plan.plan.steps.length, 3);
|
||||
assert.equal(plan.plan.caution, GUARD_NOTES['searches-failed'], 'and the card says why it stopped early');
|
||||
const requests = r.worker.requests.filter(q => q.directive === 'searchloop');
|
||||
assert.ok(requests.length <= 5, `the model was not asked again and again (${requests.length} requests)`);
|
||||
assert.ok(r.logs.some(l => /turn guard: searches-failed/.test(l)));
|
||||
});
|
||||
|
||||
test('an ordinary turn whose searches keep failing ends with the plain sentence as its last words', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const out = [];
|
||||
await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:searchloop' });
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0);
|
||||
assert.ok(out.find(f => f.type === 'done'));
|
||||
const note = out.filter(f => f.type === 'delta' && f.key).at(-1);
|
||||
assert.equal(note?.key, GUARD_NOTES['searches-failed']);
|
||||
assert.match(words(out), /Settings → Tools → Web search/);
|
||||
assert.ok(out.findIndex(f => f.key) < out.findIndex(f => f.type === 'done'), 'the sentence comes before the end of the turn');
|
||||
});
|
||||
|
||||
test('a context at 100% with no answer is never silent: the plain message comes, and the older messages are summarised', { skip }, async (t) => {
|
||||
const r = await rig(t, { context: 32768 });
|
||||
const out = [];
|
||||
await r.bridge.runTurn({ ...r.base('f1', f => out.push(f)), message: 'SCRIPT:bloat 32000' });
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0);
|
||||
assert.ok(out.find(f => f.type === 'done'));
|
||||
assert.equal(out.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.context);
|
||||
assert.match(words(out), /ran out of room/);
|
||||
await new Promise(res => setTimeout(res, 1500));
|
||||
const compacted = r.logs.find(l => /compact after a stopped turn/.test(l));
|
||||
assert.match(compacted ?? '', /compact after a stopped turn: \w+/, `compaction was asked for and the Harness answered (${compacted})`);
|
||||
const out2 = [];
|
||||
await r.bridge.runTurn({ ...r.base('f2', f => out2.push(f)), message: 'SCRIPT:bloat 3000' });
|
||||
assert.equal(out2.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.empty, 'no words at all, plenty of room: still a message');
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Connect an app: Anthropic-style apps get the server root (they add /v1/messages themselves), OpenAI-style apps keep /v1,
|
||||
// and the host accepts /v1/v1/messages as the same request for people who pasted the old address.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import http from 'node:http';
|
||||
import { build } from 'esbuild';
|
||||
import { apiPath } from '../server/api-paths.mjs';
|
||||
import { createLocalShare } from '../server/local-share.mjs';
|
||||
|
||||
const bundled = await build({ entryPoints: ['src/lib/connect-urls.ts'], bundle: true, write: false, format: 'esm', platform: 'node' });
|
||||
const { serverRoot, appBaseUrl } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
test('the Anthropic tab shows the address without /v1, the other tabs keep it', () => {
|
||||
const base = 'http://127.0.0.1:8792/v1';
|
||||
assert.equal(appBaseUrl(base, 'anthropic'), 'http://127.0.0.1:8792');
|
||||
assert.equal(appBaseUrl(base, 'openai'), base);
|
||||
assert.equal(appBaseUrl(base, 'responses'), base);
|
||||
assert.equal(serverRoot('https://abc.trycloudflare.com/v1/'), 'https://abc.trycloudflare.com');
|
||||
assert.equal(serverRoot('http://192.168.1.5:8792'), 'http://192.168.1.5:8792');
|
||||
assert.equal(serverRoot('http://host/api/v1'), 'http://host/api');
|
||||
});
|
||||
|
||||
test('the Connect dialog gives the Anthropic tab the root address and says why in plain words', async () => {
|
||||
const screen = await readFile('src/screens/Serving.tsx', 'utf8');
|
||||
assert.match(screen, /appBaseUrl\(serving\.baseUrl, protocol\)/);
|
||||
assert.match(screen, /ANTHROPIC_BASE_URL/);
|
||||
});
|
||||
|
||||
test('/v1/v1/messages is read as /v1/messages, and nothing else is aliased', () => {
|
||||
assert.equal(apiPath('/v1/v1/messages'), '/v1/messages');
|
||||
assert.equal(apiPath('/v1/v1/messages/'), '/v1/messages');
|
||||
assert.equal(apiPath('/v1/v1/messages/count_tokens'), '/v1/messages/count_tokens');
|
||||
assert.equal(apiPath('/v1/messages'), '/v1/messages');
|
||||
for (const other of ['/v1/v1/chat/completions', '/v1/v1/models', '/v1/v1/responses', '/v1/v1/v1/messages']) assert.equal(apiPath(other), other);
|
||||
});
|
||||
|
||||
test('the shared (key-protected) listener serves /v1/v1/messages as /v1/messages', async () => {
|
||||
const seen = [];
|
||||
const share = createLocalShare({ handle: async (req, res, path) => { seen.push(path); res.writeHead(200); res.end('ok'); }, hasKey: () => true, host: '127.0.0.1', port: 0 });
|
||||
const { url } = await share.start();
|
||||
try {
|
||||
const root = url.replace(/\/v1$/, '');
|
||||
for (const path of ['/v1/messages', '/v1/v1/messages']) {
|
||||
const res = await fetch(root + path, { method: 'POST', body: '{}' });
|
||||
assert.equal(res.status, 200, path);
|
||||
}
|
||||
assert.deepEqual(seen, ['/v1/messages', '/v1/messages']);
|
||||
assert.equal((await fetch(root + '/v1/v1/chat/completions', { method: 'POST', body: '{}' })).status, 404);
|
||||
} finally { await share.stop(); }
|
||||
});
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<!doctype html><html><head><title>strata local llm engine - Search</title></head><body><ol id="b_results">
|
||||
<li class="b_algo" data-id iid=SERP.5344><div class="b_tpcn"><a class="tilk" aria-label="github.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=742e070f460f31c63a7850b7e2884cb8ee651cb333f2ce0f6a64719eb0a6a8a4JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YQ&ntb=1" h="ID=SERP,5129.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">github.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://github.com › Strata</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=742e070f460f31c63a7850b7e2884cb8ee651cb333f2ce0f6a64719eb0a6a8a4JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YQ&ntb=1" h="ID=SERP,5129.2">GitHub - Niko1221/<strong>Strata</strong>: Qwen3.8-Flash-Next on any consumer …</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid=""><span class="news_dt">Sep 24, 2026</span> · Strata makes the model fit by sharing the work across your whole PC. Think of a kitchen: the things you use all the …</p></div><div elementtiming=frp.MiddleOfPage aria-hidden="true" style="pointer-events:none;margin-top:-1px;height:1px;width:1px;font-size:1px;position:absolute;top:0;right:0;" tabindex="-1"> </div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5345><div class="b_tpcn"><a class="tilk" aria-label="github.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=83a355ead65461d915b3a98842374b9104c98dfcc6a84d37dced83063413be2dJmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YS9yZWxlYXNlcw&ntb=1" h="ID=SERP,5147.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=91&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">github.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://github.com › Strata › releases</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=83a355ead65461d915b3a98842374b9104c98dfcc6a84d37dced83063413be2dJmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YS9yZWxlYXNlcw&ntb=1" h="ID=SERP,5147.2">Releases · Niko1221/<strong>Strata</strong> - GitHub</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid=""><span class="news_dt">Sep 29, 2026</span> · CUDA only, a build option: -DSTRATA_MMQ_TAB=ON with STRATA_MMQ_DIRECT=1 and …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5346><div class="b_tpcn"><a class="tilk" aria-label="strataspa.net" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=ec423c99a1c500049b15008a1c77da5392295e31d9001a6d0ce9ae573da58e90JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9zdHJhdGFzcGEubmV0Lw&ntb=1" h="ID=SERP,5164.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">strataspa.net</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://strataspa.net</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=ec423c99a1c500049b15008a1c77da5392295e31d9001a6d0ce9ae573da58e90JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9zdHJhdGFzcGEubmV0Lw&ntb=1" h="ID=SERP,5164.2"><strong>Strata</strong> SpA</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">STRATA è una società di consulenza professionale specializzata nei servizi di supporto giuridico-amministrativo e nella gestione di …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5347><div class="b_tpcn"><a class="tilk" aria-label="strata.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=1dc980cbad2cc71b1b9b3988e8f4602008bc6a4d968de8149c77db25289dcba0JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly93d3cuc3RyYXRhLmNvbS8&ntb=1" h="ID=SERP,5180.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=93&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">strata.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://www.strata.com</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=1dc980cbad2cc71b1b9b3988e8f4602008bc6a4d968de8149c77db25289dcba0JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly93d3cuc3RyYXRhLmNvbS8&ntb=1" h="ID=SERP,5180.2"><strong>Strata</strong> —3D Modeling Software</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">Strata is a 3D/VR/AR Developer and Studio that creates powerful 3D modeling software and solutions. Start a free trial and bring …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5348><div class="b_tpcn"><a class="tilk" aria-label="stratanetwork.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=d3ffcc77c74e73bdb811924b6eda6f244b5876d150d8b08dc90500765cc5a782JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9sb2dpbi5zdHJhdGFuZXR3b3JrLmNvbS9Mb2dpbg&ntb=1" h="ID=SERP,5194.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=94&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">stratanetwork.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://login.stratanetwork.com › Login</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=d3ffcc77c74e73bdb811924b6eda6f244b5876d150d8b08dc90500765cc5a782JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9sb2dpbi5zdHJhdGFuZXR3b3JrLmNvbS9Mb2dpbg&ntb=1" h="ID=SERP,5194.2"><strong>Strata</strong> Login</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">Strata Login ... Strata Login</p></div></li>
|
||||
</ol></body></html>
|
||||
@@ -27,6 +27,8 @@
|
||||
* SCRIPT:planreply a reply ending with a numbered plan of three steps (each step's text carries SCRIPT:goalstep)
|
||||
* SCRIPT:call <tool> <json> one call to any tool with the given JSON arguments
|
||||
* SCRIPT:multi <json> {"calls":[[tool,args],...],"say":"final text"}: all the calls in one reply, then the text once their results are in
|
||||
* SCRIPT:searchloop a model that never stops: every reply rewrites a numbered plan and calls web_search again with a new query
|
||||
* SCRIPT:bloat <prompt tokens> a reply that is only thinking (no answer text), with usage reporting that many prompt tokens (a context at 100%)
|
||||
*
|
||||
* A request whose last message is a tool result is answered with a text that quotes the result.
|
||||
*/
|
||||
@@ -78,9 +80,10 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
||||
const id = `chatcmpl-${requests.length}`;
|
||||
const send = (delta, finish = null, extra = {}) => res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
|
||||
let promptTokens = 100 + messages.length;
|
||||
const finish = (reason, tokens = 10) => {
|
||||
send({}, reason);
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: 100 + messages.length, completion_tokens: tokens, total_tokens: 100 + messages.length + tokens } })}\n\n`);
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: promptTokens, completion_tokens: tokens, total_tokens: promptTokens + tokens } })}\n\n`);
|
||||
res.write('data: [DONE]\n\n'); res.end();
|
||||
};
|
||||
const toolCall = async (name, call) => {
|
||||
@@ -116,6 +119,26 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
|
||||
if (/biggest lever/.test(t) && !answered && last.role !== 'tool') return say(['{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}']);
|
||||
if (/IMPROVEMENT PLAN/.test(t) && !answered && last.role !== 'tool') return say(['## Better path\n\n', '1. Improve the first attempt SCRIPT:goalstep\n', '2. Polish and check SCRIPT:goalstep\n']);
|
||||
}
|
||||
if (directive?.[1] === 'searchloop') {
|
||||
const n = requests.filter(r => r.directive === 'searchloop').length;
|
||||
send({ role: 'assistant', content: `Plan, version ${n}:
|
||||
|
||||
## Search plan
|
||||
|
||||
1. Search for the topic
|
||||
2. Read the best result
|
||||
3. Write the summary
|
||||
|
||||
` });
|
||||
const argsJson = JSON.stringify({ queries: [`topic search number ${n}`] });
|
||||
send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] });
|
||||
return finish('tool_calls', 60);
|
||||
}
|
||||
if (directive?.[1] === 'bloat') {
|
||||
promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100;
|
||||
send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' });
|
||||
return finish('stop', 20);
|
||||
}
|
||||
if (directive?.[1] === 'goalstep') {
|
||||
// A goal round: read the goal, mark it complete, then say so.
|
||||
if (!toolMessages.length) return toolCall('get_goal', {});
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
// /loop stops by itself: a count or a time said in words is read when the loop is created and enforced by the scheduler, and an
|
||||
// answer that says "done" / "stopped" ends it. The model is never left to keep replying "stopped" every minute.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const bundled = await build({ stdin: { contents: "export * from './src/lib/loop'; export * from './src/lib/loop-runner';", resolveDir: process.cwd(), loader: 'ts' }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
|
||||
const { parseLoop, readLimits, replySaysDone, judgeAnswer, withStopRule, LoopScheduler, LOOP_MAX_FAILURES, LOOP_MAX_RUNS } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
const start = text => { const c = parseLoop(text); assert.equal(c?.kind, 'start', text); return c; };
|
||||
|
||||
test('a count in words or digits is read when the loop is created, and left out of the message', () => {
|
||||
for (const [line, runs, prompt] of [
|
||||
['/loop 1m say hi, stop after 3 answers', 3, 'say hi'],
|
||||
['/loop 1m say hi and stop after three replies', 3, 'say hi'],
|
||||
['/loop 5m say hi. Stop the loop after 2 runs.', 2, 'say hi'],
|
||||
['/loop 5m check the build, only 4 times', 4, 'check the build'],
|
||||
['/loop 5m ping 3 times', 3, 'ping'],
|
||||
['/loop every 2 minutes say hi for 5 answers', 5, 'say hi'],
|
||||
['/loop 1m report the time, up to 6 times', 6, 'report the time'],
|
||||
['/loop 1m say hi then stop after 1 answer', 1, 'say hi'],
|
||||
['/loop 1m say hi, end after the 3rd run', 3, 'say hi'],
|
||||
]) {
|
||||
const c = start(line);
|
||||
assert.equal(c.maxRuns, runs, line);
|
||||
assert.equal(c.prompt, prompt, line);
|
||||
}
|
||||
});
|
||||
|
||||
test('a time limit and a stop condition in words are read too', () => {
|
||||
let c = start('/loop 10m check the build for the next 2 hours');
|
||||
assert.equal(c.maxMs, 2 * 3_600_000); assert.equal(c.prompt, 'check the build');
|
||||
c = start('/loop 5m check the build, stop after 30 minutes');
|
||||
assert.equal(c.maxMs, 30 * 60_000); assert.equal(c.prompt, 'check the build');
|
||||
c = start('/loop 2m check the build, stop when it passes');
|
||||
assert.equal(c.stopWhen, 'it passes'); assert.equal(c.prompt, 'check the build'); assert.equal(c.maxRuns, undefined);
|
||||
c = start('/loop 2m look for the file until it exists');
|
||||
assert.equal(c.stopWhen, 'it exists'); assert.equal(c.prompt, 'look for the file');
|
||||
});
|
||||
|
||||
test('an ordinary message is not mistaken for a limit, and a limit with nothing to do is explained', () => {
|
||||
for (const line of ['/loop 10m summarise my inbox notes', '/loop 5m say hi', '/loop 10m check whether the build passes', '/loop 5m run the tests faster than last time']) {
|
||||
const c = start(line);
|
||||
assert.equal(c.maxRuns, undefined, line); assert.equal(c.maxMs, undefined, line); assert.equal(c.stopWhen, undefined, line);
|
||||
assert.equal(c.prompt, line.replace(/^\/loop \S+ /, ''));
|
||||
}
|
||||
assert.equal(parseLoop('/loop 5m stop after 3 answers').kind, 'help');
|
||||
assert.match(parseLoop('/loop 5m stop after 3 answers').problem, /what to do/);
|
||||
assert.equal(readLimits('say hi').prompt, 'say hi');
|
||||
assert.equal(start('/loop 5m say hi, stop after 500 answers').maxRuns, LOOP_MAX_RUNS, 'the count is capped like the loop');
|
||||
});
|
||||
|
||||
test('a reply that says done or stopped ends the loop, a normal reply does not', () => {
|
||||
for (const reply of ['stopped', 'Stopped.', 'Done', 'DONE the build passes', 'LOOP DONE', 'The loop is stopped.']) assert.equal(replySaysDone(reply, true), true, reply);
|
||||
for (const reply of ['stopped', 'Done.', 'DONE: it passes', 'LOOP STOPPED']) assert.equal(replySaysDone(reply, false), true, reply + ' (nothing stated)');
|
||||
for (const reply of ['The build is done and the tests pass: 41 of 41.', 'Hi! Nice to see you.', 'I checked the folder and found nothing new.', '']) assert.equal(replySaysDone(reply, true), false, reply);
|
||||
// Without a stated limit only the bare words count: "Done. The deploy finished" could be a normal answer.
|
||||
assert.equal(replySaysDone('Done. The build passes.', false), false);
|
||||
assert.equal(replySaysDone('Done. The build passes.', true), true);
|
||||
assert.match(withStopRule('check the build', 'it passes'), /begin your reply with the word DONE/);
|
||||
assert.equal(withStopRule('check the build'), 'check the build');
|
||||
});
|
||||
|
||||
test('judgeAnswer: count, time, failures and the said-done rule, in that situation order', () => {
|
||||
const p = (answers, failures = 0, startedAt = 0) => ({ answers, failures, startedAt });
|
||||
assert.equal(judgeAnswer({ maxRuns: 3 }, p(2), { text: 'hi', failed: false }, 0), null);
|
||||
assert.equal(judgeAnswer({ maxRuns: 3 }, p(3), { text: 'hi', failed: false }, 0), 'count');
|
||||
assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 999), null);
|
||||
assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 1000), 'time');
|
||||
assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES - 1), { text: '', failed: true }, 0), null);
|
||||
assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES), { text: '', failed: true }, 0), 'failures');
|
||||
assert.equal(judgeAnswer({}, p(1), { text: 'stopped', failed: false }, 0), 'said-done');
|
||||
assert.equal(judgeAnswer({}, p(LOOP_MAX_RUNS), { text: 'hi', failed: false }, 0), 'cap');
|
||||
});
|
||||
|
||||
/** A scheduler on a fake clock with a scripted model. `reply(n, prompt)` is the model's n-th answer. */
|
||||
function harness(reply, { ready = () => true } = {}) {
|
||||
const sent = []; const notes = []; const timers = new Map(); let t = 0, nextTimer = 1;
|
||||
const host = {
|
||||
async send(_id, message) {
|
||||
sent.push(message);
|
||||
const r = await reply(sent.length, message.text);
|
||||
return r === null ? { answered: false, text: '', failed: false } : typeof r === 'string' ? { answered: true, text: r, failed: false } : { answered: true, ...r };
|
||||
},
|
||||
note: (_id, text) => notes.push(text),
|
||||
exists: () => true,
|
||||
ready,
|
||||
now: () => t,
|
||||
setTimer: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn, at: t + ms }); return id; },
|
||||
clearTimer: id => timers.delete(id),
|
||||
};
|
||||
const scheduler = new LoopScheduler(host);
|
||||
/** Move the clock to the next timer and run it; false when nothing is waiting. */
|
||||
const advance = async () => {
|
||||
const next = [...timers.entries()].sort((a, b) => a[1].at - b[1].at)[0];
|
||||
if (!next) return false;
|
||||
timers.delete(next[0]); t = Math.max(t, next[1].at); next[1].fn();
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
await new Promise(r => setImmediate(r));
|
||||
return true;
|
||||
};
|
||||
const drain = async (max = 400) => { let n = 0; while (n < max && await advance()) n++; return n; };
|
||||
return { scheduler, sent, notes, timers, advance, drain, clock: () => t };
|
||||
}
|
||||
|
||||
test('"stop after 3 answers" stops the scheduler after the third answer and nothing is sent again', async () => {
|
||||
const h = harness(() => 'Hello!');
|
||||
const c = start('/loop 1m say hi, stop after 3 answers');
|
||||
await h.scheduler.start('chat', c);
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 3);
|
||||
assert.equal(h.sent[0].text, 'say hi', 'the model is not told about the stop rule');
|
||||
assert.equal(h.timers.size, 0, 'no timer is left');
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
assert.match(h.notes.at(-1), /The loop is done: it ran 3 times/);
|
||||
assert.equal(h.notes.filter(n => /stops by itself after 3 answers/.test(n)).length, 1, 'the start note says how it ends');
|
||||
});
|
||||
|
||||
test('the owner case: a model that answers "stopped" every minute is cut off at once', async () => {
|
||||
// With a count in the line the scheduler stops at 3 by itself, and a "stopped" answer before that also ends it.
|
||||
const h = harness(n => (n < 2 ? 'Hi!' : 'stopped'));
|
||||
await h.scheduler.start('chat', start('/loop 1m say hi, stop after 3 answers'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 2, 'the "stopped" answer ended the loop');
|
||||
assert.match(h.notes.at(-1), /last answer said the work is done/);
|
||||
// No limit in the line at all: a bare "Stopped." still ends it, instead of 100 minutes of "stopped".
|
||||
const g = harness(n => (n < 3 ? 'Still going.' : 'Stopped.'));
|
||||
await g.scheduler.start('chat', start('/loop 1m keep an eye on the queue'));
|
||||
await g.drain();
|
||||
assert.equal(g.sent.length, 3); assert.equal(g.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a stop condition in words: the model is told how to say it is met, and its DONE ends the loop', async () => {
|
||||
const h = harness(n => (n < 4 ? 'Not yet: 2 tests fail.' : 'DONE all tests pass.'));
|
||||
await h.scheduler.start('chat', start('/loop 2m run the tests, stop when they all pass'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 4);
|
||||
assert.match(h.sent[0].text, /begin your reply with the word DONE/);
|
||||
assert.equal(h.sent[0].shown, 'run the tests', 'the chat shows the message without the rule');
|
||||
});
|
||||
|
||||
test('a time limit ends the loop by the clock, between answers', async () => {
|
||||
const h = harness(() => 'ok');
|
||||
await h.scheduler.start('chat', start('/loop 10m check the queue for the next 35 minutes'));
|
||||
await h.drain();
|
||||
// answers at 0, 10, 20, 30 minutes; the timer at 40 finds the 35 minutes over
|
||||
assert.equal(h.sent.length, 4);
|
||||
assert.match(h.notes.at(-1), /time you set is up/);
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a busy chat waits, and does not use up the count', async () => {
|
||||
let busy = true;
|
||||
const h = harness(() => 'ok', { ready: () => !busy });
|
||||
await h.scheduler.start('chat', start('/loop 1m ping, stop after 2 answers'));
|
||||
assert.equal(h.sent.length, 1);
|
||||
await h.advance(); // 1 minute: busy, retried in 15 s
|
||||
await h.advance(); await h.advance();
|
||||
assert.equal(h.sent.length, 1, 'nothing is sent while the chat is busy');
|
||||
busy = false;
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 2);
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
});
|
||||
|
||||
test('three failed answers in a row end the loop, one failure does not', async () => {
|
||||
const h = harness(n => (n === 2 ? { text: '', failed: true } : 'ok'));
|
||||
await h.scheduler.start('chat', start('/loop 1m check something, stop after 4 answers'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 5, 'the failed run is not an answer, so 4 good answers took 5 sends');
|
||||
const bad = harness(() => ({ text: '', failed: true }));
|
||||
await bad.scheduler.start('chat', start('/loop 1m check something'));
|
||||
await bad.drain();
|
||||
assert.equal(bad.sent.length, LOOP_MAX_FAILURES);
|
||||
assert.match(bad.notes.at(-1), /did not work/);
|
||||
});
|
||||
|
||||
test('/loop stop while an answer is coming means nothing more is sent', async () => {
|
||||
let release;
|
||||
const h = harness(() => new Promise(resolve => { release = () => resolve('ok'); }));
|
||||
const started = h.scheduler.start('chat', start('/loop 1m ping'));
|
||||
await Promise.resolve();
|
||||
assert.equal(h.scheduler.stop('chat'), true);
|
||||
release(); await started;
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
assert.equal(await h.advance(), false);
|
||||
assert.equal(h.sent.length, 1);
|
||||
});
|
||||
|
||||
test('a second /loop in the same chat is refused with one plain sentence; a loop with no limit still runs on', async () => {
|
||||
const h = harness(() => 'ok');
|
||||
await h.scheduler.start('chat', start('/loop 1m ping'));
|
||||
assert.equal(await h.scheduler.start('chat', start('/loop 1m other')), false);
|
||||
assert.match(h.notes.at(-1), /already has a loop/);
|
||||
for (let i = 0; i < 5; i++) await h.advance();
|
||||
assert.equal(h.sent.length, 6, 'no limit: it keeps going until the person stops it');
|
||||
assert.equal(h.scheduler.stop('chat'), true);
|
||||
});
|
||||
@@ -25,6 +25,8 @@ test('HTTP gateway lists all models, routes both protocols exactly, and isolates
|
||||
const list=(await call('/v1/models')).body.data;assert.equal(list.length,2);assert.deepEqual(new Set(list.map(i=>i.id)),new Set([a.body.instance.apiModelId,b.body.instance.apiModelId]));
|
||||
assert.equal((await call('/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409);
|
||||
assert.equal((await call('/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409);
|
||||
assert.equal((await call('/v1/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409,'an Anthropic client given the /v1 base reaches the same route');
|
||||
assert.notEqual((await call('/v1/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409,'only the messages path is aliased');
|
||||
const controllers=[new AbortController(),new AbortController()];
|
||||
const responseA=await fetch(base+'/v1/chat/completions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:a.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[0].signal});
|
||||
const responseB=await fetch(base+'/v1/messages',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:b.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[1].signal});
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// The agent's keyless web search against a MOCKED, rate-limited DuckDuckGo: spaced requests, a session cache, a cooldown that doubles,
|
||||
// Bing as the second source, and one plain sentence (with the place to add a key) when every source refuses.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createDuckDuckGoSearch, BLOCKED_MESSAGE, LIMITED_SENTENCE, UNREACHABLE_MESSAGE } from '../server/web-search-ddg.mjs';
|
||||
import { bingTarget, parseBingResults, bingLooksBlocked } from '../server/web-search-bing.mjs';
|
||||
|
||||
const BING = readFileSync(new URL('./fixtures/bing-results.html', import.meta.url), 'utf8');
|
||||
const DDG = `<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fa">DDG one</a></h2>
|
||||
<a class="result__snippet" href="x">First snippet</a></div>
|
||||
<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fb">DDG two</a></h2></div>`;
|
||||
const ANOMALY = '<html><body><div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too.</div></body></html>';
|
||||
|
||||
/** A fake clock whose sleep moves time, and a fake web: `script(url, n)` decides each answer. */
|
||||
function world(script, { random = () => 0.5 } = {}) {
|
||||
let t = 5_000_000;
|
||||
const calls = [];
|
||||
const fetch = async (url, init) => {
|
||||
const at = t;
|
||||
const call = { url: String(url), method: init?.method ?? 'GET', at, headers: init?.headers ?? {} };
|
||||
calls.push(call);
|
||||
const out = await script(call, calls.length);
|
||||
if (out instanceof Error) throw out;
|
||||
return out;
|
||||
};
|
||||
const search = createDuckDuckGoSearch({ fetch, now: () => t, sleep: async ms => { t += ms; }, random });
|
||||
return { search, calls, advance: ms => { t += ms; }, clock: () => t, hostCalls: host => calls.filter(c => c.url.includes(host)) };
|
||||
}
|
||||
const page = (body, status = 200, headers = {}) => new Response(body, { status, headers });
|
||||
const duck = url => /duckduckgo\.com/.test(url);
|
||||
|
||||
test('requests to one source are spaced 2.5 s or more apart, never in a burst', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
for (const q of ['one', 'two', 'three', 'four']) await w.search.search({ query: q });
|
||||
const at = w.calls.map(c => c.at);
|
||||
assert.equal(at.length, 4);
|
||||
for (let i = 1; i < at.length; i++) assert.ok(at[i] - at[i - 1] >= 2500, `gap ${i}: ${at[i] - at[i - 1]} ms`);
|
||||
});
|
||||
|
||||
test('the request looks like the page\'s own form post: browser headers, Referer, Origin, no hidden tricks', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
await w.search.search({ query: 'strata' });
|
||||
const [c] = w.calls;
|
||||
assert.equal(c.method, 'POST');
|
||||
assert.match(c.headers['user-agent'], /Mozilla\/5\.0 .*Chrome\/\d+/);
|
||||
assert.equal(c.headers.referer, 'https://html.duckduckgo.com/');
|
||||
assert.equal(c.headers.origin, 'https://html.duckduckgo.com');
|
||||
assert.equal(c.headers['sec-fetch-mode'], 'navigate');
|
||||
assert.match(c.headers['accept-language'], /en/);
|
||||
});
|
||||
|
||||
test('the same question is answered from the session cache, even while DuckDuckGo is refusing', async () => {
|
||||
let refuse = false;
|
||||
const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page(BING)));
|
||||
const a = await w.search.search({ query: 'Strata Engine' });
|
||||
assert.equal(a.sources.length, 2);
|
||||
refuse = true;
|
||||
const b = await w.search.search({ query: 'strata engine' });
|
||||
assert.deepEqual(b.sources, a.sources);
|
||||
assert.equal(w.calls.length, 1, 'no second request');
|
||||
w.advance(20 * 60_000);
|
||||
assert.equal((await w.search.search({ query: 'STRATA ENGINE' })).sources.length, 2, 'still cached after 20 minutes');
|
||||
assert.equal(w.calls.length, 1);
|
||||
w.advance(11 * 60_000);
|
||||
await w.search.search({ query: 'strata engine' });
|
||||
assert.ok(w.calls.length > 1, 'asked again after the cache is 30 minutes old');
|
||||
});
|
||||
|
||||
test('DuckDuckGo refuses (HTTP 202): Bing answers, DuckDuckGo is left alone for a minute, and its lite page is not tried', async () => {
|
||||
const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page(BING)));
|
||||
const first = await w.search.search({ query: 'node release notes', maxResults: 3 });
|
||||
assert.equal(first.sources.length, 3);
|
||||
assert.equal(first.sources[0].url, 'https://github.com/Niko1221/Strata');
|
||||
assert.equal(w.hostCalls('html.duckduckgo.com').length, 1);
|
||||
assert.equal(w.hostCalls('lite.duckduckgo.com').length, 0, 'a refusal is not followed by the lite page');
|
||||
assert.equal(w.hostCalls('bing.com').length, 1);
|
||||
// The next question goes straight to Bing: DuckDuckGo is cooling down.
|
||||
await w.search.search({ query: 'another question' });
|
||||
assert.equal(w.hostCalls('duckduckgo.com').length, 1, 'no request to DuckDuckGo during the cooldown');
|
||||
assert.equal(w.hostCalls('bing.com').length, 2);
|
||||
assert.ok(w.search.status().duckduckgo.blockedForMs > 0);
|
||||
// After the cooldown one probe goes out again.
|
||||
w.advance(61_000);
|
||||
await w.search.search({ query: 'a third question' });
|
||||
assert.equal(w.hostCalls('html.duckduckgo.com').length, 2);
|
||||
});
|
||||
|
||||
test('every source refuses: one plain sentence with the place to add a key; later searches make no request at all', async () => {
|
||||
const w = world(call => page(duck(call.url) ? ANOMALY : '<html>captcha</html>', duck(call.url) ? 202 : 429));
|
||||
const error = await w.search.search({ query: 'hello world' }).catch(e => e);
|
||||
assert.equal(error.code, 'WEB_RATE_LIMITED');
|
||||
assert.equal(error.message, BLOCKED_MESSAGE);
|
||||
assert.ok(error.message.startsWith(LIMITED_SENTENCE));
|
||||
assert.match(LIMITED_SENTENCE, /^Web search is limited right now\. Try again in a minute, or add a search key \(Exa, Perplexity or DeepSeek\) in Settings → Tools → Web search\.$/);
|
||||
assert.match(error.message, /Do not retry this search/, 'the model is told to stop');
|
||||
const used = w.calls.length;
|
||||
assert.equal(used, 2, 'one request per source, nothing more');
|
||||
for (const q of ['again', 'and again', 'once more']) {
|
||||
const e = await w.search.search({ query: q }).catch(x => x);
|
||||
assert.equal(e.code, 'WEB_RATE_LIMITED', q);
|
||||
}
|
||||
assert.equal(w.calls.length, used, 'a model that keeps asking does not extend the block');
|
||||
});
|
||||
|
||||
test('the cooldown doubles each time a source refuses again, and a Retry-After header is honoured', async () => {
|
||||
const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page('<html>captcha</html>', 429)));
|
||||
await w.search.search({ query: 'q1' }).catch(() => {});
|
||||
const first = w.search.status().duckduckgo.blockedForMs;
|
||||
assert.ok(first > 55_000 && first <= 60_000, `first cooldown ${first}`);
|
||||
w.advance(61_000);
|
||||
await w.search.search({ query: 'q2' }).catch(() => {});
|
||||
const second = w.search.status().duckduckgo.blockedForMs;
|
||||
assert.ok(second > 115_000 && second <= 120_000, `second cooldown ${second}`);
|
||||
w.advance(121_000);
|
||||
await w.search.search({ query: 'q3' }).catch(() => {});
|
||||
assert.ok(w.search.status().duckduckgo.blockedForMs > 235_000);
|
||||
const r = world(call => (duck(call.url) ? page(ANOMALY, 429, { 'retry-after': '300' }) : page('<html>captcha</html>', 429)));
|
||||
await r.search.search({ query: 'x' }).catch(() => {});
|
||||
assert.ok(r.search.status().duckduckgo.blockedForMs > 295_000, 'Retry-After: 300');
|
||||
});
|
||||
|
||||
test('a recovered source resets the cooldown', async () => {
|
||||
let refuse = true;
|
||||
const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page('<html>captcha</html>', 429)));
|
||||
await w.search.search({ query: 'a' }).catch(() => {});
|
||||
w.advance(61_000);
|
||||
refuse = false;
|
||||
assert.equal((await w.search.search({ query: 'b' })).sources[0].url, 'https://ddg.example/a');
|
||||
assert.equal(w.search.status().duckduckgo.strikes, 0);
|
||||
assert.equal(w.search.status().duckduckgo.blockedForMs, 0);
|
||||
});
|
||||
|
||||
test('a timeout or a server error gets one retry; two in a row moves on to the next source; nothing reachable says so', async () => {
|
||||
let n = 0;
|
||||
const flaky = world(call => (duck(call.url) ? (++n === 1 ? page('oops', 503) : page(DDG)) : page(BING)));
|
||||
assert.equal((await flaky.search.search({ query: 'q' })).sources[0].url, 'https://ddg.example/a');
|
||||
assert.equal(flaky.hostCalls('duckduckgo.com').length, 2);
|
||||
const down = world(call => (duck(call.url) ? new TypeError('fetch failed') : page(BING)));
|
||||
const viaBing = await down.search.search({ query: 'q' });
|
||||
assert.equal(viaBing.sources.length, 5, 'DuckDuckGo unreachable twice: Bing answers');
|
||||
const none = world(() => new TypeError('fetch failed'));
|
||||
const e = await none.search.search({ query: 'q' }).catch(x => x);
|
||||
assert.equal(e.message, UNREACHABLE_MESSAGE);
|
||||
assert.notEqual(e.code, 'WEB_RATE_LIMITED');
|
||||
});
|
||||
|
||||
test('a search with no hits is an answer; a cancelled search is cancelled', async () => {
|
||||
const w = world(() => page('<html><body>No results found.</body></html>'));
|
||||
assert.deepEqual(await w.search.search({ query: 'zzzz qqqq' }), { sources: [], truncated: false });
|
||||
const ctrl = new AbortController(); ctrl.abort();
|
||||
const e = await w.search.search({ query: 'later' }, ctrl.signal).catch(x => x);
|
||||
assert.equal(e.code, 'WEB_ABORTED');
|
||||
});
|
||||
|
||||
test('too many searches in a minute are held back by the app, not sent to the sources', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
let held = null;
|
||||
for (let i = 0; i < 12 && !held; i++) held = await w.search.search({ query: `question ${i}` }).then(() => null, e => e);
|
||||
assert.ok(held, 'the ninth search in a minute is held back');
|
||||
assert.equal(held.code, 'WEB_RATE_LIMITED');
|
||||
assert.ok(w.hostCalls('duckduckgo.com').length <= 8);
|
||||
});
|
||||
|
||||
test('Bing: the real result page is read (redirect links decoded, snippets kept); a challenge page is a refusal; ordinary pages are not', () => {
|
||||
const rows = parseBingResults(BING);
|
||||
assert.equal(rows.length, 5);
|
||||
assert.ok(rows.every(r => /^https:\/\//.test(r.url) && !r.url.includes('bing.com')), 'real addresses, not Bing redirects');
|
||||
assert.equal(rows[1].url, 'https://github.com/Niko1221/Strata/releases');
|
||||
assert.ok(rows[0].snippet.length > 20);
|
||||
assert.equal(bingTarget('https://www.bing.com/ck/a?!&&p=1&u=a1aHR0cHM6Ly9leGFtcGxlLmNvbS9hP3g9MQ&ntb=1'), 'https://example.com/a?x=1');
|
||||
assert.equal(bingTarget('https://www.bing.com/images/search?q=x'), null);
|
||||
assert.equal(bingTarget('https://example.org/direct'), 'https://example.org/direct');
|
||||
assert.equal(bingLooksBlocked(429, ''), true);
|
||||
assert.equal(bingLooksBlocked(200, '<html><form>captcha</form></html>'), true);
|
||||
assert.equal(bingLooksBlocked(200, BING), false);
|
||||
assert.deepEqual(parseBingResults('<html>nothing here</html>'), []);
|
||||
});
|
||||
@@ -240,6 +240,9 @@ def focused_recovery_prompt(tok, ids, generated):
|
||||
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
|
||||
QUEUE_BEAT_S = 10.0 # a request waiting for the single turn sends a keep-alive this often (#1619)
|
||||
KEEPALIVE_S = 10.0 # a held-back tool argument leaves the stream quiet: ping at least this often
|
||||
# Anthropic clients add /v1/messages to their base URL themselves. A base URL that already ends in /v1 (copied from an OpenAI-style
|
||||
# setup) makes them post /v1/v1/messages; these two paths mean the same as the real ones. Nothing else is aliased.
|
||||
V1_V1_ALIASES = {"/v1/v1/messages": "/v1/messages", "/v1/v1/messages/count_tokens": "/v1/messages/count_tokens"}
|
||||
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
|
||||
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
|
||||
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
|
||||
@@ -6116,6 +6119,7 @@ def make_handler(svc: Service):
|
||||
if not self._authorized():
|
||||
return
|
||||
path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true
|
||||
path = V1_V1_ALIASES.get(path, path) # an Anthropic client given ".../v1" as its base posts /v1/v1/messages
|
||||
if path.startswith("/v1/") and self._foreign_page():
|
||||
return
|
||||
if path == "/settings":
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""serve/test_anthropic_base_url.py - an Anthropic client reaches the server by the root address, and by the "/v1" one too.
|
||||
|
||||
The Anthropic SDKs (and Claude Code) add /v1/messages to the base URL themselves. The app used to show the OpenAI-style base
|
||||
(.../v1) in its Anthropic tab, so those clients posted /v1/v1/messages and got a 404. The address is now shown without /v1, and
|
||||
the server accepts /v1/v1/messages (and /v1/v1/messages/count_tokens) as the same request, for people who already pasted the old one.
|
||||
|
||||
Uses the real `anthropic` Python client against the mock-engine server (no network, no key). Skipped when the package is missing.
|
||||
|
||||
python -m unittest serve.test_anthropic_base_url -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from serve.frontend import ChatTemplate # noqa: E402
|
||||
from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
try:
|
||||
import anthropic
|
||||
except ImportError: # pragma: no cover
|
||||
anthropic = None
|
||||
|
||||
|
||||
REPLY = "<think>\nhm\n</think>\n\nhello from the mock"
|
||||
|
||||
|
||||
class AnthropicBase(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
tok = ByteTokenizer()
|
||||
cls.engine = MockEngine(tok, REPLY, max_context=4096)
|
||||
cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
|
||||
cls.httpd = serve(cls.svc, port=0)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.root = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def raw(self, path, body):
|
||||
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
|
||||
try:
|
||||
c.request("POST", path, body=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
|
||||
r = c.getresponse()
|
||||
return r.status, json.loads(r.read() or b"{}")
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_with_the_root_address_works(self):
|
||||
client = anthropic.Anthropic(base_url=self.root, api_key="not-needed", max_retries=0)
|
||||
msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
|
||||
self.assertEqual(msg.type, "message")
|
||||
self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_with_the_old_v1_address_works_through_the_alias(self):
|
||||
client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
|
||||
msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
|
||||
self.assertEqual(msg.type, "message")
|
||||
self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_streaming_through_the_alias(self):
|
||||
client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
|
||||
with client.messages.stream(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}]) as stream:
|
||||
text = "".join(stream.text_stream)
|
||||
self.assertIn("hello", text)
|
||||
|
||||
def test_count_tokens_alias(self):
|
||||
body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}]}
|
||||
code, real = self.raw("/v1/messages/count_tokens", body)
|
||||
code2, aliased = self.raw("/v1/v1/messages/count_tokens", body)
|
||||
self.assertEqual((code, code2), (200, 200))
|
||||
self.assertEqual(real, aliased)
|
||||
|
||||
def test_only_the_two_messages_paths_are_aliased(self):
|
||||
body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
|
||||
for path in ("/v1/v1/chat/completions", "/v1/v1/responses", "/v1/v1/v1/messages", "/v1/v2/messages"):
|
||||
code, _ = self.raw(path, body)
|
||||
self.assertEqual(code, 404, path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -494,6 +494,8 @@ def run_launch(a: argparse.Namespace) -> int:
|
||||
label = ("This computer" if "127.0.0.1" in u else "Cloudflare" if "trycloudflare" in u else
|
||||
"Tailscale" if ("ts.net" in u or u.split("//")[1].startswith("100.")) else "Network")
|
||||
_say(f" {label:<14} {u}/v1")
|
||||
if result.urls:
|
||||
_say(f" {'Anthropic apps':<14} {result.urls[0]} (Claude Code: ANTHROPIC_BASE_URL, no /v1 at the end)")
|
||||
if result.key:
|
||||
from strata_cli.launch import access
|
||||
_say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key --preset \"{s.name}\")")
|
||||
|
||||
@@ -164,7 +164,8 @@ def _limits_codex(t: Target) -> list[str]:
|
||||
|
||||
|
||||
def _limits_claude(t: Target) -> list[str]:
|
||||
out = ["Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the served context (%d here) and CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096: without them Claude Code "
|
||||
out = ["ANTHROPIC_BASE_URL is the server address %s without /v1: Claude Code adds /v1/messages itself (with /v1 in it the requests go to /v1/v1/messages)." % t.url,
|
||||
"Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the served context (%d here) and CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096: without them Claude Code "
|
||||
"assumes a 100K window and never compacts, or compacts on every turn." % t.context,
|
||||
"No Anthropic login or credential is used; the token is only checked by your own server.",
|
||||
"The notice [claude-code:unrecognized_model] on stderr is harmless."]
|
||||
@@ -249,8 +250,14 @@ def closest_name(name: str) -> str | None:
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ rendering
|
||||
|
||||
def server_root(url: str) -> str:
|
||||
"""The server root: the address without a trailing /v1 (people paste the OpenAI-style base). Anthropic apps add /v1/messages themselves."""
|
||||
root = url.strip().rstrip("/")
|
||||
return root[:-3].rstrip("/") if root.lower().endswith("/v1") else root
|
||||
|
||||
|
||||
def target(url: str, key: str | None, model: str, context: int | None = None) -> Target:
|
||||
return Target(url=url.rstrip("/"), key=key or PLACEHOLDER_KEY, model=model or "strata", context=int(context or 32768))
|
||||
return Target(url=server_root(url), key=key or PLACEHOLDER_KEY, model=model or "strata", context=int(context or 32768))
|
||||
|
||||
|
||||
def render(h: Harness, t: Target) -> dict:
|
||||
|
||||
@@ -223,6 +223,7 @@ class LaunchMonitor(MonitorApp):
|
||||
t.append(f" URL {self.info['url']}/v1 model {self.info.get('model') or 'strata'} key {shown} ")
|
||||
t.append("(k hide)" if self.show_key else "(k show)", style=MUTE)
|
||||
t.append("\n")
|
||||
t.append(f" Claude Code and other Anthropic apps use {self.info['url']} (no /v1)\n", style=MUTE)
|
||||
for u in self.info.get("urls", [])[1:]:
|
||||
t.append(f" also reachable at {u}/v1\n", style=MUTE)
|
||||
t.append("\n " + "App".ljust(20) + "Works with".ljust(22) + "Status\n", style="bold")
|
||||
|
||||
@@ -804,6 +804,20 @@ class ConnectCommand(unittest.TestCase):
|
||||
self.assertIn("ANTHROPIC_AUTH_TOKEN", out)
|
||||
self.assertNotIn("/v1", out.split("ANTHROPIC_BASE_URL")[1].splitlines()[0]) # the Anthropic client adds /v1 itself
|
||||
|
||||
def test_a_pasted_v1_address_is_cut_back_to_the_server_root(self):
|
||||
"""The Anthropic client adds /v1/messages itself, so ANTHROPIC_BASE_URL must never end in /v1 (that gave /v1/v1/messages, a 404);
|
||||
the OpenAI-style apps get exactly one /v1."""
|
||||
code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080/v1/", "--key", "sk-x1234567890abc", "--show-key", "--output", "json"])
|
||||
data = json.loads(out)
|
||||
self.assertEqual(data["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:8080")
|
||||
self.assertIn('"ANTHROPIC_BASE_URL": "http://127.0.0.1:8080"', data["files"][0]["text"])
|
||||
code, out, _ = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8080/v1", "--output", "json"])
|
||||
text = json.loads(out)["files"][0]["text"]
|
||||
self.assertIn("http://127.0.0.1:8080/v1", text)
|
||||
self.assertNotIn("/v1/v1", text)
|
||||
code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080"])
|
||||
self.assertIn("without /v1", out)
|
||||
|
||||
def test_write_keeps_a_backup_and_merges(self):
|
||||
target = Path(os.environ["HOME"]) / ".config" / "opencode" / "opencode.json"
|
||||
target.parent.mkdir(parents=True)
|
||||
|
||||
Reference in new issue
Block a user