@useavalon/caelence-agent 0.1.0 → 0.1.1-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -150
- package/package.json +3 -3
- package/src/cli/main.ts +1 -1
- package/src/core/strands.ts +10 -1
- package/src/desktop/bridge.test.ts +32 -1
- package/src/desktop/bridge.ts +11 -5
- package/src/desktop/uploads.test.ts +57 -0
- package/src/desktop/uploads.ts +92 -0
- package/src/runtime.test.ts +24 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 useAvalon
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,101 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Caelence agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A coding agent you run in a project. Terminal UI, local tools, and skills you can add or remove.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[`@useavalon/caelence-agent`](https://www.npmjs.com/package/@useavalon/caelence-agent) on npm. Needs [Bun](https://bun.sh) 1.2 or later.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
bun add github:useAvalon/caelence-agent
|
|
9
|
-
# or, once published to npm
|
|
10
|
-
bun add @useavalon/caelence-agent
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Global CLI:
|
|
7
|
+
## Get started
|
|
14
8
|
|
|
15
9
|
```bash
|
|
16
|
-
bun add -g
|
|
10
|
+
bun add -g @useavalon/caelence-agent
|
|
11
|
+
cd your-project
|
|
12
|
+
bunx harness init
|
|
13
|
+
export OPENROUTER_API_KEY=…
|
|
17
14
|
harness
|
|
18
15
|
```
|
|
19
16
|
|
|
20
|
-
|
|
17
|
+
`bunx harness init` writes `harness.config.ts`, `AGENTS.md`, a sample skill, and a smoke eval. `harness` opens the terminal UI. `caelence-agent` is the same CLI.
|
|
18
|
+
|
|
19
|
+
As a library:
|
|
21
20
|
|
|
22
21
|
```bash
|
|
23
|
-
|
|
22
|
+
bun add @useavalon/caelence-agent
|
|
24
23
|
```
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
```bash
|
|
29
|
-
export OPENROUTER_API_KEY=…
|
|
30
|
-
harness
|
|
25
|
+
```ts
|
|
26
|
+
import { createHarness } from "@useavalon/caelence-agent";
|
|
31
27
|
```
|
|
32
28
|
|
|
33
|
-
|
|
34
|
-
|------|------|
|
|
35
|
-
| `harness.config.ts` | Name, model, mode, skill/eval dirs, theme, exec approval, hooks |
|
|
36
|
-
| `skills/**/SKILL.md` | Cursor-style skills (YAML `name` / `description`) |
|
|
37
|
-
| `evals/<suite>/eval.ts` | Eval suites (`export default { name, steps }`) |
|
|
38
|
-
| `AGENTS.md` | Project instructions (stacked under user instructions) |
|
|
39
|
-
| `~/.harness/AGENTS.md` | User instructions for every host (`HARNESS_USER_INSTRUCTIONS` overrides the path) |
|
|
40
|
-
| `.harness/sessions/` | JSON session logs (gitignored) |
|
|
29
|
+
## Config
|
|
41
30
|
|
|
42
31
|
```ts
|
|
43
32
|
import type { HarnessConfig } from "@useavalon/caelence-agent";
|
|
44
33
|
|
|
45
34
|
export default {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
// hooks: [{ event: "pre_tool", command: "jq -e .toolName" }],
|
|
35
|
+
name: "my-agent",
|
|
36
|
+
model: "~x-ai/grok-latest",
|
|
37
|
+
instructionsFile: "AGENTS.md",
|
|
38
|
+
skillsDir: "skills",
|
|
39
|
+
evalsDir: "evals",
|
|
40
|
+
theme: "caelence",
|
|
41
|
+
mode: "agent",
|
|
42
|
+
tools: { exec: { approval: "prompt" } },
|
|
43
|
+
mcp: [],
|
|
56
44
|
} satisfies HarnessConfig;
|
|
57
45
|
```
|
|
58
46
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
CAELENCE_AGENT_VERSION= # optional; defaults to the package version
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
When both Langfuse keys are set, each chat turn, tool call, subagent, and eval run is traced. With keys unset the observer is a no-op. Set `observability: { enabled: false }` in `harness.config.ts` to force it off.
|
|
71
|
-
|
|
72
|
-
Set `LANGFUSE_QUALITY_EVAL=1` to run the optional LLM-as-judge after a turn (OpenRouter spend). Leave it unset otherwise.
|
|
73
|
-
|
|
74
|
-
```
|
|
75
|
-
harness experiment Run the local website-generation-regression dataset
|
|
76
|
-
```
|
|
47
|
+
| File | Role |
|
|
48
|
+
|------|------|
|
|
49
|
+
| `harness.config.ts` | Name, model, mode, skills, evals, theme, approvals |
|
|
50
|
+
| `skills/**/SKILL.md` | Skills the agent can load |
|
|
51
|
+
| `evals/<suite>/eval.ts` | Eval suites |
|
|
52
|
+
| `AGENTS.md` | Project instructions |
|
|
53
|
+
| `~/.harness/AGENTS.md` | User instructions for every project |
|
|
54
|
+
| `.harness/sessions/` | Session logs (gitignored) |
|
|
77
55
|
|
|
78
|
-
|
|
56
|
+
Set `OPENROUTER_API_KEY`. Optional: `OPENROUTER_MODEL`, `OPENROUTER_BASE_URL`. `/settings key <token>` stores a key in `~/.harness`.
|
|
79
57
|
|
|
80
58
|
## Commands
|
|
81
59
|
|
|
82
60
|
```
|
|
83
|
-
harness
|
|
61
|
+
harness Terminal UI
|
|
84
62
|
harness --mode plan Start in plan mode
|
|
85
|
-
harness chat -m "…" One-shot turn
|
|
86
|
-
harness eval [name] Run or list
|
|
87
|
-
harness experiment Run the local regression dataset
|
|
63
|
+
harness chat -m "…" One-shot turn
|
|
64
|
+
harness eval [name] Run or list evals
|
|
88
65
|
harness init Scaffold host files
|
|
89
|
-
harness desktop
|
|
66
|
+
harness desktop Optional OS window (needs Rust)
|
|
90
67
|
```
|
|
91
68
|
|
|
92
|
-
Type `/` in the terminal for
|
|
93
|
-
|
|
94
|
-
`/resume` and `/model` open a list. Tab or arrows move, enter chooses. Sessions show their title, not the file id. `/resume billing` also matches a title; `/resume 2` is the second row.
|
|
95
|
-
|
|
96
|
-
`/skills` prints names only.
|
|
97
|
-
|
|
98
|
-
Install from [skills.sh](https://skills.sh) into the harness user store (`~/.harness/skills`, or `HARNESS_USER_SKILLS`). That does not write into the repo:
|
|
69
|
+
Type `/` in the terminal for the command list. Tab completes.
|
|
99
70
|
|
|
100
71
|
```
|
|
101
72
|
/skill find
|
|
@@ -105,97 +76,30 @@ Install from [skills.sh](https://skills.sh) into the harness user store (`~/.har
|
|
|
105
76
|
/skill remove copywriting
|
|
106
77
|
```
|
|
107
78
|
|
|
108
|
-
`/skill add --project <name>` writes into the
|
|
79
|
+
`/skill add --project <name>` writes into the project `skillsDir`. `/skill new <name> <what it should do>` authors a project skill from a brief.
|
|
109
80
|
|
|
110
|
-
Skills
|
|
81
|
+
## Skills
|
|
111
82
|
|
|
112
|
-
`
|
|
83
|
+
Skills are `SKILL.md` files with YAML `name` and `description`. Load order: user store (`~/.harness/skills`), then the project (project wins). The package catalog is off until you add a skill. The agent also reads `skills/`, `.cursor/skills`, and `.claude/skills` when those folders exist.
|
|
113
84
|
|
|
114
|
-
|
|
85
|
+
| Add | What you get |
|
|
86
|
+
|------|------|
|
|
87
|
+
| `copywriting` | Writing pipeline: RMBC, Harry Dry, copy-editor |
|
|
88
|
+
| `copy-editor` | That step only |
|
|
89
|
+
| `impeccable` | Visual QA against the host `design.md` |
|
|
115
90
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
```
|
|
119
|
-
harness
|
|
120
|
-
harness desktop
|
|
121
|
-
```
|
|
91
|
+
Invented metrics and testimonials stay illegal.
|
|
122
92
|
|
|
123
93
|
## Modes
|
|
124
94
|
|
|
125
95
|
| Mode | Tools |
|
|
126
|
-
|
|
127
|
-
| `ask` |
|
|
128
|
-
| `plan` |
|
|
129
|
-
| `agent` |
|
|
130
|
-
|
|
131
|
-
Switch in the TUI with `/mode ask`, `/mode plan`, or `/mode agent`. The header shows the current mode. Token counts (and USD only when the provider reports a cost) appear there after a turn.
|
|
132
|
-
|
|
133
|
-
## Git
|
|
134
|
-
|
|
135
|
-
Prefer `git_status`, `git_diff`, and `git_log` over `exec`. `git_commit` needs approval, commits listed paths or already-staged files, and does not push. Paths stay under the project root.
|
|
136
|
-
|
|
137
|
-
`exec` and `git_commit` are gated. Default policy is `prompt` (y / n / always this session). `auto` still denies destructive commands. Local exec is the host, not a sandbox.
|
|
138
|
-
|
|
139
|
-
## Hooks
|
|
140
|
-
|
|
141
|
-
Optional `hooks` in `harness.config.ts`. Each hook is a shell command. JSON on stdin. `pre_tool` with a nonzero exit denies the call (stderr is the reason). Spawn failure fails open.
|
|
142
|
-
|
|
143
|
-
```
|
|
144
|
-
session_start After the runtime starts
|
|
145
|
-
pre_tool Before a tool runs. Nonzero exit denies
|
|
146
|
-
post_tool After a tool finishes
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
User and project instruction files stack. Project `AGENTS.md` does not replace `~/.harness/AGENTS.md`.
|
|
150
|
-
|
|
151
|
-
## Subagents
|
|
152
|
-
|
|
153
|
-
The parent agent has a `task` tool. It runs a nested turn with the same local tools except `task` (no recursive spawn). Optional `skills` injects those skill bodies into the subagent. Nested sessions stay in memory and do not appear in `/resume`.
|
|
154
|
-
|
|
155
|
-
Use it for one copy-pipeline step, isolated research, or a bounded edit. Not for a one-line question.
|
|
156
|
-
|
|
157
|
-
## Optional catalog skills
|
|
158
|
-
|
|
159
|
-
The package ships a generic writing pipeline and a visual-QA skill. They are not loaded until you add them:
|
|
160
|
-
|
|
161
|
-
- `/skill add copywriting` — router plus `copy-rmbc`, `copy-harry-dry`, `copy-editor`
|
|
162
|
-
- `/skill add copy-editor` — that step only, including `references/anti-slop.md`
|
|
163
|
-
- `/skill add impeccable` — visual QA (critique / polish / audit). Honor the host `design.md`. Not copy.
|
|
164
|
-
|
|
165
|
-
`/skill remove copywriting` drops the writing pack. Host `skills/` of the same name still win. Read loaded skills with `read_skill`. Invented metrics and testimonials stay illegal.
|
|
166
|
-
|
|
167
|
-
A host can add its own skills in `skills/`, `.cursor/skills`, or `.claude/skills`. Those are not shipped here.
|
|
168
|
-
|
|
169
|
-
## Library
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
import { createHarness, loadSkills, runEvalSuite } from "@useavalon/caelence-agent";
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
Agent events use these kinds: `text_delta`, `tool_call_*`, `approval_request`, `session_meta`, `usage`, `todos`, `error`, `completion`.
|
|
176
|
-
|
|
177
|
-
## Publish
|
|
178
|
-
|
|
179
|
-
The package ships TypeScript source for Bun. CI on `main` and pull requests runs Biome, `tsc --noEmit`, and `bun run test`.
|
|
180
|
-
|
|
181
|
-
Publishing uses [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/), not a GitHub `NPM_TOKEN` secret. Classic npm tokens are revoked. After the first local publish (`npm login`, then `npm publish --access public`):
|
|
182
|
-
|
|
183
|
-
1. Open the package on npmjs.com → Settings → Trusted publishing
|
|
184
|
-
2. Add GitHub Actions for `useAvalon` / `caelence-agent` with workflow `release.yml` (allow `npm publish`)
|
|
185
|
-
3. Add a second publisher for `canary.yml`
|
|
186
|
-
4. Optionally set publishing access to require 2FA and disallow tokens
|
|
96
|
+
|------|------|
|
|
97
|
+
| `ask` | Read, search, git status / diff / log |
|
|
98
|
+
| `plan` | Ask plus `todo_write` |
|
|
99
|
+
| `agent` | Writes, `exec`, `git_commit`, and `task` |
|
|
187
100
|
|
|
188
|
-
|
|
101
|
+
`/mode ask`, `/mode plan`, or `/mode agent`. `exec` and `git_commit` ask for approval by default (`prompt`). `auto` still denies destructive commands. Local exec is the host machine, not a sandbox.
|
|
189
102
|
|
|
190
|
-
|
|
191
|
-
|------|--------|
|
|
192
|
-
| `CI` | Push or PR to `main` |
|
|
193
|
-
| `Canary Release` | Push to `main` that touches `src/`, `bin/`, or `skills/` |
|
|
194
|
-
| `Release` | Manual. Channel: stable, beta, or rc. Default is dry-run |
|
|
103
|
+
## License
|
|
195
104
|
|
|
196
|
-
|
|
197
|
-
bun run lint
|
|
198
|
-
bun run typecheck
|
|
199
|
-
bun run test
|
|
200
|
-
bun run check:exports
|
|
201
|
-
```
|
|
105
|
+
[MIT](LICENSE)
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@useavalon/caelence-agent",
|
|
3
|
-
"version": "0.1.0",
|
|
3
|
+
"version": "0.1.1-canary.0",
|
|
4
4
|
"description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"license": "
|
|
6
|
+
"license": "MIT",
|
|
7
7
|
"author": "useAvalon",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
],
|
|
37
37
|
"scripts": {
|
|
38
38
|
"start": "bun bin/harness.ts",
|
|
39
|
-
"test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts",
|
|
39
|
+
"test": "bun test src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts",
|
|
40
40
|
"typecheck": "bunx tsc --noEmit -p tsconfig.json",
|
|
41
41
|
"lint": "biome ci .",
|
|
42
42
|
"format": "biome format --write .",
|
package/src/cli/main.ts
CHANGED
|
@@ -183,7 +183,7 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
|
|
|
183
183
|
);
|
|
184
184
|
return 1;
|
|
185
185
|
}
|
|
186
|
-
const child = spawn("bun", [
|
|
186
|
+
const child = spawn("bun", [resolve(desktopDir, "scripts/run-tauri.ts")], {
|
|
187
187
|
cwd: desktopDir,
|
|
188
188
|
env,
|
|
189
189
|
stdio: "inherit",
|
package/src/core/strands.ts
CHANGED
|
@@ -154,6 +154,16 @@ export function constructOpenRouterProvider(options: {
|
|
|
154
154
|
maxTokens?: number;
|
|
155
155
|
sessionId?: () => string | undefined;
|
|
156
156
|
}): MainModelProvider {
|
|
157
|
+
if (!options.apiKey.trim()) {
|
|
158
|
+
return {
|
|
159
|
+
kind: "openrouter",
|
|
160
|
+
modelId: options.model,
|
|
161
|
+
async *stream() {
|
|
162
|
+
yield { type: "error", message: "OPENROUTER_API_KEY is not set." };
|
|
163
|
+
yield { type: "done" };
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
157
167
|
let lastUsage: TokenUsage | undefined;
|
|
158
168
|
let reasoningSink: ((text: string) => void) | undefined;
|
|
159
169
|
const model = new OpenAIModel({
|
|
@@ -163,7 +173,6 @@ export function constructOpenRouterProvider(options: {
|
|
|
163
173
|
maxTokens: options.maxTokens ?? DEFAULT_MAIN_MODEL_MAX_TOKENS,
|
|
164
174
|
params: {
|
|
165
175
|
reasoning: { effort: "low", exclude: false },
|
|
166
|
-
stream_options: { include_usage: true },
|
|
167
176
|
},
|
|
168
177
|
clientConfig: {
|
|
169
178
|
baseURL: options.baseUrl.replace(/\/+$/, ""),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { DEFAULT_CONFIG } from "../config.ts";
|
|
@@ -48,6 +48,7 @@ async function withBridge(
|
|
|
48
48
|
const headers = { authorization: "Bearer test-token", "content-type": "application/json" };
|
|
49
49
|
return {
|
|
50
50
|
ready,
|
|
51
|
+
cwd,
|
|
51
52
|
headers,
|
|
52
53
|
async close() {
|
|
53
54
|
await stop();
|
|
@@ -328,4 +329,34 @@ describe("desktop bridge", () => {
|
|
|
328
329
|
await ctx.close();
|
|
329
330
|
}
|
|
330
331
|
});
|
|
332
|
+
|
|
333
|
+
test("saves turn attachments and allows an attachments-only message", async () => {
|
|
334
|
+
const ctx = await withBridge();
|
|
335
|
+
try {
|
|
336
|
+
const turn = await fetch(`${ctx.ready.url}/turn`, {
|
|
337
|
+
method: "POST",
|
|
338
|
+
headers: ctx.headers,
|
|
339
|
+
body: JSON.stringify({
|
|
340
|
+
message: "",
|
|
341
|
+
attachments: [
|
|
342
|
+
{
|
|
343
|
+
name: "note.txt",
|
|
344
|
+
mime: "text/plain",
|
|
345
|
+
data: Buffer.from("from the composer").toString("base64"),
|
|
346
|
+
},
|
|
347
|
+
],
|
|
348
|
+
}),
|
|
349
|
+
});
|
|
350
|
+
expect(turn.ok).toBe(true);
|
|
351
|
+
await turn.text();
|
|
352
|
+
const names = await readdir(join(ctx.cwd, ".harness", "uploads"));
|
|
353
|
+
expect(names.some((name) => name.endsWith("-note.txt"))).toBe(true);
|
|
354
|
+
const file = names.find((name) => name.endsWith("-note.txt"));
|
|
355
|
+
expect(await readFile(join(ctx.cwd, ".harness", "uploads", file ?? ""), "utf8")).toBe(
|
|
356
|
+
"from the composer",
|
|
357
|
+
);
|
|
358
|
+
} finally {
|
|
359
|
+
await ctx.close();
|
|
360
|
+
}
|
|
361
|
+
});
|
|
331
362
|
});
|
package/src/desktop/bridge.ts
CHANGED
|
@@ -27,6 +27,7 @@ import { createHarness, type HarnessRuntime } from "../runtime.ts";
|
|
|
27
27
|
import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
|
|
28
28
|
import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
|
|
29
29
|
import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
|
|
30
|
+
import { composeUploadMessage, parseIncomingUploads, saveUploads } from "./uploads.ts";
|
|
30
31
|
|
|
31
32
|
export interface DesktopState {
|
|
32
33
|
name: string;
|
|
@@ -599,20 +600,25 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
599
600
|
if (req.method === "POST" && path === "/turn") {
|
|
600
601
|
if (busy) return json({ error: "A turn is already running." }, 409);
|
|
601
602
|
const body = await readJson(req);
|
|
602
|
-
const
|
|
603
|
-
if (!message.trim()) return json({ error: "Message is empty." }, 400);
|
|
603
|
+
const incoming = typeof body.message === "string" ? body.message : "";
|
|
604
604
|
const editUserTurn =
|
|
605
605
|
typeof body.editUserTurn === "number" &&
|
|
606
606
|
Number.isInteger(body.editUserTurn) &&
|
|
607
607
|
body.editUserTurn >= 0
|
|
608
608
|
? body.editUserTurn
|
|
609
609
|
: undefined;
|
|
610
|
-
|
|
610
|
+
const uploads =
|
|
611
|
+
editUserTurn === undefined && !incoming.trim().startsWith("/")
|
|
612
|
+
? saveUploads(harness.cwd, parseIncomingUploads(body.attachments))
|
|
613
|
+
: [];
|
|
614
|
+
const message = composeUploadMessage(incoming, uploads);
|
|
615
|
+
if (!message.trim()) return json({ error: "Message is empty." }, 400);
|
|
616
|
+
if (editUserTurn === undefined && isHelpAlias(incoming)) {
|
|
611
617
|
const outcome = await runSlashLine(harness, "/help");
|
|
612
618
|
return json({ outcome, state: snapshot(harness, busy, title) });
|
|
613
619
|
}
|
|
614
|
-
if (editUserTurn === undefined &&
|
|
615
|
-
const outcome = await runSlashLine(harness,
|
|
620
|
+
if (editUserTurn === undefined && incoming.trim().startsWith("/")) {
|
|
621
|
+
const outcome = await runSlashLine(harness, incoming);
|
|
616
622
|
if (outcome.kind === "clear") title = "New chat";
|
|
617
623
|
if (outcome.kind === "session") {
|
|
618
624
|
harness.setSession(outcome.session.id);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
composeUploadMessage,
|
|
7
|
+
isTextUpload,
|
|
8
|
+
parseIncomingUploads,
|
|
9
|
+
safeUploadName,
|
|
10
|
+
saveUploads,
|
|
11
|
+
} from "./uploads.ts";
|
|
12
|
+
|
|
13
|
+
describe("uploads", () => {
|
|
14
|
+
test("parses named base64 attachments and ignores junk", () => {
|
|
15
|
+
expect(
|
|
16
|
+
parseIncomingUploads([
|
|
17
|
+
{ name: " a.txt ", mime: "text/plain", data: "YQ==" },
|
|
18
|
+
{ name: "", data: "YQ==" },
|
|
19
|
+
{ mime: "text/plain", data: "YQ==" },
|
|
20
|
+
"nope",
|
|
21
|
+
]),
|
|
22
|
+
).toEqual([{ name: "a.txt", mime: "text/plain", data: "YQ==" }]);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("treats source and markdown as text", () => {
|
|
26
|
+
expect(isTextUpload("notes.md", "application/octet-stream")).toBe(true);
|
|
27
|
+
expect(isTextUpload("shot.png", "image/png")).toBe(false);
|
|
28
|
+
expect(isTextUpload("data.json", "application/json")).toBe(true);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("sanitizes upload names", () => {
|
|
32
|
+
expect(safeUploadName("../weird name!.png")).toBe("weird_name_.png");
|
|
33
|
+
expect(safeUploadName("...")).toBe("file");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("writes files and composes a message with text excerpts", async () => {
|
|
37
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-uploads-"));
|
|
38
|
+
try {
|
|
39
|
+
const saved = saveUploads(cwd, [
|
|
40
|
+
{ name: "note.txt", mime: "text/plain", data: Buffer.from("hello").toString("base64") },
|
|
41
|
+
{ name: "shot.png", mime: "image/png", data: Buffer.from([0x89, 0x50]).toString("base64") },
|
|
42
|
+
]);
|
|
43
|
+
expect(saved).toHaveLength(2);
|
|
44
|
+
expect(saved[0]?.rel.startsWith(".harness/uploads/")).toBe(true);
|
|
45
|
+
expect(saved[0]?.excerpt).toBe("hello");
|
|
46
|
+
expect(saved[1]?.excerpt).toBeUndefined();
|
|
47
|
+
const body = await readFile(join(cwd, saved[0]?.rel ?? ""), "utf8");
|
|
48
|
+
expect(body).toBe("hello");
|
|
49
|
+
expect(composeUploadMessage("look", saved)).toContain("look");
|
|
50
|
+
expect(composeUploadMessage("look", saved)).toContain(saved[0]?.rel ?? "");
|
|
51
|
+
expect(composeUploadMessage("look", saved)).toContain("```\nhello\n```");
|
|
52
|
+
expect(composeUploadMessage("", saved)).toContain(saved[1]?.rel ?? "");
|
|
53
|
+
} finally {
|
|
54
|
+
await rm(cwd, { recursive: true, force: true });
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { toProjectRel } from "../tools/paths.ts";
|
|
4
|
+
|
|
5
|
+
export const MAX_UPLOADS = 8;
|
|
6
|
+
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
|
7
|
+
const TEXT_EXCERPT_BYTES = 100_000;
|
|
8
|
+
|
|
9
|
+
const TEXT_MIME =
|
|
10
|
+
/^(text\/|application\/(json|xml|javascript|sql|yaml|x-yaml|toml|x-sh|x-httpd-php))/i;
|
|
11
|
+
const TEXT_EXT =
|
|
12
|
+
/\.(txt|md|markdown|json|csv|tsv|ts|tsx|js|jsx|mjs|cjs|css|scss|html|htm|xml|yml|yaml|toml|py|rs|go|sh|bash|zsh|env|svg|log|ini|cfg)$/i;
|
|
13
|
+
|
|
14
|
+
export interface IncomingUpload {
|
|
15
|
+
name: string;
|
|
16
|
+
mime: string;
|
|
17
|
+
data: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface SavedUpload {
|
|
21
|
+
name: string;
|
|
22
|
+
rel: string;
|
|
23
|
+
mime: string;
|
|
24
|
+
excerpt?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function parseIncomingUploads(raw: unknown): IncomingUpload[] {
|
|
28
|
+
if (!Array.isArray(raw)) return [];
|
|
29
|
+
const out: IncomingUpload[] = [];
|
|
30
|
+
for (const item of raw) {
|
|
31
|
+
if (!item || typeof item !== "object") continue;
|
|
32
|
+
const rec = item as Record<string, unknown>;
|
|
33
|
+
const name = typeof rec.name === "string" ? rec.name.trim() : "";
|
|
34
|
+
const data = typeof rec.data === "string" ? rec.data.trim() : "";
|
|
35
|
+
const mime =
|
|
36
|
+
typeof rec.mime === "string" && rec.mime.trim()
|
|
37
|
+
? rec.mime.trim()
|
|
38
|
+
: "application/octet-stream";
|
|
39
|
+
if (!name || !data) continue;
|
|
40
|
+
out.push({ name, mime, data });
|
|
41
|
+
if (out.length >= MAX_UPLOADS) break;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isTextUpload(name: string, mime: string): boolean {
|
|
47
|
+
return TEXT_MIME.test(mime) || TEXT_EXT.test(name);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function safeUploadName(name: string): string {
|
|
51
|
+
const trimmed = name.trim() || "file";
|
|
52
|
+
const base = trimmed.replace(/[^\w.-]+/g, "_").replace(/^[._]+/, "");
|
|
53
|
+
return (base || "file").slice(0, 120);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function saveUploads(cwd: string, items: IncomingUpload[]): SavedUpload[] {
|
|
57
|
+
if (items.length === 0) return [];
|
|
58
|
+
const dir = resolve(cwd, ".harness", "uploads");
|
|
59
|
+
mkdirSync(dir, { recursive: true });
|
|
60
|
+
const saved: SavedUpload[] = [];
|
|
61
|
+
for (const item of items) {
|
|
62
|
+
const bytes = Buffer.from(item.data, "base64");
|
|
63
|
+
if (bytes.byteLength === 0 || bytes.byteLength > MAX_UPLOAD_BYTES) continue;
|
|
64
|
+
const unique = `${Date.now()}-${saved.length}-${safeUploadName(item.name)}`;
|
|
65
|
+
const abs = resolve(dir, unique);
|
|
66
|
+
writeFileSync(abs, bytes);
|
|
67
|
+
const rel = toProjectRel(cwd, abs);
|
|
68
|
+
const excerpt =
|
|
69
|
+
isTextUpload(item.name, item.mime) && bytes.byteLength <= TEXT_EXCERPT_BYTES
|
|
70
|
+
? bytes.toString("utf8")
|
|
71
|
+
: undefined;
|
|
72
|
+
saved.push({
|
|
73
|
+
name: item.name,
|
|
74
|
+
rel,
|
|
75
|
+
mime: item.mime,
|
|
76
|
+
...(excerpt !== undefined ? { excerpt } : {}),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return saved;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function composeUploadMessage(text: string, files: SavedUpload[]): string {
|
|
83
|
+
if (files.length === 0) return text;
|
|
84
|
+
const blocks = files.map((file) => {
|
|
85
|
+
if (file.excerpt !== undefined) {
|
|
86
|
+
return `Attached \`${file.rel}\` (${file.name}):\n\n\`\`\`\n${file.excerpt}\n\`\`\``;
|
|
87
|
+
}
|
|
88
|
+
return `Attached \`${file.rel}\` (${file.name}, ${file.mime}). Use that project path.`;
|
|
89
|
+
});
|
|
90
|
+
const body = text.trim();
|
|
91
|
+
return body ? `${body}\n\n${blocks.join("\n\n")}` : blocks.join("\n\n");
|
|
92
|
+
}
|
package/src/runtime.test.ts
CHANGED
|
@@ -62,6 +62,30 @@ describe("createHarness modes", () => {
|
|
|
62
62
|
}
|
|
63
63
|
});
|
|
64
64
|
|
|
65
|
+
test("starts without an OpenRouter key", async () => {
|
|
66
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-nokey-"));
|
|
67
|
+
const previous = process.env.OPENROUTER_API_KEY;
|
|
68
|
+
delete process.env.OPENROUTER_API_KEY;
|
|
69
|
+
try {
|
|
70
|
+
const harness = await createHarness({
|
|
71
|
+
cwd,
|
|
72
|
+
config: DEFAULT_CONFIG,
|
|
73
|
+
constructAgent: () => ({
|
|
74
|
+
async run() {
|
|
75
|
+
throw new Error("should not run");
|
|
76
|
+
},
|
|
77
|
+
}),
|
|
78
|
+
observability: noopObservability,
|
|
79
|
+
});
|
|
80
|
+
expect(harness.hasApiKey).toBe(false);
|
|
81
|
+
harness.close();
|
|
82
|
+
} finally {
|
|
83
|
+
if (previous === undefined) delete process.env.OPENROUTER_API_KEY;
|
|
84
|
+
else process.env.OPENROUTER_API_KEY = previous;
|
|
85
|
+
await rm(cwd, { recursive: true, force: true });
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
65
89
|
test("accumulates usage on the runtime", async () => {
|
|
66
90
|
const cwd = await mkdtemp(join(tmpdir(), "harness-spend-"));
|
|
67
91
|
try {
|