harn-serve 0.10.122

Shared outbound workflow server core for Harn adapters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use super::*;
/// End-to-end ACP slash-command flow: a Zed-style client receives the
/// `available_commands_update` notification immediately after
/// `session/new`, then invokes one of the advertised commands and
/// observes a successful round-trip with the named pipeline executed.
/// Locks the wire shape required by the ACP spec
/// (<https://agentclientprotocol.com/protocol/slash-commands>).
#[tokio::test(flavor = "current_thread")]
async fn acp_advertises_and_dispatches_slash_commands() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("commands.harn");
            std::fs::write(
                &pipeline_path,
                "@command(name: \"review\", description: \"Review the diff\", \
                     hint: \"focus area\")\n\
                     pipeline review_branch(harness: Harness, task: unknown) {\n  \
                       harness.stdio.println(\"REVIEW:\" + prompt)\n}\n\n\
                     pipeline default(harness: Harness, task: unknown) {\n  \
                       harness.stdio.println(\"DEFAULT:\" + prompt)\n}\n",
            )
            .expect("write pipeline");

            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy()),
                request_rx,
                response_tx,
            ));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "session/new",
                    "params": {"cwd": dir.path()},
                }))
                .expect("send session/new");
            let created = recv_json(&mut response_rx).await;
            let session_id = created["result"]["sessionId"]
                .as_str()
                .expect("session id")
                .to_string();

            let advertised = recv_json(&mut response_rx).await;
            assert_eq!(advertised["method"], "session/update");
            assert_eq!(advertised["params"]["sessionId"], session_id);
            assert_eq!(
                advertised["params"]["update"]["sessionUpdate"],
                "available_commands_update"
            );
            let commands = advertised["params"]["update"]["availableCommands"]
                .as_array()
                .expect("availableCommands array");
            assert_eq!(commands.len(), 1);
            assert_eq!(commands[0]["name"], "review");
            assert_eq!(commands[0]["description"], "Review the diff");
            assert_eq!(commands[0]["input"]["hint"], "focus area");

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [{"type": "text", "text": "/review src/lib.rs"}],
                    },
                }))
                .expect("send session/prompt");

            let mut saw_review_chunk = false;
            let mut saw_completed = false;
            for _ in 0..32 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                    continue;
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                {
                    let text = message["params"]["update"]["content"]["text"]
                        .as_str()
                        .unwrap_or_default();
                    if text.contains("REVIEW:src/lib.rs") {
                        saw_review_chunk = true;
                    }
                    assert!(
                        !text.contains("DEFAULT:"),
                        "default pipeline must not run when slash command dispatches"
                    );
                }
                if message["id"] == 2 {
                    assert_eq!(message["result"]["stopReason"], "end_turn");
                    saw_completed = true;
                    break;
                }
            }
            assert!(saw_review_chunk, "named pipeline should run for /review");
            assert!(saw_completed, "prompt should finish successfully");

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

/// Unknown slash invocations (i.e. `/typo args` when `typo` isn't
/// advertised) must not be re-routed — the original prompt text
/// flows through to the default pipeline so it can decide how to
/// handle the literal slash.
#[tokio::test(flavor = "current_thread")]
async fn acp_unknown_slash_invocation_falls_through_to_default_pipeline() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("fallthrough.harn");
            std::fs::write(
                &pipeline_path,
                "@command(name: \"known\", description: \"known\")\n\
                     pipeline known(harness: Harness, task: unknown) { harness.stdio.println(\"KNOWN\") }\n\n\
                     pipeline default(harness: Harness, task: unknown) { harness.stdio.println(\"DEFAULT:\" + prompt) }\n",
            )
            .expect("write pipeline");

            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy()),
                request_rx,
                response_tx,
            ));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "session/new",
                    "params": {"cwd": dir.path()},
                }))
                .expect("send session/new");
            let created = recv_json(&mut response_rx).await;
            let session_id = created["result"]["sessionId"]
                .as_str()
                .expect("session id")
                .to_string();
            let _advertised = recv_json(&mut response_rx).await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [{"type": "text", "text": "/typo and friends"}],
                    },
                }))
                .expect("send session/prompt");

            let mut saw_default_with_full_text = false;
            for _ in 0..32 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                    continue;
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                {
                    let text = message["params"]["update"]["content"]["text"]
                        .as_str()
                        .unwrap_or_default();
                    if text.contains("DEFAULT:/typo and friends") {
                        saw_default_with_full_text = true;
                    }
                }
                if message["id"] == 2 {
                    assert_eq!(message["result"]["stopReason"], "end_turn");
                    break;
                }
            }
            assert!(
                saw_default_with_full_text,
                "default pipeline should receive the full original prompt text"
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

/// Inline-prompt mode (no `--pipeline`) has no surface for
/// `@command`-tagged pipelines. A leading slash is unambiguously a
/// user error there; surface a clear diagnostic instead of letting
/// the compile-time `pipeline main() { /foo args }` error leak out.
#[tokio::test(flavor = "current_thread")]
async fn acp_inline_mode_rejects_slash_invocations_with_friendly_error() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let mut server = AcpServer::new_with_output(AcpServerConfig::new(None), AcpOutput::Channel(tx));

    server
        .handle_incoming_message(serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "session/new",
            "params": {"cwd": "."},
        }))
        .await;
    let created = recv_json(&mut rx).await;
    let session_id = created["result"]["sessionId"]
        .as_str()
        .expect("session id")
        .to_string();

    server
        .handle_incoming_message(serde_json::json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "session/prompt",
            "params": {
                "sessionId": session_id,
                "prompt": [{"type": "text", "text": "/foo args"}],
            },
        }))
        .await;

    // The friendly diagnostic is a terminal failure, so it arrives as exactly
    // one typed JSON-RPC error and never as an assistant `agent_message_chunk`.
    let error = recv_json(&mut rx).await;
    assert_eq!(
        error["method"],
        serde_json::Value::Null,
        "no session/update precedes the error"
    );
    assert_eq!(error["id"], 2);
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap_or_default()
            .contains("Slash commands require `--pipeline"),
        "expected friendly inline-mode error message, got: {error}"
    );
    assert_eq!(
        error["error"]["data"]["schema"],
        ACP_PROMPT_ERROR_DATA_SCHEMA
    );
    assert_eq!(error["error"]["data"]["terminalClass"], "generic_throw");
}

/// Hot-reload: when the pipeline source changes between prompts, the
/// next prompt re-emits `available_commands_update` with the fresh
/// command set. When the source is unchanged, no duplicate update is
/// emitted (idempotent advertise).
#[tokio::test(flavor = "current_thread")]
async fn acp_reemits_available_commands_on_pipeline_hot_reload() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("hot.harn");
            std::fs::write(
                &pipeline_path,
                "@command(name: \"alpha\", description: \"first\")\n\
                     pipeline alpha(harness: Harness, task: unknown) { harness.stdio.println(\"alpha\") }\n",
            )
            .expect("write initial pipeline");

            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy()),
                request_rx,
                response_tx,
            ));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "session/new",
                    "params": {"cwd": dir.path()},
                }))
                .expect("send session/new");
            let created = recv_json(&mut response_rx).await;
            let session_id = created["result"]["sessionId"]
                .as_str()
                .expect("session id")
                .to_string();
            let initial = recv_json(&mut response_rx).await;
            let initial_commands = initial["params"]["update"]["availableCommands"]
                .as_array()
                .expect("availableCommands array");
            assert_eq!(initial_commands.len(), 1);
            assert_eq!(initial_commands[0]["name"], "alpha");

            std::fs::write(
                &pipeline_path,
                "@command(name: \"alpha\", description: \"first\")\n\
                     pipeline alpha(harness: Harness, task: unknown) { harness.stdio.println(\"alpha\") }\n\n\
                     @command(name: \"beta\", description: \"second\")\n\
                     pipeline beta(harness: Harness, task: unknown) { harness.stdio.println(\"beta\") }\n",
            )
            .expect("rewrite pipeline");

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [{"type": "text", "text": "/beta now"}],
                    },
                }))
                .expect("send session/prompt");

            let mut saw_refreshed_advertise = false;
            let mut saw_beta_chunk = false;
            for _ in 0..32 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                    continue;
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "available_commands_update"
                {
                    let names: Vec<String> = message["params"]["update"]["availableCommands"]
                        .as_array()
                        .unwrap()
                        .iter()
                        .map(|c| c["name"].as_str().unwrap().to_string())
                        .collect();
                    assert_eq!(names, vec!["alpha".to_string(), "beta".to_string()]);
                    saw_refreshed_advertise = true;
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                    && message["params"]["update"]["content"]["text"]
                        .as_str()
                        .unwrap_or_default()
                        .contains("beta")
                {
                    saw_beta_chunk = true;
                }
                if message["id"] == 2 {
                    assert_eq!(message["result"]["stopReason"], "end_turn");
                    break;
                }
            }
            assert!(
                saw_refreshed_advertise,
                "expected fresh available_commands_update after source change"
            );
            assert!(
                saw_beta_chunk,
                "the newly added /beta command should dispatch"
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

/// Drive an agent loop through a real ACP roundtrip and return the complete
/// prompt result, including Harn's typed terminal extension.
async fn run_acp_agent_loop_prompt(prompt_body: &str) -> serde_json::Value {
    let dir = tempfile::tempdir().expect("tempdir");
    let pipeline_path = dir.path().join("agent-loop.harn");
    std::fs::write(
        &pipeline_path,
        format!(
            "import {{ agent_loop }} from \"std/agent/loop\"\n\
             pipeline default(harness: Harness, task: unknown) {{\n{prompt_body}\n}}\n"
        ),
    )
    .expect("write agent-loop pipeline");
    let (request_tx, mut response_rx, server, session_id) = start_acp_code_session_with_config(
        AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy().to_string()),
        serde_json::json!(dir.path()),
    )
    .await;

    request_tx
        .send(serde_json::json!({
            "jsonrpc": "2.0",
            "id": 3,
            "method": "session/prompt",
            "params": {
                "sessionId": session_id,
                "prompt": [{"type": "text", "text": "hello"}],
            },
        }))
        .expect("send session/prompt");

    let mut result = serde_json::Value::Null;
    for _ in 0..64 {
        let message = recv_json(&mut response_rx).await;
        if message["method"] == "host/capabilities" {
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": message["id"].clone(),
                    "result": {},
                }))
                .expect("send host capabilities response");
            continue;
        }
        if message["id"] == 3 {
            result = message["result"].clone();
            break;
        }
    }
    drop(request_tx);
    server.await.expect("ACP channel server task");
    result
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_reports_end_turn_when_loop_finishes_naturally() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let body = "harness.llm.mock_clear()\n\
                            harness.llm.mock_enqueue({text: \"all done\"})\n\
                            agent_loop(harness, \"hello\", nil, {provider: \"mock\"})";
            let result = run_acp_agent_loop_prompt(body).await;
            assert_eq!(result["stopReason"], "end_turn");
            assert_eq!(result["_meta"]["harn"]["terminal"]["kind"], "natural");
            assert_eq!(result["_meta"]["harn"]["terminal"]["owner"], "agent");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_reports_max_tokens_from_provider_signal() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let body = "harness.llm.mock_clear()\n\
                            harness.llm.mock_enqueue({text: \"truncated\", stop_reason: \"max_tokens\"})\n\
                            agent_loop(harness, \"hello\", nil, {provider: \"mock\"})";
            let result = run_acp_agent_loop_prompt(body).await;
            assert_eq!(result["stopReason"], "max_tokens");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_reports_refusal_from_provider_signal() {
    let local = tokio::task::LocalSet::new();
    local
            .run_until(async {
                let body = "harness.llm.mock_clear()\n\
                            harness.llm.mock_enqueue({text: \"I cannot assist with that.\", stop_reason: \"refusal\"})\n\
                            agent_loop(harness, \"hello\", nil, {provider: \"mock\"})";
                let result = run_acp_agent_loop_prompt(body).await;
                assert_eq!(result["stopReason"], "refusal");
            })
            .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_reports_max_turn_requests_when_iteration_cap_hit() {
    let local = tokio::task::LocalSet::new();
    local
            .run_until(async {
                // `loop_until_done: true` keeps the loop iterating on a
                // text-only mock turn, and `max_iterations: 1` forces
                // the cap to fire on iteration 1 → ACP `max_turn_requests`.
                let body = "harness.llm.mock_clear()\n\
                            harness.llm.mock_enqueue({text: \"still working\"})\n\
                            harness.llm.mock_enqueue({text: \"still working\"})\n\
                            agent_loop(harness, \"hello\", nil, {provider: \"mock\", loop_until_done: true, max_iterations: 1})";
                let result = run_acp_agent_loop_prompt(body).await;
                assert_eq!(result["stopReason"], "max_turn_requests");
                assert_eq!(
                    result["_meta"]["harn"]["terminal"],
                    serde_json::json!({
                        "kind": "policy_budget",
                        "reason": "max_iterations",
                        "owner": "policy",
                    })
                );
            })
            .await;
}