Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions rust/crates/agent-runtime/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,11 @@ pub(crate) struct ToolCallEvent {
pub tool_kind: Option<ToolKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// The command line an `execute` call runs, as its shell sees it; `title`
/// then says what it is for. Sent only to a backend whose `didStart`
/// carried `toolCommands`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<ToolLocation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -636,6 +641,10 @@ fn check_bounds(event: &SessionEvent) -> Result<(), String> {
SessionEvent::ToolCall(call) => {
label(&call.tool_call_id, "toolCallID")?;
optional_label(&call.title, "title")?;
if call.command.as_deref().is_some_and(str::is_empty) {
return Err("has an empty command".to_string());
}
text(call.command.as_deref().unwrap_or_default(), "command")?;
if call.locations.len() > MAX_LOCATIONS {
return Err("has too many locations".to_string());
}
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/agent-runtime/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,9 @@ fn start_checked(runtime: &Arc<Runtime>, request: StartRequest) -> Result<Value,
request.resume.as_deref(),
);
started["session"] = json!(id);
// Older hosts reject unknown `toolCall` fields, so a backend sends a
// tool call's `command` only after Core says here that it takes one.
started["toolCommands"] = true.into();
if link.notify(&backend, AGENTS_DID_START, started).is_err() {
runtime.live.lock().remove(&id);
streams.handle.terminate();
Expand Down
24 changes: 21 additions & 3 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1558,10 +1558,12 @@ fn call_read(
});
// Older hosts reject unknown message fields. Backends emit IDs only when the
// caller explicitly asks for them; ordinary reads keep the original wire shape.
// A page also asks for tool-call details, so recorded turns can show as live ones.
// A page also asks for tool-call details, so recorded turns can show as live ones,
// and for the commands of `execute` calls, which older hosts reject.
if message_ids {
params["messageIDs"] = true.into();
params["toolCalls"] = true.into();
params["toolCommands"] = true.into();
}
let answer = link
.call(
Expand Down Expand Up @@ -1633,6 +1635,9 @@ struct ReadMessage {
tool_kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
/// The command line of an `execute` call, as in the live `toolCall` event.
#[serde(default, skip_serializing_if = "Option::is_none")]
command: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
locations: Option<Vec<ReadLocation>>,
}
Expand All @@ -1655,6 +1660,7 @@ fn valid_tool_details(message: &ReadMessage) -> bool {
|| message.status.is_some()
|| message.tool_kind.is_some()
|| message.title.is_some()
|| message.command.is_some()
|| message.locations.is_some();
if !details {
return true;
Expand All @@ -1679,6 +1685,10 @@ fn valid_tool_details(message: &ReadMessage) -> bool {
)
})
&& message.title.as_deref().is_none_or(label)
&& message
.command
.as_deref()
.is_none_or(|command| !command.is_empty() && command.len() <= MAX_MESSAGE_TEXT_BYTES)
&& message.locations.as_ref().is_none_or(|locations| {
locations.len() <= MAX_TOOL_LOCATIONS
&& locations.iter().all(|location| label(&location.path))
Expand All @@ -1692,8 +1702,16 @@ struct ReadItem {
messages: Vec<ReadMessage>,
}

/// The fields a reader may return only when the request asked for `toolCalls`.
const TOOL_DETAIL_FIELDS: [&str; 5] = ["toolCallID", "status", "toolKind", "title", "locations"];
/// The fields a reader may return only when the request asked for `toolCalls`
/// (and, for `command`, `toolCommands`, which Core always asks for with it).
const TOOL_DETAIL_FIELDS: [&str; 6] = [
"toolCallID",
"status",
"toolKind",
"title",
"command",
"locations",
];

/// Decodes one answer item. Without `tool_details` the original strict shape applies:
/// a detail field, even an explicit null, makes the reading invalid.
Expand Down
47 changes: 45 additions & 2 deletions rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,12 @@ fn native_session_relays_the_cli_and_checks_reports_against_turns() {
);
assert_eq!(
harness.link.await_notice(AGENTS_DID_START, |_| true),
json!({ "agentID": AGENT, "cwd": path_text(&harness.work), "session": session })
json!({
"agentID": AGENT,
"cwd": path_text(&harness.work),
"session": session,
"toolCommands": true
})
);
let started = harness.next_event(&session, "started");
assert_eq!(started["pluginID"], PLUGIN);
Expand Down Expand Up @@ -905,6 +910,30 @@ fn native_session_relays_the_cli_and_checks_reports_against_turns() {
harness.next_event(&session, "permissionRequested")["permission"],
"p1"
);

// An `execute` call carries its command line apart from its title.
harness
.report(
&session,
json!([{
"kind": "toolCall", "turn": 1, "toolCallID": "c1", "status": "completed",
"toolKind": "execute", "title": "List the files", "command": "ls -la"
}]),
)
.expect("a tool call with a command");
let call = harness.next_event(&session, "toolCall");
assert_eq!(call["title"], "List the files");
assert_eq!(call["command"], "ls -la");
let refusal = harness
.report(
&session,
json!([{
"kind": "toolCall", "turn": 1, "toolCallID": "c2", "status": "completed",
"toolKind": "execute", "command": ""
}]),
)
.expect_err("an empty command is refused");
assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS);
let sessions = harness.sessions();
assert_eq!(sessions.len(), 1);
assert_eq!(sessions[0]["pendingPermissions"], json!(["p1"]));
Expand Down Expand Up @@ -2731,6 +2760,7 @@ fn records_page_message_ids_are_opt_in_and_validated() {
if function == "sessions.read" && params["mode"] == "messages" {
assert_eq!(params["messageIDs"], true);
assert_eq!(params["toolCalls"], true);
assert_eq!(params["toolCommands"], true);
let mut answer = read(params);
for message in answer["items"][0]["messages"].as_array_mut().unwrap() {
message["id"] = "source-message-1".into();
Expand Down Expand Up @@ -2769,18 +2799,24 @@ fn records_page_tool_call_details_follow_the_live_bounds() {
"status": "inProgress", "toolKind": "read", "title": "Read main.go",
"locations": [{ "path": "/work/main.go", "line": 3 }] });
let result = json!({ "role": "tool", "text": "package main", "toolCallID": "call-1", "status": "completed" });
let answer = json!({ "items": [{ "messages": [call, result] }] });
let command = json!({ "role": "tool", "text": "", "toolCallID": "call-2", "status": "completed",
"toolKind": "execute", "title": "List the files", "command": "ls -la" });
let answer = json!({ "items": [{ "messages": [call, result, command] }] });
harness.link.set_answer(move |_, _| Ok(answer.clone()));
let page = harness.run("agentSessions.page", request.clone());
assert_eq!(page["messages"][0]["locations"][0]["line"], 3);
assert_eq!(page["messages"][1]["status"], "completed");
assert_eq!(page["messages"][2]["title"], "List the files");
assert_eq!(page["messages"][2]["command"], "ls -la");
let refused = [
json!({ "role": "assistant", "text": "x", "toolCallID": "call-1" }),
json!({ "role": "tool", "text": "x", "status": "completed" }),
json!({ "role": "tool", "text": "x", "toolCallID": "call-1", "status": "done" }),
json!({ "role": "tool", "text": "x", "toolCallID": "call-1", "toolKind": "shell" }),
json!({ "role": "tool", "text": "x", "toolCallID": "", "title": "t" }),
json!({ "role": "tool", "text": "x", "toolCallID": "c", "locations": [{ "path": "" }] }),
json!({ "role": "tool", "text": "x", "toolCallID": "c", "command": "" }),
json!({ "role": "assistant", "text": "x", "command": "ls" }),
];
for message in refused {
harness
Expand Down Expand Up @@ -2823,6 +2859,13 @@ fn legacy_reads_refuse_tool_details_they_did_not_ask_for() {
harness.refused("agentSessions.read", legacy.clone()),
"agentSessions.invalidRead"
);
let command =
json!({ "items": [{ "messages": [{ "role": "tool", "text": "x", "command": "ls" }] }] });
harness.link.set_answer(move |_, _| Ok(command.clone()));
assert_eq!(
harness.refused("agentSessions.read", legacy.clone()),
"agentSessions.invalidRead"
);
// An explicit null is still a field the legacy shape does not have.
let null =
json!({ "items": [{ "messages": [{ "role": "tool", "text": "x", "status": null }] }] });
Expand Down
23 changes: 19 additions & 4 deletions shared/plugins/contract/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3970,7 +3970,7 @@ Notifications Core sends (the host may not send them):

| Notification | Params |
| --- | --- |
| `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?}` |
| `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?, toolCommands?}` |
| `lithe/host/agents/didOutput` | `{session, lines}` |
| `lithe/host/agents/didPrompt` | `{session, turn, text, attachments?, mode?: "steer", input?}`; `mode` and `input` occur together only for running-turn input |
| `lithe/host/agents/didCancel` | `{session, turn}` |
Expand All @@ -3979,6 +3979,10 @@ Notifications Core sends (the host may not send them):
| `lithe/host/agents/didSetConfigOption` | `{session, option, value}` |
| `lithe/host/agents/didExit` | `{session, exitCode?}` |

- `didStart` carries `toolCommands: true` when Core takes a `command` on
`toolCall` events (see below). A backend sends `command` only to a session
whose `didStart` said so; Core revisions without it reject the field and
refuse the whole report.
- `didOutput` carries at most 64 lines or 4 MiB per notification, in order.
A line longer than 16 MiB is dropped and the host receives the event
`outputLineDropped`; a notification the backend does not take ends the
Expand Down Expand Up @@ -4059,7 +4063,7 @@ Session events (`report`'s `events[]`, each tagged by `kind`):
| --- | --- |
| `session` | `agentSessionID, model?, effort?, agentVersion?`: the CLI's own session, for resume and the records |
| `message` | `turn, role` (`assistant` or `thought`), `messageID, text, delta`: `delta: true` appends `text` to the message |
| `toolCall` | `turn, toolCallID, status` (`pending`, `inProgress`, `completed`, `failed`), `toolKind?` (`read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `other`), `title?, locations?` (at most 64 `{path, line?}`), `diff?` (`{path, oldText?, newText}`), `output?` |
| `toolCall` | `turn, toolCallID, status` (`pending`, `inProgress`, `completed`, `failed`), `toolKind?` (`read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `other`), `title?, command?, locations?` (at most 64 `{path, line?}`), `diff?` (`{path, oldText?, newText}`), `output?` |
| `plan` | `turn, entries`: at most 256 `{content, status}` |
| `permissionRequested` | `turn, permission, title, toolCallID?, options`: 1–8 `{id, label, optionKind}` with unique IDs, `optionKind` one of `allowOnce`, `allowAlways`, `rejectOnce`, `rejectAlways` |
| `usage` | `turn?, model?, tokens, contextUsed?, contextWindow?, costUsd?` (finite, not negative) |
Expand Down Expand Up @@ -4115,6 +4119,14 @@ original interactions and handle rejection before advertising the extension.
replaces the last; an empty list withdraws them. The event names no turn
and may come at any time. The host shows `model` and `thoughtLevel`
settings by the model picker and the others as menus.
- `command` is the command line an `execute` call runs, as its shell sees
it, 1 byte to 1 MiB; `title` then says in plain words what the command is
for, such as the description the CLI gave it. A CLI that has no such
description leaves `title` out or sets it to the command. Send `command`
only when `didStart` carried `toolCommands: true`. The host shows the title
as the step's heading and the command in its command card, and falls back
to the title alone without `command`. This is an addition within API-45
and `agents` 0.
- `message`, `toolCall`, `plan`, `permissionRequested` and `turnEnded` name
the active turn; a `usage` turn is at most the latest one. `turnEnded`
ends the turn and drops its pending permission requests.
Expand Down Expand Up @@ -4296,7 +4308,7 @@ state?}` and has 30 seconds. It answers:
conversation text;
- `rateLimits`: `{atMs, windows, plan?}`, the latest quota the file shows.

`read` receives `{agentID, sourceID, mode, messageIDs?, items: [{path, lines}]}` and has
`read` receives `{agentID, sourceID, mode, messageIDs?, toolCalls?, toolCommands?, items: [{path, lines}]}` and has
15 seconds. It answers exactly `{items}`, one per request item: in `titles`
mode `{title}` (cut to 512 bytes), in `messages` mode `{messages}`, at most
2048 `{role, text, id?, atMs?, toolName?}` with `role` one of `user`,
Expand All @@ -4315,7 +4327,10 @@ message carry the live [`toolCall`](#native-sessions) details: `toolCallID`
(required with any other detail), `status` (`pending`, `inProgress`,
`completed`, `failed`), `toolKind` (`read`, `edit`, `delete`, `move`,
`search`, `execute`, `think`, `fetch`, `other`), `title` and `locations`
(at most 64 `{path, line?}`), labels and paths 1 byte to 1 KiB. A call and
(at most 64 `{path, line?}`), labels and paths 1 byte to 1 KiB. With
`toolCommands: true`, which `agentSessions.page` sends with `toolCalls`, a
call may also carry the live `command` (1 byte to 1 MiB); without it a
`command` is `agentSessions.invalidRead`. A call and
its result are separate messages with the same `toolCallID`, in file order;
`text` holds the result's output. A host folds them into one tool call the
way it folds live `toolCall` updates, and starts a turn at each `user`
Expand Down
20 changes: 13 additions & 7 deletions shared/plugins/contract/v1/fixtures/agents/native-session.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A prompt with attachments reaches the handler's attachment method with each attachment as Core described it (type, path, name, uri, and mimeType for an image), recorded as a fourth element; a prompt without attachments reaches the plain prompt method. A test backend gives every session of agent plain a handler with only the plain prompt method; for it the SDK's default passes a prompt whose attachments are all file links to that method as the text, then a blank line unless the text is blank, then each attachment's link [@name](uri) on its own line, and ends a turn whose prompt has an image as failed. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.",
"description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A didStart's toolCommands reaches the handler as true only when Core sent it as true. A prompt with attachments reaches the handler's attachment method with each attachment as Core described it (type, path, name, uri, and mimeType for an image), recorded as a fourth element; a prompt without attachments reaches the plain prompt method. A test backend gives every session of agent plain a handler with only the plain prompt method; for it the SDK's default passes a prompt whose attachments are all file links to that method as the text, then a blank line unless the text is blank, then each attachment's link [@name](uri) on its own line, and ends a turn whose prompt has an image as failed. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.",
"sessions": {
"notifications": [
{
Expand All @@ -16,7 +16,8 @@
"session": "agent-2",
"agentID": "example",
"cwd": "/work/orders",
"resume": "previous-session"
"resume": "previous-session",
"toolCommands": true
}
},
{
Expand Down Expand Up @@ -133,7 +134,8 @@
"session": "agent-1",
"agentID": "example",
"cwd": "/work/orders",
"resume": null
"resume": null,
"toolCommands": false
}
],
[
Expand Down Expand Up @@ -201,7 +203,8 @@
"session": "agent-2",
"agentID": "example",
"cwd": "/work/orders",
"resume": "previous-session"
"resume": "previous-session",
"toolCommands": true
}
],
[
Expand Down Expand Up @@ -384,7 +387,8 @@
"session": "agent-4",
"agentID": "example",
"cwd": "/work/orders",
"resume": null
"resume": null,
"toolCommands": false
}
],
[
Expand All @@ -409,7 +413,8 @@
"session": "agent-5",
"agentID": "plain",
"cwd": "/work/orders",
"resume": null
"resume": null,
"toolCommands": false
}
],
[
Expand Down Expand Up @@ -660,7 +665,8 @@
"session": "agent-6",
"agentID": "example",
"cwd": "/work/orders",
"resume": null
"resume": null,
"toolCommands": false
}
],
[
Expand Down
Loading
Loading