@sokdak/happy-wire 0.1.0-main.5

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,404 @@
1
+ import * as z from 'zod';
2
+ import { isCuid, createId } from '@paralleldrive/cuid2';
3
+
4
+ const sessionRoleSchema = z.enum(["user", "agent"]);
5
+ const sessionTextEventSchema = z.object({
6
+ t: z.literal("text"),
7
+ text: z.string(),
8
+ thinking: z.boolean().optional()
9
+ });
10
+ const sessionUsageSchema = z.object({
11
+ input_tokens: z.number().int().nonnegative(),
12
+ cache_creation_input_tokens: z.number().int().nonnegative().optional(),
13
+ cache_read_input_tokens: z.number().int().nonnegative().optional(),
14
+ output_tokens: z.number().int().nonnegative(),
15
+ context_window: z.number().int().positive().optional(),
16
+ service_tier: z.string().optional()
17
+ }).passthrough();
18
+ const sessionServiceMessageEventSchema = z.object({
19
+ t: z.literal("service"),
20
+ text: z.string()
21
+ });
22
+ const sessionToolCallStartEventSchema = z.object({
23
+ t: z.literal("tool-call-start"),
24
+ call: z.string(),
25
+ name: z.string(),
26
+ title: z.string(),
27
+ description: z.string(),
28
+ args: z.record(z.string(), z.unknown())
29
+ });
30
+ const sessionToolCallEndEventSchema = z.object({
31
+ t: z.literal("tool-call-end"),
32
+ call: z.string()
33
+ });
34
+ const sessionFileEventSchema = z.object({
35
+ t: z.literal("file"),
36
+ ref: z.string(),
37
+ name: z.string(),
38
+ size: z.number(),
39
+ mimeType: z.string().optional(),
40
+ image: z.object({
41
+ width: z.number(),
42
+ height: z.number(),
43
+ thumbhash: z.string()
44
+ }).optional()
45
+ });
46
+ const sessionTurnStartEventSchema = z.object({
47
+ t: z.literal("turn-start")
48
+ });
49
+ const sessionStartEventSchema = z.object({
50
+ t: z.literal("start"),
51
+ title: z.string().optional()
52
+ });
53
+ const sessionTurnEndStatusSchema = z.enum(["completed", "failed", "cancelled"]);
54
+ const sessionTurnEndEventSchema = z.object({
55
+ t: z.literal("turn-end"),
56
+ status: sessionTurnEndStatusSchema
57
+ });
58
+ const sessionStopEventSchema = z.object({
59
+ t: z.literal("stop")
60
+ });
61
+ const sessionEventSchema = z.discriminatedUnion("t", [
62
+ sessionTextEventSchema,
63
+ sessionServiceMessageEventSchema,
64
+ sessionToolCallStartEventSchema,
65
+ sessionToolCallEndEventSchema,
66
+ sessionFileEventSchema,
67
+ sessionTurnStartEventSchema,
68
+ sessionStartEventSchema,
69
+ sessionTurnEndEventSchema,
70
+ sessionStopEventSchema
71
+ ]);
72
+ const sessionEnvelopeSchema = z.object({
73
+ id: z.string(),
74
+ time: z.number(),
75
+ role: sessionRoleSchema,
76
+ turn: z.string().optional(),
77
+ subagent: z.string().refine((value) => isCuid(value), {
78
+ message: "subagent must be a cuid2 value"
79
+ }).optional(),
80
+ // Underlying agent-protocol message id (e.g. Claude's `uuid` in the
81
+ // session JSONL). Set on text-bearing envelopes so the app can let
82
+ // users pick a precise rewind point for session fork / duplicate.
83
+ claudeUuid: z.string().min(1).optional(),
84
+ // Codex app-server item id for this envelope. Used as the precise
85
+ // rollback point for Codex thread duplicate/fork-from-message.
86
+ codexItemId: z.string().min(1).optional(),
87
+ // Optional model usage carried by the source agent message. Consumers use
88
+ // this to update session context meters without rendering a separate row.
89
+ usage: sessionUsageSchema.optional(),
90
+ ev: sessionEventSchema
91
+ }).superRefine((envelope, ctx) => {
92
+ if (envelope.ev.t === "service" && envelope.role !== "agent") {
93
+ ctx.addIssue({
94
+ code: z.ZodIssueCode.custom,
95
+ message: 'service events must use role "agent"',
96
+ path: ["role"]
97
+ });
98
+ }
99
+ if ((envelope.ev.t === "start" || envelope.ev.t === "stop") && envelope.role !== "agent") {
100
+ ctx.addIssue({
101
+ code: z.ZodIssueCode.custom,
102
+ message: `${envelope.ev.t} events must use role "agent"`,
103
+ path: ["role"]
104
+ });
105
+ }
106
+ });
107
+ function createEnvelope(role, ev, opts = {}) {
108
+ return sessionEnvelopeSchema.parse({
109
+ id: opts.id ?? createId(),
110
+ time: opts.time ?? Date.now(),
111
+ role,
112
+ ...opts.turn ? { turn: opts.turn } : {},
113
+ ...opts.subagent ? { subagent: opts.subagent } : {},
114
+ ...opts.claudeUuid ? { claudeUuid: opts.claudeUuid } : {},
115
+ ...opts.codexItemId ? { codexItemId: opts.codexItemId } : {},
116
+ ...opts.usage ? { usage: opts.usage } : {},
117
+ ev
118
+ });
119
+ }
120
+
121
+ const MessageMetaSchema = z.object({
122
+ sentFrom: z.string().optional(),
123
+ // Native clients may publish their own mode codes (for example Rig's
124
+ // auto/workspace_write/read_only/full_access), so this stays open-ended.
125
+ permissionMode: z.string().optional(),
126
+ model: z.string().nullable().optional(),
127
+ modelProviderId: z.string().optional(),
128
+ fallbackModel: z.string().nullable().optional(),
129
+ customSystemPrompt: z.string().nullable().optional(),
130
+ appendSystemPrompt: z.string().nullable().optional(),
131
+ allowedTools: z.array(z.string()).nullable().optional(),
132
+ disallowedTools: z.array(z.string()).nullable().optional(),
133
+ effort: z.string().nullable().optional(),
134
+ displayText: z.string().optional()
135
+ });
136
+
137
+ const UserMessageSchema = z.object({
138
+ role: z.literal("user"),
139
+ content: z.object({
140
+ type: z.literal("text"),
141
+ text: z.string()
142
+ }),
143
+ localKey: z.string().optional(),
144
+ meta: MessageMetaSchema.optional()
145
+ });
146
+ const AgentMessageSchema = z.object({
147
+ role: z.literal("agent"),
148
+ content: z.object({
149
+ type: z.string()
150
+ }).passthrough(),
151
+ meta: MessageMetaSchema.optional()
152
+ });
153
+ const LegacyMessageContentSchema = z.discriminatedUnion("role", [UserMessageSchema, AgentMessageSchema]);
154
+
155
+ const SessionMessageContentSchema = z.object({
156
+ c: z.string(),
157
+ t: z.literal("encrypted")
158
+ });
159
+ const SessionMessageSchema = z.object({
160
+ id: z.string(),
161
+ seq: z.number(),
162
+ localId: z.string().nullish(),
163
+ content: SessionMessageContentSchema,
164
+ createdAt: z.number(),
165
+ updatedAt: z.number()
166
+ });
167
+ const SessionProtocolMessageSchema = z.object({
168
+ role: z.literal("session"),
169
+ content: sessionEnvelopeSchema,
170
+ meta: MessageMetaSchema.optional()
171
+ });
172
+ const MessageContentSchema = z.discriminatedUnion("role", [
173
+ UserMessageSchema,
174
+ AgentMessageSchema,
175
+ SessionProtocolMessageSchema
176
+ ]);
177
+ const VersionedEncryptedValueSchema = z.object({
178
+ version: z.number(),
179
+ value: z.string()
180
+ });
181
+ const VersionedNullableEncryptedValueSchema = z.object({
182
+ version: z.number(),
183
+ value: z.string().nullable()
184
+ });
185
+ const UpdateNewMessageBodySchema = z.object({
186
+ t: z.literal("new-message"),
187
+ sid: z.string(),
188
+ message: SessionMessageSchema
189
+ });
190
+ const UpdateSessionBodySchema = z.object({
191
+ t: z.literal("update-session"),
192
+ id: z.string(),
193
+ metadata: VersionedEncryptedValueSchema.nullish(),
194
+ agentState: VersionedNullableEncryptedValueSchema.nullish()
195
+ });
196
+ const VersionedMachineEncryptedValueSchema = z.object({
197
+ version: z.number(),
198
+ value: z.string()
199
+ });
200
+ const UpdateMachineBodySchema = z.object({
201
+ t: z.literal("update-machine"),
202
+ machineId: z.string(),
203
+ metadata: VersionedMachineEncryptedValueSchema.nullish(),
204
+ daemonState: VersionedMachineEncryptedValueSchema.nullish(),
205
+ active: z.boolean().optional(),
206
+ activeAt: z.number().optional()
207
+ });
208
+ const CoreUpdateBodySchema = z.discriminatedUnion("t", [
209
+ UpdateNewMessageBodySchema,
210
+ UpdateSessionBodySchema,
211
+ UpdateMachineBodySchema
212
+ ]);
213
+ const CoreUpdateContainerSchema = z.object({
214
+ id: z.string(),
215
+ seq: z.number(),
216
+ body: CoreUpdateBodySchema,
217
+ createdAt: z.number()
218
+ });
219
+ const ApiMessageSchema = SessionMessageSchema;
220
+ const ApiUpdateNewMessageSchema = UpdateNewMessageBodySchema;
221
+ const ApiUpdateSessionStateSchema = UpdateSessionBodySchema;
222
+ const ApiUpdateMachineStateSchema = UpdateMachineBodySchema;
223
+ const UpdateBodySchema = UpdateNewMessageBodySchema;
224
+ const UpdateSchema = CoreUpdateContainerSchema;
225
+
226
+ const TASK_NOTIFICATION_OPEN = "<task-notification>";
227
+ const TASK_NOTIFICATION_CLOSE = "</task-notification>";
228
+ function leadingTaskNotificationEnd(text) {
229
+ if (!text.startsWith(TASK_NOTIFICATION_OPEN)) {
230
+ return null;
231
+ }
232
+ let depth = 1;
233
+ let cursor = TASK_NOTIFICATION_OPEN.length;
234
+ while (depth > 0) {
235
+ const nextOpen = text.indexOf(TASK_NOTIFICATION_OPEN, cursor);
236
+ const nextClose = text.indexOf(TASK_NOTIFICATION_CLOSE, cursor);
237
+ if (nextClose === -1) {
238
+ return null;
239
+ }
240
+ if (nextOpen !== -1 && nextOpen < nextClose) {
241
+ depth += 1;
242
+ cursor = nextOpen + TASK_NOTIFICATION_OPEN.length;
243
+ continue;
244
+ }
245
+ depth -= 1;
246
+ cursor = nextClose + TASK_NOTIFICATION_CLOSE.length;
247
+ }
248
+ return cursor;
249
+ }
250
+ function stripLeadingTaskNotificationWrappers(text) {
251
+ let remainder = text.trimStart();
252
+ let stripped = false;
253
+ while (remainder.startsWith(TASK_NOTIFICATION_OPEN)) {
254
+ const wrapperEnd = leadingTaskNotificationEnd(remainder);
255
+ if (wrapperEnd === null) {
256
+ break;
257
+ }
258
+ stripped = true;
259
+ remainder = remainder.slice(wrapperEnd).trimStart();
260
+ }
261
+ return stripped ? remainder : text;
262
+ }
263
+
264
+ const VoiceConversationGrantedSchema = z.object({
265
+ allowed: z.literal(true),
266
+ conversationToken: z.string(),
267
+ conversationId: z.string(),
268
+ agentId: z.string(),
269
+ elevenUserId: z.string(),
270
+ usedSeconds: z.number(),
271
+ limitSeconds: z.number()
272
+ });
273
+ const VoiceConversationDeniedSchema = z.object({
274
+ allowed: z.literal(false),
275
+ reason: z.enum(["voice_hard_limit_reached", "subscription_required", "voice_conversation_limit_reached"]),
276
+ usedSeconds: z.number(),
277
+ limitSeconds: z.number(),
278
+ agentId: z.string()
279
+ });
280
+ const VoiceConversationResponseSchema = z.discriminatedUnion("allowed", [
281
+ VoiceConversationGrantedSchema,
282
+ VoiceConversationDeniedSchema
283
+ ]);
284
+ const VoiceUsageResponseSchema = z.object({
285
+ usedSeconds: z.number(),
286
+ limitSeconds: z.number(),
287
+ conversationCount: z.number(),
288
+ conversationLimit: z.number(),
289
+ elevenUserId: z.string()
290
+ });
291
+
292
+ const RigProviderSchema = z.object({
293
+ id: z.string(),
294
+ kind: z.string(),
295
+ name: z.string()
296
+ }).passthrough();
297
+ const RigModelSchema = z.object({
298
+ id: z.string(),
299
+ code: z.string(),
300
+ name: z.string(),
301
+ value: z.string(),
302
+ providerId: z.string(),
303
+ providerKind: z.string(),
304
+ providerName: z.string(),
305
+ provider: RigProviderSchema,
306
+ contextWindow: z.number().optional(),
307
+ serviceTiers: z.array(z.string()),
308
+ thinkingLevels: z.array(z.string()),
309
+ defaultThinkingLevel: z.string()
310
+ }).passthrough();
311
+ const RigOperatingModeKindSchema = z.string();
312
+ const RigOperatingModeSchema = z.object({
313
+ code: z.string(),
314
+ value: z.string(),
315
+ description: z.string(),
316
+ kind: RigOperatingModeKindSchema
317
+ }).passthrough();
318
+ const RigCapabilitiesSchema = z.object({
319
+ abort: z.boolean(),
320
+ attachments: z.object({
321
+ enabled: z.boolean(),
322
+ maxBytes: z.number(),
323
+ mediaTypes: z.array(z.string())
324
+ }).passthrough(),
325
+ files: z.object({
326
+ browse: z.boolean(),
327
+ read: z.boolean(),
328
+ search: z.boolean(),
329
+ write: z.boolean()
330
+ }).passthrough(),
331
+ modelSelection: z.boolean(),
332
+ reasoningSelection: z.boolean(),
333
+ permissionModeSelection: z.boolean(),
334
+ resume: z.boolean(),
335
+ rpcMethods: z.array(z.string()),
336
+ shell: z.boolean(),
337
+ steering: z.boolean()
338
+ }).passthrough();
339
+ const RigActivitySchema = z.object({
340
+ subagents: z.object({
341
+ running: z.number(),
342
+ queued: z.number(),
343
+ total: z.number()
344
+ }).passthrough(),
345
+ workflows: z.object({
346
+ running: z.number(),
347
+ total: z.number()
348
+ }).passthrough(),
349
+ processes: z.object({
350
+ running: z.number()
351
+ }).passthrough(),
352
+ tasks: z.object({
353
+ pending: z.number(),
354
+ inProgress: z.number(),
355
+ completed: z.number(),
356
+ total: z.number()
357
+ }).passthrough()
358
+ }).passthrough();
359
+ const RigMetadataV1Schema = z.object({
360
+ // Parse later additive revisions with the v1-compatible fields we know.
361
+ rigMetadataVersion: z.number().int().min(1),
362
+ client: z.object({
363
+ id: z.literal("rig"),
364
+ name: z.string(),
365
+ version: z.string()
366
+ }).passthrough(),
367
+ provider: RigProviderSchema,
368
+ providers: z.array(RigProviderSchema),
369
+ model: z.object({
370
+ providerId: z.string(),
371
+ id: z.string()
372
+ }).passthrough(),
373
+ models: z.array(RigModelSchema),
374
+ currentModelProviderId: z.string(),
375
+ currentModelCode: z.string(),
376
+ permissionMode: z.string(),
377
+ currentOperatingModeCode: z.string(),
378
+ operatingModes: z.array(RigOperatingModeSchema),
379
+ reasoning: z.object({
380
+ current: z.string().nullable(),
381
+ levels: z.array(z.string())
382
+ }).passthrough(),
383
+ currentThoughtLevelCode: z.string().optional(),
384
+ thoughtLevels: z.array(z.object({
385
+ code: z.string(),
386
+ value: z.string()
387
+ }).passthrough()),
388
+ session: z.object({
389
+ status: z.string(),
390
+ permissionMode: z.string(),
391
+ modelLocked: z.boolean(),
392
+ serviceTier: z.string().optional()
393
+ }).passthrough(),
394
+ capabilities: RigCapabilitiesSchema,
395
+ activity: RigActivitySchema,
396
+ mcpServers: z.array(z.object({
397
+ name: z.string(),
398
+ status: z.string()
399
+ }).passthrough()),
400
+ tools: z.array(z.string()),
401
+ skills: z.array(z.string())
402
+ }).passthrough();
403
+
404
+ export { AgentMessageSchema, ApiMessageSchema, ApiUpdateMachineStateSchema, ApiUpdateNewMessageSchema, ApiUpdateSessionStateSchema, CoreUpdateBodySchema, CoreUpdateContainerSchema, LegacyMessageContentSchema, MessageContentSchema, MessageMetaSchema, RigActivitySchema, RigCapabilitiesSchema, RigMetadataV1Schema, RigModelSchema, RigOperatingModeKindSchema, RigOperatingModeSchema, RigProviderSchema, SessionMessageContentSchema, SessionMessageSchema, SessionProtocolMessageSchema, UpdateBodySchema, UpdateMachineBodySchema, UpdateNewMessageBodySchema, UpdateSchema, UpdateSessionBodySchema, UserMessageSchema, VersionedEncryptedValueSchema, VersionedMachineEncryptedValueSchema, VersionedNullableEncryptedValueSchema, VoiceConversationDeniedSchema, VoiceConversationGrantedSchema, VoiceConversationResponseSchema, VoiceUsageResponseSchema, createEnvelope, sessionEnvelopeSchema, sessionEventSchema, sessionFileEventSchema, sessionRoleSchema, sessionServiceMessageEventSchema, sessionStartEventSchema, sessionStopEventSchema, sessionTextEventSchema, sessionToolCallEndEventSchema, sessionToolCallStartEventSchema, sessionTurnEndEventSchema, sessionTurnEndStatusSchema, sessionTurnStartEventSchema, sessionUsageSchema, stripLeadingTaskNotificationWrappers };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@sokdak/happy-wire",
3
+ "version": "0.1.0-main.5",
4
+ "description": "Shared message wire types and Zod schemas for Happy clients and services",
5
+ "author": "Kirill Dubovitskiy",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "homepage": "https://github.com/slopus/happy/tree/main/packages/happy-wire",
9
+ "bugs": "https://github.com/slopus/happy/issues",
10
+ "repository": "slopus/happy",
11
+ "main": "./dist/index.cjs",
12
+ "module": "./dist/index.mjs",
13
+ "types": "./dist/index.d.cts",
14
+ "exports": {
15
+ ".": {
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ },
20
+ "import": {
21
+ "types": "./dist/index.d.mts",
22
+ "default": "./dist/index.mjs"
23
+ }
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "package.json",
29
+ "README.md"
30
+ ],
31
+ "dependencies": {
32
+ "@paralleldrive/cuid2": "^2.2.2",
33
+ "zod": "^4.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": ">=20",
37
+ "pkgroll": "^2.14.2",
38
+ "release-it": "^19.0.6",
39
+ "shx": "^0.3.3",
40
+ "typescript": "5.9.3",
41
+ "vitest": "^3.2.4"
42
+ },
43
+ "publishConfig": {
44
+ "registry": "https://registry.npmjs.org",
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "typecheck": "tsc --noEmit",
49
+ "build": "shx rm -rf dist && tsc --noEmit && pkgroll",
50
+ "test": "$npm_execpath run build && vitest run",
51
+ "release": "npx --no-install release-it"
52
+ }
53
+ }