factory 0.1.52: "harness" reads runtime in a client's prompt and tool descriptions, and Claude Code's tool search goes as tools declared in full

@DennisYan4 on X (2026-11-19): Claude Code, Pi and Codex through Factory
answer 400 content_policy_rejected since 11-17, and Claude Code's deferred
tools fail. Factory's policy check refuses a client describing itself as an
agent harness; Pi passed once its prompt said "runtime" for "harness". The
word alone changes (names like harness_key and the user's own turns are
left), in system prompts, system messages, the update-config entry and tool
descriptions. Claude Code's tool search (defer_loading, the
DeferredToolPlaceholder tool, tool_reference/tool_definition/tool_addition
blocks) is turned into what its own no-tool-search path sends: every loaded
tool declared in full, a reference answered as text so the pairing stays.

Run: bun test packages/factory on mote (226 tests, green); the 5 new
harness tests are red on the previous index.mjs. The root `bun test` was
left to CI (a one-hour run on mote).
This commit is contained in:
yetone
2026-11-19 22:26:35 +08:00
parent 9c5d284cf0
commit 21c3f948f1
8 changed files with 305 additions and 28 deletions
+1 -1
View File
@@ -66,7 +66,7 @@ test("Claude Code's request made chat completions goes without the phrases Facto
// user turn by the translation: reworded, its facts kept
expect(m[2].content.startsWith("# Runtime context\nThe session environment is: \n - Primary working directory: /Users/me/proj\n")).toBe(true)
expect(m[2].content).toContain("\n\nCurrent model: glm-5.3-flash.\n\n")
expect(m[2].content).toContain("the harness executes these, not the assistant, so memory")
expect(m[2].content).toContain("the runtime executes these, not the assistant, so memory")
expect(m.length).toBe(JSON.parse(CHAT).messages.length)
expect(b.model).toBe("glm-5.3-flash")
})
+136
View File
@@ -0,0 +1,136 @@
// @DennisYan4 on X (2026-11-19): since 11-17 Claude Code, Pi and Codex
// through Factory got 400 content_policy_rejected. Tool names weren't the
// cause; Pi passed once its system prompt said "runtime" for "harness", and
// Claude Code also hit Factory's refusal of tool search (defer_loading and
// the DeferredToolPlaceholder tool).
//
// The phrases are the clients' own bytes: Pi 1.5.2's
// dist/core/system-prompt.js, Codex 0.165.0's prompt, Claude Code 2.1.327's.
// testdata/claude-code-2.1.327-toolsearch.json is a real Claude Code
// 2.1.327 request with ENABLE_TOOL_SEARCH, captured from a sandbox HOME
// after a ToolSearch call (paths changed to /home/u, the first user turn
// cut to its words).
import { afterEach, expect, test } from "bun:test"
import { readFileSync } from "node:fs"
import { FactoryAuthPlugin, _internal } from "./index.mjs"
const { harnessText, undeferredTools, toolDescriptions } = _internal
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const API = "https://api.factory.ai"
const messages = API + "/api/llm/a/v1/messages"
const responses = API + "/api/llm/o/v1/responses"
const chat = API + "/api/llm/o/v1/chat/completions"
const CAPTURE = readFileSync(new URL("./testdata/claude-code-2.1.327-toolsearch.json", import.meta.url), "utf8")
const PI = "You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code."
const PI_DOCS = "Pi documentation (read only when the user asks about the harness itself, its SDK, extensions, themes, skills, or TUI):\n- Before implementing harness changes, read the relevant docs and examples in full"
const CODEX = "- Receive user prompts and other context provided by the harness, such as files in the workspace."
const CLAUDE_TOOL = "The exception is external work the harness cannot track (a CI run, a deploy, a remote queue)"
async function loaded() {
const sent = []
globalThis.fetch = async (url, init = {}) => {
const u = new URL(String(url))
if (u.pathname === "/api/cli/whoami") return new Response(JSON.stringify({ userId: "user_k", orgId: "fac_K", email: "k@example.com", region: "" }))
sent.push({ url: String(url), headers: new Headers(init.headers), body: init.body })
return new Response('{"id":"ok"}')
}
let saved = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3_600_000, accountId: "d@example.com", activeOrganizationId: "fac_D", region: "" }
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async ({ body }) => (saved = body) } } })
const l = await hooks.auth.loader(async () => saved)
return async (url, body) => {
const res = await l.fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) })
expect(res.status).toBe(200)
return JSON.parse(sent.at(-1).body)
}
}
test("the clients' harness wording reads runtime", () => {
expect(harnessText(PI)).toBe("You are a coding assistant running inside pi, a coding agent runtime. Help users inspect files, run commands, and modify code.")
expect(harnessText(PI_DOCS)).toBe(PI_DOCS.replaceAll("harness", "runtime"))
expect(harnessText(CODEX)).toBe("- Receive user prompts and other context provided by the runtime, such as files in the workspace.")
expect(harnessText("# Harness\n - Text you output")).toBe("# Runtime\n - Text you output")
expect(harnessText("test harnesses")).toBe("test runtimes")
expect(harnessText("harness-tracked work")).toBe("runtime-tracked work")
})
test("a name that holds harness stays as written", () => {
for (const s of ["harness_key", "src/harness.rs", "harness.rs", "harness-ci", "./harness", "test_harness", "MyHarness", "harnessed", "path/to/harness"]) expect(harnessText(s)).toBe(s)
})
test("Pi's, Codex's and Claude Code's prompts go to Factory without harness", async () => {
const send = await loaded()
const a = await send(messages, { model: "claude-opus-4-5-20251101", system: [{ type: "text", text: PI + "\n\n" + PI_DOCS }], messages: [{ role: "user", content: "a harness for my tests" }], max_tokens: 10 })
expect(JSON.stringify(a.system)).not.toContain("harness")
// the user's own words go as written
expect(a.messages[0].content).toBe("a harness for my tests")
const r = await send(responses, { model: "gpt-5.1-codex", instructions: CODEX, input: [{ role: "user", content: [{ type: "input_text", text: "fix the harness" }] }] })
expect(r.instructions).not.toContain("harness")
expect(r.instructions).toContain("provided by the runtime")
expect(JSON.stringify(r.input)).toContain("fix the harness")
const c = await send(chat, { model: "glm-5.3-flash", messages: [{ role: "system", content: PI }, { role: "user", content: "hi" }], tools: [{ type: "function", function: { name: "Wake", description: CLAUDE_TOOL, parameters: { type: "object", properties: { why: { type: "string", description: "what the harness waits on" } } } } }] })
expect(JSON.stringify(c)).not.toContain("harness")
})
test("a tool's description and its parameters' read runtime, its values as written", () => {
const tools = [{ name: "Wake", description: CLAUDE_TOOL, input_schema: { type: "object", properties: { mode: { type: "string", enum: ["harness"], default: "harness", description: "the harness's mode" } } } }]
expect(toolDescriptions(tools)).toBe(true)
expect(tools[0].description).toContain("the runtime cannot track")
expect(tools[0].input_schema.properties.mode.description).toBe("the runtime's mode")
expect(tools[0].input_schema.properties.mode.enum).toEqual(["harness"])
expect(tools[0].input_schema.properties.mode.default).toBe("harness")
expect(toolDescriptions([{ name: "x", description: "plain" }])).toBe(false)
})
test("Claude Code's tool search reaches Factory as tools declared in full", async () => {
const before = JSON.parse(CAPTURE)
// the capture is what Claude Code sends: the placeholder, a deferred
// WebFetch, and ToolSearch's answer as a tool_reference
expect(before.tools.find((t) => t.name === "DeferredToolPlaceholder")?.defer_loading).toBe(true)
expect(before.tools.find((t) => t.name === "WebFetch")?.defer_loading).toBe(true)
expect(CAPTURE).toContain('{"type": "tool_reference", "tool_name": "WebFetch"}')
expect(CAPTURE).toContain("harness")
const send = await loaded()
const b = await send(messages, CAPTURE)
const out = JSON.stringify(b)
expect(out).not.toContain("defer_loading")
expect(out).not.toContain("DeferredToolPlaceholder")
expect(out).not.toContain("tool_reference")
expect(out).not.toContain("harness")
// (Claude Code's own tool names go out as droid's, renamed in place)
expect(b.tools.length).toBe(before.tools.length - 1)
const web = b.tools.find((t) => t.name === "WebFetch")
expect(web.input_schema).toEqual(before.tools.find((t) => t.name === "WebFetch").input_schema)
// ToolSearch's call and its answer stay paired, the answer as text
const use = b.messages[1].content.find((c) => c.type === "tool_use")
const result = b.messages[2].content.find((c) => c.type === "tool_result")
expect(result.tool_use_id).toBe(use.id)
expect(result.content).toEqual([{ type: "text", text: "Tool WebFetch is loaded and can be called now." }])
expect(b.messages.length).toBe(before.messages.length)
})
test("tool definitions Claude Code carries in messages join the tools", () => {
const request = {
tools: [{ name: "Read", input_schema: { type: "object" } }, { name: "DeferredToolPlaceholder", description: "Reserved placeholder that keeps deferred tool loading active; never call this tool.", input_schema: { type: "object", properties: {} }, defer_loading: true }],
messages: [
{ role: "user", content: [{ type: "text", text: "hi" }] },
{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "ToolSearch", input: { query: "grep" } }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: [{ type: "tool_definition", definition: { name: "Grep", description: "search", input_schema: { type: "object" }, defer_loading: true } }] }] },
{ role: "user", content: [{ type: "tool_addition", tool: { type: "tool_definition", definition: { name: "Glob", input_schema: { type: "object" }, defer_loading: true } } }, { type: "tool_removal", tool_name: "Old" }] },
{ role: "user", content: [{ type: "text", text: "go" }] },
],
}
expect(undeferredTools(request)).toBe(true)
expect(request.tools).toEqual([{ name: "Read", input_schema: { type: "object" } }, { name: "Grep", description: "search", input_schema: { type: "object" } }, { name: "Glob", input_schema: { type: "object" } }])
expect(request.messages.length).toBe(4)
expect(request.messages[2].content[0].content).toEqual([{ type: "text", text: "Tool Grep is loaded and can be called now." }])
expect(request.messages[3].content).toEqual([{ type: "text", text: "go" }])
// a request without tool search is left as it was
const plain = { tools: [{ name: "Read" }], messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }] }
expect(undeferredTools(plain)).toBe(false)
})
+144 -6
View File
@@ -698,14 +698,16 @@ function droidBody(path, body) {
delete m.top_p
}
const opened = promptOpenings(m.input)
const described = toolDescriptions(m.tools)
const ins = promptText(v ?? "")
if (!ins.startsWith(DROID_LINE)) m.instructions = ins.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + ins
else if (ins !== v || opened) m.instructions = ins
else if (ins !== v || opened || described) m.instructions = ins
else if (!sampled) return body
} else if (path.endsWith("/chat/completions")) {
if (!Array.isArray(m.messages)) return body
const opened = promptOpenings(m.messages, true)
if (!droidChat(m.messages) && !opened) return body
const described = toolDescriptions(m.tools)
if (!droidChat(m.messages) && !opened && !described) return body
} else return body
return JSON.stringify(m)
}
@@ -1158,10 +1160,61 @@ function configSkillText(text) {
if (!text.includes(CONFIG_SKILL_REFUSED)) return text
return text
.split("\n")
.map((line) => (CONFIG_SKILL_ENTRY.test(line) ? line.replace(CONFIG_SKILL_REFUSED, CONFIG_SKILL_SAFE) : line))
.map((line) => (CONFIG_SKILL_ENTRY.test(line) ? harnessText(line.replace(CONFIG_SKILL_REFUSED, CONFIG_SKILL_SAFE)) : line))
.join("\n")
}
// Factory's policy check reads a client's description of itself as an
// agent harness as an attempt to run its models from another agent
// framework, and refuses the request (@DennisYan4 on X, 2026-11-19: Claude
// Code, Pi and Codex 400 content_policy_rejected since 11-17; Pi passed
// once its prompt said "runtime" for "harness"). Claude Code ("the Claude
// Code harness", "injected by the harness"), Pi 1.5 ("a coding agent
// harness") and Codex ("context provided by the harness") all describe
// themselves so. In a client's own prompt text and its tools' descriptions
// the word, and only the word, says "runtime"; a name built from it
// (harness_key, harness.rs, harness-ci) and the user's own words in their
// turns and tool output are left as they are. A compound with a past
// participle ("harness-tracked work", Claude Code's ScheduleWakeup) is
// prose, and changes.
const HARNESS_WORD = /(?<![\w/\\.-])(h|H)arness(es)?(?![\w/\\-]|\.\w)|(?<![\w/\\.-])(h|H)arness(?=-[a-z]+ed\b)/g
function harnessText(text) {
if (typeof text !== "string" || !/harness/i.test(text)) return text
return text.replace(HARNESS_WORD, (_, h, plural, h2) => ((h ?? h2) === "H" ? "R" : "r") + "untime" + (plural ? "s" : ""))
}
// toolDescriptions puts each tool's description, and its schema's
// descriptions, through harnessText: Anthropic's tools[].description and
// input_schema, chat's tools[].function, Responses' tools[]. False when
// nothing changed.
function schemaDescriptions(schema, depth = 0) {
if (!schema || typeof schema !== "object" || depth > 32) return false
let changed = false
for (const [key, value] of Object.entries(schema)) {
if (key === "description" && typeof value === "string") {
const adapted = harnessText(value)
if (adapted !== value) (schema[key] = adapted), (changed = true)
} else if (value && typeof value === "object" && !["default", "const", "examples", "enum"].includes(key)) {
if (schemaDescriptions(value, depth + 1)) changed = true
}
}
return changed
}
function toolDescriptions(tools) {
if (!Array.isArray(tools)) return false
let changed = false
for (const tool of tools) {
if (!tool || typeof tool !== "object") continue
const fn = tool.function && typeof tool.function === "object" ? tool.function : tool
if (typeof fn.description === "string") {
const adapted = harnessText(fn.description)
if (adapted !== fn.description) (fn.description = adapted), (changed = true)
}
for (const key of ["input_schema", "parameters"]) if (schemaDescriptions(fn[key])) changed = true
}
return changed
}
// Claude Code also sends the skill list alone as a system message: the
// entries only, no header, no <system-reminder> wrapper and no token tail,
// as text blocks or a string (#72). Only a system message that is such a
@@ -1641,12 +1694,12 @@ function zcodeRuntimeContext(text) {
// promptText adapts a system prompt's text.
function promptText(text) {
return configSkillText(clientOpening(systemModelLine(claudeIdentity(zcodeRuntimeContext(text)))))
return harnessText(configSkillText(clientOpening(systemModelLine(claudeIdentity(zcodeRuntimeContext(text))))))
}
// systemMessageText adapts a system message's text after the prompt.
function systemMessageText(text) {
return bareSkills(clientOpening(systemContext(zcodeRuntimeContext(text))))
return harnessText(bareSkills(clientOpening(systemContext(zcodeRuntimeContext(text)))))
}
// userBlockText adapts one text block of a user turn.
@@ -1682,6 +1735,89 @@ function userText(text) {
return text.replace(REMINDER_BLOCK, (block) => userBlockText(block))
}
// Claude Code's tool search (ENABLE_TOOL_SEARCH, on behind a gateway since
// 2.1.304) declares a tool ToolSearch loaded with defer_loading, keeps it
// on with a never-called DeferredToolPlaceholder tool, and answers a
// ToolSearch call with tool_reference blocks (newer builds: the tool's
// tool_definition, and tool_addition/tool_removal blocks in a message).
// Factory's Messages route has no tool search and turns the request away
// (@DennisYan4 on X, 2026-11-19), and droid never sends any of it. Claude
// Code's own answer for a backend without tool search (its Foundry path)
// is what goes here: the placeholder off, defer_loading off every tool, so
// each loaded tool is declared in full. A definition carried in a message
// joins the tools; a tool_result's reference, or definition, goes as the
// text magpie's gateway tells a model on a translated route, so the
// tool_use/tool_result pairing stays; tool_addition and tool_removal
// blocks go, and a message they leave empty with them. False when the
// request has none of it.
const DEFERRED_PLACEHOLDER = "DeferredToolPlaceholder"
const toolLoadedText = (name) => "Tool " + name + " is loaded and can be called now."
function undeferredTools(request) {
let changed = false
const tools = Array.isArray(request.tools) ? request.tools : null
const have = new Set()
if (tools) {
for (let i = tools.length - 1; i >= 0; i--) {
const tool = tools[i]
if (tool?.name === DEFERRED_PLACEHOLDER) {
tools.splice(i, 1)
changed = true
continue
}
if (tool && typeof tool === "object" && "defer_loading" in tool) {
delete tool.defer_loading
changed = true
}
if (typeof tool?.name === "string") have.add(tool.name)
}
}
const added = []
const declare = (def) => {
if (!def || typeof def !== "object" || Array.isArray(def) || typeof def.name !== "string" || !def.name || have.has(def.name) || def.name === DEFERRED_PLACEHOLDER) return
const { defer_loading: _, ...rest } = def
added.push(rest)
have.add(def.name)
}
const messages = request.messages
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i]
if (!Array.isArray(message?.content)) continue
const kept = []
let touched = false
for (const block of message.content) {
const type = block?.type
if (type === "tool_addition" || type === "tool_removal" || type === "tool_reference") {
if (type === "tool_addition" && block.tool?.type === "tool_definition") declare(block.tool.definition)
touched = true
continue
}
if (type === "tool_result" && Array.isArray(block.content) && block.content.some((c) => c?.type === "tool_reference" || c?.type === "tool_definition")) {
const content = []
for (const c of block.content) {
if (c?.type === "tool_definition") declare(c.definition)
const name = c?.type === "tool_reference" ? c.tool_name : c?.type === "tool_definition" ? c.definition?.name : undefined
if (c?.type !== "tool_reference" && c?.type !== "tool_definition") content.push(c)
else if (typeof name === "string" && name) content.push({ type: "text", text: toolLoadedText(name) })
}
block.content = content.length ? content : [{ type: "text", text: "No tools were loaded." }]
touched = true
}
kept.push(block)
}
if (!touched) continue
changed = true
if (kept.length === 0) messages.splice(i, 1)
else message.content = kept
}
if (added.length) {
added.reverse()
if (tools) tools.push(...added)
else request.tools = added
changed = true
}
return changed
}
function anthropicBody(body) {
let request
try {
@@ -1819,6 +1955,8 @@ function anthropicBody(body) {
delete request.context_management
changed = true
}
if (undeferredTools(request)) changed = true
if (toolDescriptions(request.tools)) changed = true
return changed ? JSON.stringify(request) : body
}
@@ -2317,4 +2455,4 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
}
// for tests
export const _internal = { renamedInFull, CONVERSATION, sessionId, STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, GEMINI_ORDER, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
export const _internal = { harnessText, undeferredTools, toolDescriptions, renamedInFull, CONVERSATION, sessionId, STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, GEMINI_ORDER, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-factory-auth",
"version": "0.1.51",
"version": "0.1.52",
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
"type": "module",
"main": "./opencode.mjs",
+3 -1
View File
@@ -88,7 +88,9 @@ test("pi's opening quoted in user, assistant or system text is escaped, a fragme
] })
// Factory refuses the sentence in user and assistant text too, so the last
// pass escapes it everywhere; only the complete sentence changes.
expect(b.system[1].text).toBe("Quote: " + ESCAPED_OPENING)
// a system prompt's "harness" reads runtime first, so its quote no longer
// holds the refused sentence
expect(b.system[1].text).toBe("Quote: " + OPENING.replace("harness", "runtime"))
expect(b.messages[0].content[0].text).toBe("Why does pi say: " + ESCAPED_OPENING)
expect(b.messages[1].content[0].text).toBe("Why does pi say: " + ESCAPED_OPENING)
expect(b.messages[2].content[0].text).toBe(partial)
+16 -16
View File
@@ -224,7 +224,7 @@ test("adapts the built-in configuration skill self-reference on inference and co
for (const endpoint of [url, url + "/count_tokens"]) {
await l.fetch(endpoint, { method: "POST", body })
const sent = JSON.parse(seen.at(-1).body)
expect(sent.messages[0].content).toEqual([{ ...block, text: skillReminder.replace("not Claude", "not the assistant") }, { type: "text", text: "Reply OK." }])
expect(sent.messages[0].content).toEqual([{ ...block, text: skillReminder.replace("not Claude", "not the assistant").replaceAll("harness", "runtime") }, { type: "text", text: "Reply OK." }])
expect(sent.tools).toEqual(tools)
expect(sent.system).toBe(droid)
}
@@ -267,7 +267,7 @@ test("adapts Claude 5 system-role runtime context without changing its role or i
.replace("You are powered by the model", "Current model:")
.replace("The exact model ID is", "Model ID:")
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:")
.replace("not Claude", "not the assistant")
.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")
const request = {
system: [{ type: "text", text: droid }],
messages: [{ role: "user", content: [{ type: "text", text: "Reply OK.", cache_control: { type: "ephemeral" } }] }, { role: "system", content: context }],
@@ -504,7 +504,7 @@ test("adapts runtime context after a SessionStart hook's output, as a system mes
.replace("You have been invoked in the following environment:", "The session environment is:")
.replace("You are powered by the model named", "Current model name:")
.replace("The exact model ID is", "Model ID:")
.replace("not Claude", "not the assistant")
.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")
const text = hook + "\n" + context
for (const message of [{ role: "system", content: text }, { role: "user", content: [{ type: "text", text: "Reply OK." }, { type: "text", text }] }]) {
await l.fetch(url, { method: "POST", body: JSON.stringify({ system: droid, messages: [message] }) })
@@ -529,7 +529,7 @@ test("adapts runtime metadata after subagent hooks and deferred tools without ch
.replace("You have been invoked in the following environment:", "The session environment is:")
.replace("You are powered by the model named", "Current model name:")
.replace("The exact model ID is", "Model ID:")
.replace("not Claude", "not the assistant")
.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")
const prefixes = [tools,
"SubagentStart hook additional context: " + hookBody,
"SubagentStart hook additional context: " + hookBody + "\n\n" + tools,
@@ -542,7 +542,7 @@ test("adapts runtime metadata after subagent hooks and deferred tools without ch
for (const content of [text, [{ type: "text", text, cache_control: { type: "ephemeral" } }]]) {
const request = { system: droid, messages: [{ role: "user", content: "OK" }, { role, content }] }
await l.fetch(endpoint, { method: "POST", body: JSON.stringify(request) })
const expected = prefix + "\n\n" + adapted
const expected = (role === "system" ? prefix.replaceAll("harness", "runtime") : prefix) + "\n\n" + adapted
const output = typeof content === "string" ? expected : [{ ...content[0], text: expected }]
expect(JSON.parse(seen.at(-1).body)).toEqual({ ...request, messages: [request.messages[0], { role, content: output }] })
const once = seen.at(-1).body
@@ -1263,10 +1263,10 @@ test("adapts token-prefixed runtime bundles as system turns or folded user text"
"Previously read file: /tmp/large.ts. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it.",
"# Runtime context\nThe session environment is: \n - Primary working directory: /tmp/project\n - Platform: darwin",
"Current model name: Sonnet 5.5. Model ID: group/auto-claude-sonnet-5-5. Model knowledge cutoff: June 2026.",
skillHeader, skills.replace("not Claude", "not the assistant"), hook].join("\n\n")
skillHeader, skills.replace("not Claude", "not the assistant").replaceAll("harness", "runtime"), hook].join("\n\n")
const skillOnly = [token, skillHeader, skills, "## Exited Auto Mode", token].join("\n\n")
for (const endpoint of [url, url + "/count_tokens"]) {
for (const [input, output] of [[text, expected], [skillOnly, skillOnly.replace("not Claude", "not the assistant")]]) {
for (const [input, output] of [[text, expected], [skillOnly, skillOnly.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")]]) {
for (const content of [input, [{ type: "text", text: input, cache_control: { type: "ephemeral" } }]]) {
for (const role of ["system", "user"]) {
const request = { system: droid, messages: [{ role, content }, { role: "user", content: "OK" }] }
@@ -1285,7 +1285,7 @@ test("adapts token-prefixed runtime bundles as system turns or folded user text"
test("adapts standalone skill updates with trailing token context", async () => {
const { l, seen } = await loaded()
const text = "The following skills are available for use with the Skill tool:\n\n- custom: Keep not Claude in this user's description.\n" + configSkill + "\n\n## Exited Auto Mode\n\nResume using the dedicated tools for file reads, searches, and edits.\n\n<total_tokens>15000000 tokens left</total_tokens>"
const expected = text.replace(configSkill, configSkill.replace("not Claude", "not the assistant"))
const expected = text.replace(configSkill, configSkill.replace("not Claude", "not the assistant").replaceAll("harness", "runtime"))
for (const endpoint of [url, url + "/count_tokens"]) {
for (const role of ["system", "user"]) {
for (const content of [text, [{ type: "text", text, cache_control: { type: "ephemeral" } }]]) {
@@ -1309,7 +1309,7 @@ test("preserves quoted and incomplete standalone skill updates and tool output",
for (const content of [value, [{ type: "text", text: value }]]) {
const body = JSON.stringify({ system: droid, messages: [{ role, content }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
expect(seen.at(-1).body).toBe(role === "system" ? body.replaceAll("harness", "runtime") : body)
}
}
}
@@ -1336,7 +1336,7 @@ test("adapts complete skill paragraphs after runtime notifications and repeated
const modes = ["## Exited Auto Mode", "Resume using dedicated tools.", token, "While bypass permissions mode is active:", "Keep these tool-choice instructions verbatim.", token].join("\n\n")
for (const notice of notices) {
const text = [notice, header, list, modes, header, list, token].join("\n\n")
const expected = text.replaceAll(configSkill, configSkill.replace("not Claude", "not the assistant"))
const expected = text.replaceAll(configSkill, configSkill.replace("not Claude", "not the assistant").replaceAll("harness", "runtime"))
for (const endpoint of [url, url + "/count_tokens"]) {
for (const role of ["system", "user"]) {
for (const content of [text, [{ type: "text", text, cache_control: { type: "ephemeral" } }]]) {
@@ -1374,7 +1374,7 @@ test("preserves incomplete skill paragraphs, quoted headers and hook-owned listi
for (const content of [value, [{ type: "text", text: value }]]) {
const body = JSON.stringify({ system: droid, messages: [{ role, content }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
expect(seen.at(-1).body).toBe(role === "system" ? body.replaceAll("harness", "runtime") : body)
}
}
}
@@ -1525,7 +1525,7 @@ const bareConfigSkill = '- update-config: Use this skill to configure the Claude
test("a skill list sent alone as a system message has the update-config line adapted (#72)", async () => {
const { l, seen } = await loaded()
const fixed = bareConfigSkill.replace("not Claude", "not the assistant")
const fixed = bareConfigSkill.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")
const list = "- custom: Keep not Claude in this user's description.\n" + bareConfigSkill + "\n- other: Another skill."
for (const [text, want] of [[bareConfigSkill, fixed], [list, list.replace(bareConfigSkill, fixed)]]) {
for (const content of [[{ type: "text", text }], text]) {
@@ -1545,7 +1545,7 @@ test("a skill list sent alone as a system message has the update-config line ada
test("recognizes the update-config entry with or without the invoking slash (#72)", async () => {
const { l, seen } = await loaded()
const slashed = bareConfigSkill.replace("- update-config:", "- /update-config:")
const want = (text) => text.replace("not Claude", "not the assistant")
const want = (text) => text.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")
for (const text of [bareConfigSkill, slashed]) {
const request = { model: "factory/claude-opus-5-5", max_tokens: 32, messages: [{ role: "user", content: "hi" }, { role: "system", content: text }] }
await l.fetch(url, { method: "POST", body: JSON.stringify(request) })
@@ -1562,7 +1562,7 @@ test("only a system message that is a skill list is adapted (#72)", async () =>
]) {
const request = { model: "factory/claude-opus-5-5", max_tokens: 32, messages: [{ role: "user", content: "hi" }, { role, content: text }] }
await l.fetch(url, { method: "POST", body: JSON.stringify(request) })
expect(JSON.parse(seen.at(-1).body).messages[1].content).toBe(text)
expect(JSON.parse(seen.at(-1).body).messages[1].content).toBe(role === "system" ? text.replaceAll("harness", "runtime") : text)
}
})
@@ -1628,7 +1628,7 @@ test("adapts the update-config self-reference in a system prompt's configuration
const sent = JSON.parse(seen.at(-1).body)
expect(sent.system).toEqual([
{ type: "text", text: droid },
{ ...system[1], text: text.replace(configDescription, configDescription.replace("not Claude", "not the assistant")) },
{ ...system[1], text: text.replace(configDescription, configDescription.replace("not Claude", "not the assistant").replaceAll("harness", "runtime")) },
])
expect(JSON.stringify(sent)).not.toContain("not Claude, so")
}
@@ -1651,7 +1651,7 @@ test("leaves the refused sentence in a system prompt outside the update-config e
]
const body = JSON.stringify({ model: "factory/claude-haiku-5-5", max_tokens: 32, system, messages: [{ role: "user", content: "hi" }] })
await l.fetch(url, { method: "POST", body })
expect(seen[0].body).toBe(body)
expect(seen[0].body).toBe(body.replaceAll("harness", "runtime"))
})
test("adapting a system prompt's configuration section is idempotent", async () => {
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -244,9 +244,9 @@ test("dsh's request on chat completions goes out with no refused name, its promp
const names = sent.tools.map((t) => t.function.name)
expect(names.some((n) => seenRefused(n))).toBe(false)
expect(names.filter((n, i) => n !== dshNames[i])).toEqual(["Execute", "Edit", "Glob", "Grep", "Read", "WebSearch", "Create"])
// only the names change: descriptions, schemas and dsh's own text stay
// only the names change: descriptions (their "harness" read runtime), schemas and dsh's own text stay
expect(sent.tools.map((t) => t.function.parameters)).toEqual(dsh.tools.map((t) => t.function.parameters))
expect(sent.tools.map((t) => t.function.description)).toEqual(dsh.tools.map((t) => t.function.description))
expect(sent.tools.map((t) => t.function.description)).toEqual(dsh.tools.map((t) => _internal.harnessText(t.function.description)))
expect(sent.messages.slice(-2)).toEqual(dsh.messages.slice(-2))
const text = await res.text()
const calls = text.split("\n").filter((x) => x.startsWith("data: {")).map((x) => JSON.parse(x.slice(6)))
@@ -311,7 +311,7 @@ test("a request refused for a name not listed yet goes once more with every tool
expect(second).toContain("Execute")
expect(second.filter((n) => dshNames.includes(n))).toEqual([])
// only names change
expect(JSON.parse(seen[1].body).tools.map((t) => t.function.description)).toEqual(dsh.tools.map((t) => t.function.description))
expect(JSON.parse(seen[1].body).tools.map((t) => t.function.description)).toEqual(dsh.tools.map((t) => _internal.harnessText(t.function.description)))
expect((await res.json()).choices[0].message.tool_calls[0].function.name).toBe("create_goal")
// the next turn of the same tool set is renamed in full at once
const again = await l.fetch(C, { method: "POST", body })