@roj-ai/shared 0.0.2

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.
Files changed (72) hide show
  1. package/dist/chat-protocol.d.ts +60 -0
  2. package/dist/chat-protocol.d.ts.map +1 -0
  3. package/dist/index.d.ts +13 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/lib/domain-utils.d.ts +16 -0
  6. package/dist/lib/domain-utils.d.ts.map +1 -0
  7. package/dist/lib/ids.d.ts +18 -0
  8. package/dist/lib/ids.d.ts.map +1 -0
  9. package/dist/lib/result.d.ts +26 -0
  10. package/dist/lib/result.d.ts.map +1 -0
  11. package/dist/projections/agent-detail-projection.d.ts +91 -0
  12. package/dist/projections/agent-detail-projection.d.ts.map +1 -0
  13. package/dist/projections/agent-registry.d.ts +16 -0
  14. package/dist/projections/agent-registry.d.ts.map +1 -0
  15. package/dist/projections/agent-tree-projection.d.ts +30 -0
  16. package/dist/projections/agent-tree-projection.d.ts.map +1 -0
  17. package/dist/projections/chat-debug.d.ts +34 -0
  18. package/dist/projections/chat-debug.d.ts.map +1 -0
  19. package/dist/projections/events.d.ts +9 -0
  20. package/dist/projections/events.d.ts.map +1 -0
  21. package/dist/projections/index.d.ts +22 -0
  22. package/dist/projections/index.d.ts.map +1 -0
  23. package/dist/projections/mailbox.d.ts +21 -0
  24. package/dist/projections/mailbox.d.ts.map +1 -0
  25. package/dist/projections/metrics.d.ts +30 -0
  26. package/dist/projections/metrics.d.ts.map +1 -0
  27. package/dist/projections/protocol-status.d.ts +9 -0
  28. package/dist/projections/protocol-status.d.ts.map +1 -0
  29. package/dist/projections/services-projection.d.ts +24 -0
  30. package/dist/projections/services-projection.d.ts.map +1 -0
  31. package/dist/projections/session-info.d.ts +19 -0
  32. package/dist/projections/session-info.d.ts.map +1 -0
  33. package/dist/projections/timeline.d.ts +26 -0
  34. package/dist/projections/timeline.d.ts.map +1 -0
  35. package/dist/projections/types.d.ts +182 -0
  36. package/dist/projections/types.d.ts.map +1 -0
  37. package/dist/rpc/client.d.ts +79 -0
  38. package/dist/rpc/client.d.ts.map +1 -0
  39. package/dist/rpc/index.d.ts +9 -0
  40. package/dist/rpc/index.d.ts.map +1 -0
  41. package/dist/src/api-types.d.ts +8 -0
  42. package/dist/src/index.d.ts +17 -0
  43. package/dist/src/rpc/admin-methods.d.ts +99 -0
  44. package/dist/src/rpc/client.d.ts +26 -0
  45. package/dist/src/rpc/definition.d.ts +39 -0
  46. package/dist/src/rpc/instance-methods.d.ts +94 -0
  47. package/dist/src/rpc/methods.d.ts +260 -0
  48. package/dist/src/rpc/server.d.ts +21 -0
  49. package/dist/src/workspace-config.d.ts +16 -0
  50. package/dist/tsconfig.tsbuildinfo +1 -0
  51. package/package.json +36 -0
  52. package/src/chat-protocol.ts +46 -0
  53. package/src/globals.d.ts +3 -0
  54. package/src/index.ts +82 -0
  55. package/src/lib/domain-utils.ts +26 -0
  56. package/src/lib/ids.ts +19 -0
  57. package/src/lib/result.ts +35 -0
  58. package/src/projections/agent-detail-projection.ts +623 -0
  59. package/src/projections/agent-registry.ts +37 -0
  60. package/src/projections/agent-tree-projection.ts +229 -0
  61. package/src/projections/chat-debug.ts +260 -0
  62. package/src/projections/events.ts +10 -0
  63. package/src/projections/index.ts +59 -0
  64. package/src/projections/mailbox.ts +113 -0
  65. package/src/projections/metrics.ts +111 -0
  66. package/src/projections/protocol-status.ts +23 -0
  67. package/src/projections/services-projection.ts +89 -0
  68. package/src/projections/session-info.ts +47 -0
  69. package/src/projections/timeline.ts +228 -0
  70. package/src/projections/types.ts +237 -0
  71. package/src/rpc/client.ts +188 -0
  72. package/src/rpc/index.ts +14 -0
@@ -0,0 +1,237 @@
1
+ /**
2
+ * View model types for client-side projections.
3
+ */
4
+
5
+ import type {
6
+ AgentCounters,
7
+ AgentId,
8
+ AgentPauseReason,
9
+ AskUserInputType,
10
+ ChatMessageId,
11
+ DomainEvent,
12
+ LLMCallId,
13
+ MessageId,
14
+ ProtocolAgentStatus,
15
+ ToolCallId,
16
+ } from '@roj-ai/sdk'
17
+
18
+ // ============================================================================
19
+ // Debug view types (computed client-side from SessionState)
20
+ // ============================================================================
21
+
22
+ /**
23
+ * Agent tree node for visualization.
24
+ */
25
+ export interface AgentTreeNode {
26
+ id: AgentId
27
+ definitionName: string
28
+ status: ProtocolAgentStatus
29
+ parentId: AgentId | null
30
+ children: AgentTreeNode[]
31
+ mailboxCount: number
32
+ pendingToolCalls: number
33
+ isExecuting: boolean
34
+ cost: number
35
+ }
36
+
37
+ /**
38
+ * Agent detail response - computed client-side from SessionState.
39
+ */
40
+ export interface GetAgentDetailResponse {
41
+ id: AgentId
42
+ definitionName: string
43
+ status: ProtocolAgentStatus
44
+ parentId: AgentId | null
45
+ mailbox: MailboxMessageView[]
46
+ conversationHistory: ConversationMessageView[]
47
+ pendingToolCalls: ToolCallView[]
48
+ counters: AgentCounters
49
+ loadedSkills: { id: string; name: string; loadedAt: number }[]
50
+ cost: number
51
+ typedInput?: unknown
52
+ pauseReason?: AgentPauseReason
53
+ pauseMessage?: string
54
+ }
55
+
56
+ export interface MailboxMessageView {
57
+ id: MessageId
58
+ from: string // Can be AgentId, WorkerId, "user", or system role
59
+ content: string
60
+ timestamp: number
61
+ consumed: boolean
62
+ }
63
+
64
+ export type ConversationMessageView =
65
+ | UserConversationMessageView
66
+ | AssistantConversationMessageView
67
+ | ToolConversationMessageView
68
+ | SystemConversationMessageView
69
+
70
+ export interface UserConversationMessageView {
71
+ role: 'user'
72
+ content: string
73
+ fullContent: string
74
+ timestamp?: number
75
+ }
76
+
77
+ export interface AssistantConversationMessageView {
78
+ role: 'assistant'
79
+ content: string
80
+ fullContent: string
81
+ toolCalls?: { id: ToolCallId; name: string; input: unknown }[]
82
+ timestamp?: number
83
+ cost?: number
84
+ llmCallId?: LLMCallId
85
+ promptTokens?: number
86
+ cachedTokens?: number
87
+ cacheWriteTokens?: number
88
+ }
89
+
90
+ export interface ToolConversationMessageView {
91
+ role: 'tool'
92
+ toolCallId: ToolCallId
93
+ content: string
94
+ fullContent: string
95
+ isError: boolean
96
+ timestamp?: number
97
+ }
98
+
99
+ export interface SystemConversationMessageView {
100
+ role: 'system'
101
+ content: string
102
+ fullContent: string
103
+ timestamp?: number
104
+ }
105
+
106
+ export interface ToolCallView {
107
+ id: ToolCallId
108
+ name: string
109
+ input: unknown
110
+ status: 'pending' | 'executing' | 'completed' | 'failed'
111
+ result?: unknown
112
+ error?: string
113
+ }
114
+
115
+ // ============================================================================
116
+ // Events response type
117
+ // ============================================================================
118
+
119
+ /**
120
+ * Events response - used by sessions.getEvents RPC method.
121
+ */
122
+ export interface GetEventsResponse {
123
+ events: DomainEvent[]
124
+ total: number
125
+ lastIndex: number
126
+ }
127
+
128
+ // ============================================================================
129
+ // Metrics types
130
+ // ============================================================================
131
+
132
+ /**
133
+ * Metrics view - computed client-side from events.
134
+ */
135
+ export interface ProviderMetrics {
136
+ llmCalls: number
137
+ totalTokens: number
138
+ promptTokens: number
139
+ completionTokens: number
140
+ totalCost: number
141
+ }
142
+
143
+ export interface GetMetricsResponse {
144
+ totalTokens: number
145
+ promptTokens: number
146
+ completionTokens: number
147
+ totalCost?: number
148
+ llmCalls: number
149
+ toolCalls: number
150
+ agentCount: number
151
+ durationMs: number
152
+ byProvider: Record<string, ProviderMetrics>
153
+ }
154
+
155
+ // ============================================================================
156
+ // Timeline types
157
+ // ============================================================================
158
+
159
+ /**
160
+ * Timeline item representing an LLM call, tool execution, or context compaction.
161
+ */
162
+ export interface TimelineItem {
163
+ id: string
164
+ type: 'llm' | 'tool' | 'compaction'
165
+ agentId: AgentId
166
+ agentName: string
167
+ startedAt: number
168
+ completedAt?: number
169
+ durationMs?: number
170
+ status: 'running' | 'success' | 'error'
171
+ // LLM specific
172
+ model?: string
173
+ promptTokens?: number
174
+ completionTokens?: number
175
+ cachedTokens?: number
176
+ cacheWriteTokens?: number
177
+ cost?: number
178
+ llmCallId?: LLMCallId
179
+ // Tool specific
180
+ toolName?: string
181
+ toolCallId?: ToolCallId
182
+ toolInput?: unknown
183
+ toolResult?: unknown
184
+ // Compaction specific
185
+ originalTokens?: number
186
+ compactedTokens?: number
187
+ messagesRemoved?: number
188
+ // Error
189
+ error?: string
190
+ }
191
+
192
+ // ============================================================================
193
+ // Global mailbox types
194
+ // ============================================================================
195
+
196
+ /**
197
+ * Message in the global mailbox view.
198
+ */
199
+ export interface GlobalMailboxMessage {
200
+ id: MessageId
201
+ fromAgentId: string // Can be AgentId, "user", or system role
202
+ fromAgentName: string
203
+ toAgentId: AgentId
204
+ toAgentName: string
205
+ content: string
206
+ timestamp: number
207
+ consumed: boolean
208
+ }
209
+
210
+ // ============================================================================
211
+ // Chat debug types
212
+ // ============================================================================
213
+
214
+ /**
215
+ * Debug chat message with links to related entities.
216
+ */
217
+ export interface DebugChatMessage {
218
+ // Base
219
+ type: 'user_message' | 'agent_message' | 'ask_user'
220
+ messageId: MessageId | ChatMessageId
221
+ content: string
222
+ timestamp: number
223
+ eventIndex: number
224
+
225
+ // Links
226
+ agentId?: AgentId
227
+ agentName?: string
228
+ llmCallId?: LLMCallId
229
+ toolCallId?: ToolCallId
230
+ mailboxMessageId?: MessageId
231
+
232
+ // Type-specific
233
+ format?: 'text' | 'markdown'
234
+ inputType?: AskUserInputType
235
+ answered?: boolean
236
+ answer?: unknown
237
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Type-safe RPC Client
3
+ *
4
+ * Provides a fully typed interface for calling RPC methods.
5
+ * All method names and input/output types are validated at compile time.
6
+ *
7
+ * Supports both single calls and batch calls:
8
+ * - Single: rpc.call("method", input) -> Result<output, RpcErrorInfo>
9
+ * - Batch: rpc.batch(b => [b.add("m1", i1), b.add("m2", i2)]) -> Result<[o1, o2], RpcErrorInfo>
10
+ */
11
+
12
+ import type { RpcInput, RpcMethodName, RpcOutput } from '@roj-ai/sdk/rpc'
13
+ import type { Result } from '../lib/result.js'
14
+ import { Err, Ok } from '../lib/result.js'
15
+
16
+ /**
17
+ * Structured error info from RPC responses.
18
+ */
19
+ export interface RpcErrorInfo {
20
+ type: string
21
+ message: string
22
+ details?: unknown
23
+ }
24
+
25
+ /**
26
+ * RPC error class for backwards compatibility.
27
+ */
28
+ export class RpcError extends Error {
29
+ constructor(
30
+ public status: number,
31
+ public error: RpcErrorInfo,
32
+ ) {
33
+ super(error.message)
34
+ this.name = 'RpcError'
35
+ }
36
+ }
37
+
38
+ /**
39
+ * RPC response envelope (new format).
40
+ */
41
+ interface RpcResponse {
42
+ ok: boolean
43
+ value?: unknown
44
+ error?: RpcErrorInfo
45
+ }
46
+
47
+ interface BatchResponse {
48
+ results?: Array<{ ok: boolean; value?: unknown; error?: RpcErrorInfo }>
49
+ ok?: boolean
50
+ error?: RpcErrorInfo
51
+ }
52
+
53
+ /**
54
+ * A typed marker for a batch call entry. Carries the output type at compile time.
55
+ */
56
+ export interface BatchEntry<_T> {
57
+ readonly method: string
58
+ readonly input: unknown
59
+ }
60
+
61
+ /**
62
+ * Batch call builder. Collects typed entries for a batch RPC request.
63
+ */
64
+ export class BatchBuilder {
65
+ add<M extends RpcMethodName>(method: M, input: RpcInput<M>): BatchEntry<RpcOutput<M>> {
66
+ return { method, input }
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Maps a tuple of BatchEntry<T> to a tuple of T.
72
+ */
73
+ type BatchResults<T extends readonly BatchEntry<unknown>[]> = {
74
+ [K in keyof T]: T[K] extends BatchEntry<infer R> ? R : never
75
+ }
76
+
77
+ /**
78
+ * Type-safe RPC client for calling server methods.
79
+ */
80
+ export class RpcClient {
81
+ private projectId: string | null = null
82
+
83
+ constructor(private baseUrl: string = '') {}
84
+
85
+ /**
86
+ * Get the base URL for non-RPC requests.
87
+ */
88
+ getBaseUrl(): string {
89
+ return this.baseUrl
90
+ }
91
+
92
+ /**
93
+ * Set the project ID for DO-based RPC calls.
94
+ * When set, the projectId is added as a query parameter to /rpc requests.
95
+ */
96
+ setProjectId(projectId: string | null): void {
97
+ this.projectId = projectId
98
+ }
99
+
100
+ /**
101
+ * Get the currently configured project ID.
102
+ */
103
+ getProjectId(): string | null {
104
+ return this.projectId
105
+ }
106
+
107
+ private getRpcUrl(): string {
108
+ let url = `${this.baseUrl}/rpc`
109
+ if (this.projectId) {
110
+ url += `?project=${encodeURIComponent(this.projectId)}`
111
+ }
112
+ return url
113
+ }
114
+
115
+ /**
116
+ * Call an RPC method with type-safe input and output.
117
+ */
118
+ async call<M extends RpcMethodName>(
119
+ method: M,
120
+ input: RpcInput<M>,
121
+ ): Promise<Result<RpcOutput<M>, RpcErrorInfo>> {
122
+ const response = await fetch(this.getRpcUrl(), {
123
+ method: 'POST',
124
+ headers: { 'Content-Type': 'application/json' },
125
+ body: JSON.stringify({ method, input }),
126
+ credentials: 'include',
127
+ })
128
+
129
+ const data = (await response.json()) as RpcResponse
130
+
131
+ // Transport error (non-200 for invalid JSON, missing method)
132
+ if (!response.ok) {
133
+ return Err(data.error ?? { type: 'transport_error', message: 'Request failed' })
134
+ }
135
+
136
+ // Application result
137
+ if (data.ok) {
138
+ return Ok(data.value as RpcOutput<M>)
139
+ }
140
+
141
+ return Err(data.error ?? { type: 'unknown_error', message: 'Unknown error' })
142
+ }
143
+
144
+ /**
145
+ * Execute multiple RPC calls as a batch.
146
+ */
147
+ async batch<const T extends readonly BatchEntry<unknown>[]>(
148
+ buildCalls: (b: BatchBuilder) => T,
149
+ ): Promise<Result<BatchResults<T>, RpcErrorInfo>> {
150
+ const entries = buildCalls(new BatchBuilder())
151
+
152
+ const response = await fetch(this.getRpcUrl(), {
153
+ method: 'POST',
154
+ headers: { 'Content-Type': 'application/json' },
155
+ body: JSON.stringify({
156
+ batch: entries.map(e => ({ method: e.method, input: e.input })),
157
+ }),
158
+ credentials: 'include',
159
+ })
160
+
161
+ const data = (await response.json()) as BatchResponse
162
+
163
+ // Transport error
164
+ if (!response.ok) {
165
+ return Err(data.error ?? { type: 'transport_error', message: 'Request failed' })
166
+ }
167
+
168
+ const results = data.results ?? []
169
+
170
+ // Check if any call in the batch failed
171
+ for (const entry of results) {
172
+ if (!entry.ok && entry.error) {
173
+ return Err(entry.error)
174
+ }
175
+ }
176
+
177
+ // If fewer results than entries, the batch was short-circuited by an error
178
+ if (results.length < entries.length) {
179
+ const lastResult = results[results.length - 1]
180
+ if (lastResult && !lastResult.ok && lastResult.error) {
181
+ return Err(lastResult.error)
182
+ }
183
+ return Err({ type: 'batch_incomplete', message: 'Batch execution was interrupted' })
184
+ }
185
+
186
+ return Ok(results.map(r => r.value) as BatchResults<T>)
187
+ }
188
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * RPC Module - Shared re-exports for client/CLI consumers.
3
+ */
4
+
5
+ // Client
6
+ export { BatchBuilder, type BatchEntry, RpcClient, RpcError, type RpcErrorInfo } from './client.js'
7
+
8
+ // Result types
9
+ export { Err, flatMapResult, isErr, isOk, mapResult, Ok, unwrapOr, unwrapOrThrow } from '../lib/result.js'
10
+ export type { Result } from '../lib/result.js'
11
+
12
+ // Type-only re-exports from agent-server (zero runtime cost)
13
+ export type { RpcInput, RpcMethodDef, RpcMethodName, RpcMethods, RpcOutput } from '@roj-ai/sdk/rpc'
14
+ export type { AgentChatMessage, AskUserChatMessage, ChatMessage, UserChatMessage } from '@roj-ai/sdk/rpc'