File size: 2,044 Bytes
7c5ed63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Hono } from 'hono';
import { join } from 'node:path';

import { KIMI_CODE_HOME } from '../config';
import { isSafeAgentId, readSessionDetail } from '../lib/session-store';
import { rehydrateWireEntries } from '../lib/blob-resolver';
import { readAgentWire } from '../lib/wire-reader';
import { projectContext } from '../lib/context-projector';

export function contextRoute(home: string = KIMI_CODE_HOME): Hono {
  const r = new Hono();
  r.get('/:id/context', async (c) => {
    const id = c.req.param('id');
    const agentId = c.req.query('agent') ?? 'main';
    if (!isSafeAgentId(agentId)) {
      return c.json({ error: 'invalid agent id', code: 'BAD_REQUEST' }, 400);
    }
    const detail = await readSessionDetail(home, id);
    if (!detail) {
      return c.json({ error: 'session not found', code: 'NOT_FOUND' }, 404);
    }
    const agent = detail.agents.find((a) => a.agentId === agentId);
    if (!agent || !agent.wireExists) {
      return c.json({ error: 'agent wire not found', code: 'NOT_FOUND' }, 404);
    }
    try {
      const wire = await readAgentWire(
        join(detail.sessionDir, 'agents', agentId, 'wire.jsonl'),
      );
      const baseUrl = new URL(c.req.url).origin;
      rehydrateWireEntries(wire.records, id, agentId, baseUrl);
      // `?history=full` reconstructs the FULL pre-compaction/undo/clear history
      // for debugging; the default mirrors the model's-eye post-compaction view.
      const mode = c.req.query('history') === 'full' ? 'full' : 'model';
      const proj = projectContext(wire.records, mode);
      return c.json({
        sessionId: id,
        agentId,
        messages: proj.messages,
        usage: proj.usage,
        contextTokens: proj.contextTokens,
        config: proj.config,
        permission: proj.permission,
        planMode: proj.planMode,
        goal: proj.goal,
        swarm: proj.swarm,
      });
    } catch (err) {
      const msg = (err as Error).message;
      return c.json({ error: msg, code: 'READ_ERROR' }, 500);
    }
  });
  return r;
}