1use std::sync::Arc;
14
15use base64::Engine as _;
16
17use super::{live, origin_sig, withhold};
18use crate::backend::message_origin::RecordOrigin;
19use crate::backend::mps;
20use crate::backend::storage::filestore::{AppendPos, FileStore};
21
22use crate::backend::blockcontroller::shell::handle_append_block_file;
23
24fn is_defined_agent_zone(zone: &str) -> bool {
32 zone.strip_prefix("agent:")
33 .and_then(|z| z.strip_suffix(":current"))
34 .is_some_and(|id| crate::backend::providers::get_provider(id).is_none())
35}
36
37pub fn persist_user_line(
51 broker: Option<&mps::Broker>,
52 block_id: &str,
53 data: &[u8],
54 filestore: Option<&Arc<FileStore>>,
55 global_output_zone: Option<&str>,
56 record: Option<&RecordOrigin>,
57) {
58 persist_user_line_as(broker, block_id, data, filestore, global_output_zone, true, record);
59}
60
61pub fn persist_injected_user_line(
65 broker: Option<&mps::Broker>,
66 block_id: &str,
67 data: &[u8],
68 filestore: Option<&Arc<FileStore>>,
69 global_output_zone: Option<&str>,
70 record: Option<&RecordOrigin>,
71) {
72 persist_user_line_as(broker, block_id, data, filestore, global_output_zone, false, record);
73}
74
75fn persist_user_line_as(
76 broker: Option<&mps::Broker>,
77 block_id: &str,
78 data: &[u8],
79 filestore: Option<&Arc<FileStore>>,
80 global_output_zone: Option<&str>,
81 shown_by_pane: bool,
82 record: Option<&RecordOrigin>,
83) {
84 if record.is_some_and(|r| r.resend) {
86 return;
87 }
88 let data = withhold::lines(data);
90 let data: &[u8] = &data;
91 let global = global_output_zone.and_then(|zone| {
92 crate::backend::agent_session::global_transcript_store().map(|gfs| (gfs, zone))
93 });
94 let from_device = crate::backend::viewer::origin::stamp(block_id, data);
97 let echo = if from_device.is_none() && shown_by_pane { Some("stdin") } else { None };
98 let data = from_device.as_deref().unwrap_or(data);
99 let stamped;
100 let data = match record {
101 Some(record) => {
102 stamped = crate::backend::message_origin::stamp_bytes(data, record);
103 stamped.as_slice()
104 }
105 None => data,
106 };
107 let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
109 let signed = origin_sig::sign_line(owner, data, agentmux_common::time::now_ms());
110 let data = signed.as_slice();
111 append_transcript(broker, block_id, data, filestore, global, global_output_zone.is_some(), echo);
112}
113
114fn origin_of_echo(block_id: &str, line: &str, global_output_zone: Option<&str>) -> Option<String> {
118 let text = origin_sig::echoed_prompt(line)?;
119 let record = super::origin_ledger::take(block_id, &text)?;
120 let mut value: serde_json::Value = serde_json::from_str(line).ok()?;
121 value.as_object_mut()?.remove("amx");
122 crate::backend::viewer::origin::stamp_record(block_id, &mut value, &text);
123 let stored = format!("{value}\n");
124 let stamped = crate::backend::message_origin::stamp_bytes(withhold::text(&stored).as_bytes(), &record);
125 let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
126 String::from_utf8(origin_sig::sign_line(owner, &stamped, agentmux_common::time::now_ms())).ok()
127}
128
129pub fn append_output_line(
135 broker: &mps::Broker,
136 block_id: &str,
137 line: &str,
138 filestore: Option<&Arc<FileStore>>,
139 global_output_zone: Option<&str>,
140) {
141 append_output_line_by(broker, block_id, line, filestore, global_output_zone, None);
142}
143
144pub fn append_agent_output_line(
147 broker: &mps::Broker,
148 block_id: &str,
149 line: &str,
150 filestore: Option<&Arc<FileStore>>,
151 global_output_zone: Option<&str>,
152 runtime: origin_sig::WriterRuntime,
153) {
154 append_output_line_by(broker, block_id, line, filestore, global_output_zone, Some(runtime));
155}
156
157fn append_output_line_by(
158 broker: &mps::Broker,
159 block_id: &str,
160 line: &str,
161 filestore: Option<&Arc<FileStore>>,
162 global_output_zone: Option<&str>,
163 writer: Option<origin_sig::WriterRuntime>,
164) {
165 let line_with_newline = origin_of_echo(block_id, line, global_output_zone)
167 .or_else(|| {
168 let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
169 let stamped = origin_sig::stamp_writer(owner, &withhold::text(line), writer?, agentmux_common::time::now_ms())?;
170 Some(format!("{stamped}\n"))
171 })
172 .unwrap_or_else(|| format!("{}\n", withhold::text(line)));
173 handle_append_block_file(
174 broker,
175 block_id,
176 crate::backend::agent_session::OUTPUT_FILE,
177 line_with_newline.as_bytes(),
178 filestore,
179 global_output_zone,
180 );
181}
182
183pub(crate) fn mirror_append_to_global(gfs: &Arc<FileStore>, zone: &str, data: &[u8]) -> Option<AppendPos> {
189 use crate::backend::agent_session::OUTPUT_FILE;
190 let landed = append_transcript_lines(gfs, zone, OUTPUT_FILE, data, true, "global transcripts", true);
194 if landed.is_some() {
195 crate::backend::history_changed::mark();
197 }
198 landed
199}
200
201pub(crate) fn mirror_seed_with_stamps(gfs: &Arc<FileStore>, def: &str, data: &[u8], stamps: &[(i64, i64)]) -> Result<Option<AppendPos>, String> {
205 use crate::backend::agent_session::{agent_current_zone, OUTPUT_FILE, TSIDX_FILE};
206 use crate::backend::storage::error::StoreError;
207 use crate::backend::storage::filestore::{FileMeta, FileOpts};
208 let zone = agent_current_zone(def);
209 let archives = format!("agent:{def}:archive:");
210 let seed = || gfs.append_lines_with_stamps_if_unused(&zone, OUTPUT_FILE, data, TSIDX_FILE, stamps, &archives);
211 let landed = match seed() {
212 Err(StoreError::NotFound) => {
213 match gfs.make_file(&zone, OUTPUT_FILE, FileMeta::default(), FileOpts::default()) {
214 Ok(()) | Err(StoreError::AlreadyExists) => {}
215 Err(e) => return Err(format!("make_file: {e}")),
216 }
217 seed()
218 }
219 other => other,
220 }
221 .map_err(|e| format!("seed: {e}"))?;
222 if landed.is_some() {
223 crate::backend::history_changed::mark();
224 }
225 Ok(landed)
226}
227
228fn append_transcript_lines(fs: &Arc<FileStore>, zone: &str, name: &str, data: &[u8], stamp: bool, what: &str, shared: bool) -> Option<AppendPos> {
239 use crate::backend::agent_session::TSIDX_FILE;
240 let append = || {
241 if stamp {
242 fs.append_lines_stamped(zone, name, data, TSIDX_FILE)
243 } else {
244 fs.append_lines(zone, name, data)
245 }
246 };
247 append_transcript_with(fs, zone, name, what, shared, &append)
248}
249
250fn append_transcript_with(
252 fs: &Arc<FileStore>,
253 zone: &str,
254 name: &str,
255 what: &str,
256 shared: bool,
257 append: &dyn Fn() -> Result<AppendPos, crate::backend::storage::error::StoreError>,
258) -> Option<AppendPos> {
259 use crate::backend::storage::error::StoreError;
260 use crate::backend::transcript::damage;
261 if shared && damage::is_damaged(zone) {
262 return None;
263 }
264 let failed = |e: &StoreError| {
265 if shared && damage::note_corrupt(zone, "append", e) {
266 return;
267 }
268 tracing::warn!(zone = %zone, error = %e, "{what}: append failed");
269 };
270 match append() {
271 Ok(pos) => return Some(pos),
272 Err(StoreError::NotFound) => {}
273 Err(e) => {
274 failed(&e);
275 return None;
276 }
277 }
278 if let Err(e) = fs.make_file(
279 zone,
280 name,
281 std::collections::HashMap::new(),
282 crate::backend::storage::filestore::FileOpts::default(),
283 ) {
284 if !matches!(e, StoreError::AlreadyExists) {
285 if !(shared && damage::note_corrupt(zone, "append", &e)) {
286 tracing::warn!(zone = %zone, error = %e, "{what}: make_file failed; skipping write");
287 }
288 return None;
289 }
290 }
291 append().map_err(|e| failed(&e)).ok()
292}
293
294pub(crate) fn append_transcript(
313 broker: Option<&mps::Broker>,
314 block_id: &str,
315 data: &[u8],
316 filestore: Option<&Arc<FileStore>>,
317 global: Option<(&Arc<FileStore>, &str)>,
318 stamp_tsidx: bool,
319 echo: Option<&str>,
320) {
321 let data = withhold::lines(data);
329 let records = crate::backend::storage::filestore::normalized_records(&data);
330 if records.is_empty() {
331 return;
332 }
333 let _order = transcript_order_lock(block_id);
334 if !stamp_tsidx {
335 append_lines_run(broker, block_id, &records, filestore, global, stamp_tsidx, echo);
336 return;
337 }
338 let global_only = global.is_some_and(|(_, zone)| is_defined_agent_zone(zone));
340 let targets = live::targets(block_id, filestore, global);
341 if let Some(left) = live::recover_once(block_id, &targets, global_only) {
342 if !left.is_empty() {
343 append_lines_run(broker, block_id, &left, filestore, global, stamp_tsidx, None);
344 }
345 }
346 for run in live::plan(block_id, &records) {
347 match run {
348 live::Run::Lines(lines) => append_lines_run(broker, block_id, &lines, filestore, global, stamp_tsidx, echo),
349 live::Run::Fragments(lines) => {
350 live::append_fragments(block_id, &targets, &lines, global_only);
351 publish_fragments(broker, block_id, &lines);
352 }
353 live::Run::ClearLive => {
354 live::clear(&targets);
355 live::clear_held_live(block_id);
356 }
357 }
358 }
359}
360
361fn publish_fragments(broker: Option<&mps::Broker>, block_id: &str, records: &[u8]) {
364 let Some(broker) = broker else { return };
365 let event_data = mps::WSFileEventData {
366 zoneid: block_id.to_string(),
367 filename: crate::backend::agent_session::OUTPUT_FILE.to_string(),
368 fileop: mps::FILE_OP_APPEND.to_string(),
369 data64: base64::engine::general_purpose::STANDARD.encode(records),
370 offset: None,
371 pos: Vec::new(),
372 echo: None,
373 };
374 broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
375}
376
377#[allow(clippy::too_many_arguments)]
380fn append_lines_run(
381 broker: Option<&mps::Broker>,
382 block_id: &str,
383 records: &[u8],
384 filestore: Option<&Arc<FileStore>>,
385 global: Option<(&Arc<FileStore>, &str)>,
386 stamp_tsidx: bool,
387 echo: Option<&str>,
388) {
389 use crate::backend::agent_session::OUTPUT_FILE;
390 let mut offset = None;
391 let mut pos = Vec::new();
392 let mut stored = false;
394 let global_only = global.is_some_and(|(_, zone)| is_defined_agent_zone(zone));
396 let mut global_pos = None;
397 if global_only {
398 if let Some((gfs, zone)) = global {
399 let mut held = live::take_unshared(block_id);
402 let mut caught_up = true;
403 if !held.is_empty() {
404 caught_up = mirror_append_to_global(gfs, zone, &held).is_some();
405 if caught_up {
406 held.clear();
407 }
408 }
409 global_pos = Some(if caught_up { mirror_append_to_global(gfs, zone, &records) } else { None });
410 if global_pos.as_ref().is_some_and(Option::is_none) {
411 held.extend_from_slice(&records);
413 }
414 live::put_unshared(block_id, gfs, zone, held);
415 }
416 }
417 let write_block_copy = !global_only || global_pos.as_ref().is_some_and(Option::is_none);
418 if let Some(fs) = filestore.filter(|_| write_block_copy) {
419 if let Some(p) = append_transcript_lines(fs, block_id, OUTPUT_FILE, &records, stamp_tsidx, "filestore", false) {
420 offset = Some(p.records_offset.max(0) as u64);
422 stored = true;
423 if let Some(c) = p.counted {
424 pos.push(mps::StreamPos { stream: format!("b:{block_id}"), gen: c.gen, line: c.first_line, lines: c.lines });
425 }
426 }
427 }
428 if let Some((gfs, zone)) = global {
429 let landed = match global_pos {
430 Some(done) => done,
431 None => mirror_append_to_global(gfs, zone, &records),
432 };
433 if echo.is_none() {
435 let at = landed.as_ref().map(|p| p.records_offset.max(0) as u64);
436 crate::backend::audit_activity::note_records(block_id, zone, &records, at);
437 crate::backend::token_ledger::note_records(zone, &records);
439 } else {
440 crate::backend::token_ledger::note_prompt(zone, &records);
442 }
443 stored |= landed.is_some();
444 if let Some(c) = landed.and_then(|p| p.counted) {
445 pos.push(mps::StreamPos { stream: format!("g:{zone}"), gen: c.gen, line: c.first_line, lines: c.lines });
446 }
447 }
448 crate::backend::viewer::audit::note_landed(block_id, &records, &pos, stored);
450
451 let event_data = mps::WSFileEventData {
452 zoneid: block_id.to_string(),
453 filename: OUTPUT_FILE.to_string(),
454 fileop: mps::FILE_OP_APPEND.to_string(),
455 data64: base64::engine::general_purpose::STANDARD.encode(&records),
456 offset,
457 pos,
458 echo: echo.map(str::to_string),
459 };
460 if let Some(broker) = broker {
462 broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
463 }
464}
465
466pub fn with_transcript_order<T>(block_id: &str, f: impl FnOnce() -> T) -> T {
474 let _order = transcript_order_lock(block_id);
475 f()
476}
477
478pub fn publish_transcript_changed(
484 broker: &mps::Broker,
485 block_id: &str,
486 fileop: &str,
487 filestore: &FileStore,
488 mstore: &crate::backend::storage::store::Store,
489) {
490 let source = crate::backend::transcript::source::TranscriptSource::resolve(filestore, mstore, block_id);
491 publish_transcript_changed_from(broker, block_id, fileop, filestore, &source);
492}
493
494pub(crate) fn publish_transcript_changed_from(
499 broker: &mps::Broker,
500 block_id: &str,
501 fileop: &str,
502 filestore: &FileStore,
503 source: &crate::backend::transcript::source::TranscriptSource<'_>,
504) {
505 use crate::backend::agent_session::OUTPUT_FILE;
506 let pos_in = |fs: &FileStore, zone: &str, stream: String| match fs.line_state(zone, OUTPUT_FILE) {
507 Ok(Some(state)) => state
508 .counted
509 .map(|c| vec![mps::StreamPos { stream, gen: c.gen, line: 0, lines: c.lines }])
510 .unwrap_or_default(),
511 _ => Vec::new(),
512 };
513 let mut pos = pos_in(filestore, block_id, format!("b:{block_id}"));
514 if pos.is_empty() && source.global {
515 pos = pos_in(source.fs, &source.zone, format!("g:{}", source.zone));
516 }
517 let event_data = mps::WSFileEventData {
518 zoneid: block_id.to_string(),
519 filename: OUTPUT_FILE.to_string(),
520 fileop: fileop.to_string(),
521 data64: String::new(),
522 offset: None,
523 pos,
524 echo: None,
525 };
526 broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
527}
528
529fn transcript_order_lock(block_id: &str) -> std::sync::MutexGuard<'static, ()> {
534 use std::hash::{Hash, Hasher};
535 const STRIPES: usize = 64;
536 static LOCKS: [std::sync::Mutex<()>; STRIPES] = [const { std::sync::Mutex::new(()) }; STRIPES];
537 let mut h = std::collections::hash_map::DefaultHasher::new();
538 block_id.hash(&mut h);
539 LOCKS[(h.finish() % STRIPES as u64) as usize]
540 .lock()
541 .unwrap_or_else(|poisoned| poisoned.into_inner())
542}
543
544pub fn resolve_global_output_zone(
550 mstore: &Option<Arc<crate::backend::storage::store::Store>>,
551 block_id: &str,
552) -> Option<String> {
553 let store = mstore.as_ref()?;
554 let block = store
555 .must_get::<crate::backend::obj::Block>(block_id)
556 .ok()?;
557 crate::backend::agent_session::agent_zone_for_block_meta(&block.meta)
558}
559
560#[cfg(test)]
561mod damage_tests {
562 use super::*;
563 use crate::backend::storage::filestore::{FileMeta, FileOpts};
564 use crate::backend::transcript::damage::{self, test_support};
565
566 const LINE: &[u8] = b"{\"type\":\"user\"}
567";
568
569 fn own_copy(own: &FileStore, block: &str) -> Vec<u8> {
570 own.read_file(block, "output").unwrap().unwrap_or_default()
571 }
572
573 #[test]
574 fn a_corrupt_error_on_the_shared_zone_marks_it_and_the_blocks_copy_keeps_the_line() {
575 for n in [1, 2] {
576 let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
577 test_support::corrupt(&gfs);
578 let (block, zone) = (format!("blk-damage-append-{n}"), format!("agent:damage-append-{n}:current"));
579 assert!(!damage::is_damaged(&zone));
580 append_transcript(None, &block, LINE, Some(&own), Some((&gfs, zone.as_str())), true, None);
581 assert!(damage::is_damaged(&zone), "attempt {n}: the first corrupt error marks the zone");
582 assert_eq!(own_copy(&own, &block), LINE, "attempt {n}: the block's copy has the line, so nothing is lost");
583 }
584 }
585
586 #[test]
587 fn a_damaged_zone_is_not_written_to_again_but_the_blocks_copy_is() {
588 let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
589 let (block, zone) = ("blk-damage-append-3", "agent:damage-append-3:current");
590 damage::note_corrupt(zone, "append", &StoreError::Sqlite(rusqlite::Error::SqliteFailure(
592 rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT),
593 None,
594 )));
595 use crate::backend::storage::error::StoreError;
596 append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
597 append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
598 assert!(gfs.stat(zone, "output").unwrap().is_none(), "nothing was sent to the shared store");
599 assert_eq!(own_copy(&own, block), [LINE, LINE].concat());
600 assert!(mirror_append_to_global(&gfs, zone, LINE).is_none());
601 }
602
603 #[test]
604 fn a_zone_that_is_not_damaged_is_written_as_before() {
605 let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
606 let (block, zone) = ("blk-damage-append-4", "agent:damage-append-4:current");
607 gfs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
608 append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
609 assert_eq!(gfs.read_file(zone, "output").unwrap().unwrap(), LINE);
610 assert!(!damage::is_damaged(zone));
611 }
612}
613
614#[cfg(test)]
616mod withhold_tests {
617 use super::*;
618 use crate::backend::message_origin::{MessageOrigin, RecordOrigin};
619 use crate::backend::storage::store::Store;
620 use serde_json::json;
621
622 const KEY: &str = "canary-instance-key-7741-QzXw";
623 const TOKEN: &str = "canary-agent-token-9082-LmNo";
624 const VAULT: &str = "canary-vault-value-5513-RsTu";
625
626 fn seed() {
627 for value in [KEY, TOKEN, VAULT] {
628 withhold::register(value);
629 }
630 }
631
632 fn user_line(text: &str) -> Vec<u8> {
633 format!("{}\n", json!({ "type": "user", "message": { "role": "user", "content": text } })).into_bytes()
634 }
635
636 fn stored(fs: &FileStore, zone: &str) -> String {
637 String::from_utf8(fs.read_file(zone, "output").unwrap().unwrap_or_default()).unwrap()
638 }
639
640 #[test]
641 fn nothing_srv_holds_secret_reaches_a_stored_transcript_by_any_writer() {
642 seed();
643 let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
644 let (block, zone) = ("blk-withhold-all", "agent:withhold-all:current");
645 let broker = mps::Broker::new();
646 for line in [
648 json!({ "type": "user", "message": { "role": "user", "content": [{ "type": "tool_result", "tool_use_id": "t1", "content": format!("AUTH={KEY}\nAGENT={TOKEN}") }] } }),
649 json!({ "type": "assistant", "message": { "content": [{ "type": "text", "text": format!("the key is {VAULT}") }] } }),
650 json!({ "type": "stream_event", "event": { "delta": { "text": VAULT } } }),
651 ] {
652 append_agent_output_line(&broker, block, &line.to_string(), Some(&own), Some(zone), origin_sig::WriterRuntime::Host);
653 }
654 let origin = RecordOrigin::new(MessageOrigin::user());
656 persist_user_line(None, block, &user_line(&format!("use {KEY}")), Some(&own), Some(zone), Some(&origin));
657 persist_injected_user_line(None, block, &user_line(&format!("note {TOKEN}")), Some(&own), Some(zone), Some(&origin));
658 append_transcript(None, block, &user_line(&format!("raw {VAULT}")), Some(&own), Some((&gfs, zone)), true, None);
660
661 for (what, text) in [("the block's copy", stored(&own, block)), ("the agent's zone", stored(&gfs, zone))] {
662 for canary in [KEY, TOKEN, VAULT] {
663 assert!(!text.contains(canary), "{what} holds {canary}");
664 }
665 }
666 let text = stored(&gfs, zone);
667 assert!(text.contains(withhold::MARK), "the agent's zone has the marks: {text}");
668 }
669
670 #[test]
671 fn a_record_srv_signed_still_verifies_with_a_value_withheld_from_its_words() {
672 seed();
673 let (fs, ms) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(Store::open_in_memory().unwrap()));
674 let block = "blk-withhold-sig";
675 let record = RecordOrigin::new(MessageOrigin::from_sender("agent1"));
676 persist_injected_user_line(None, block, &user_line(&format!("note {TOKEN}")), Some(&fs), None, Some(&record));
677 let read = crate::backend::transcript::tail::tail_lines(&ms, &fs, block, 10).unwrap().lines;
678 assert_eq!(read.len(), 1);
679 let line: serde_json::Value = serde_json::from_str(&read[0]).unwrap();
680 assert_eq!(line["amx"]["verified"], true, "the signature covers what is stored: {line}");
681 assert_eq!(line["message"]["content"], format!("note {}", withhold::MARK));
682 }
683
684 #[test]
685 fn a_line_with_nothing_to_withhold_is_stored_byte_for_byte() {
686 seed();
687 let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
688 let (block, zone) = ("blk-withhold-none", "agent:withhold-none:current");
689 let line = b"{\"type\":\"assistant\",\"message\":{\"content\":\"nothing secret\"}}\n";
690 append_transcript(None, block, line, Some(&own), Some((&gfs, zone)), true, None);
691 assert_eq!(stored(&own, block), "", "a defined agent's line is not also written to the block");
692 assert_eq!(stored(&gfs, zone).as_bytes(), line);
693 }
694}