@honcho-ai/claude-honcho 0.3.3 → 0.4.0

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 (36) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +111 -335
  3. package/dist/hooks/pre-tool-honcho.js +551 -605
  4. package/dist/hooks/pre-tool-honcho.js.map +11 -9
  5. package/dist/hooks/save-user-message.js +1741 -1057
  6. package/dist/hooks/save-user-message.js.map +24 -19
  7. package/dist/hooks/session-end.js +559 -617
  8. package/dist/hooks/session-end.js.map +11 -9
  9. package/dist/hooks/session-start.js +1938 -1304
  10. package/dist/hooks/session-start.js.map +31 -22
  11. package/dist/hooks/stop.js +1785 -1157
  12. package/dist/hooks/stop.js.map +25 -19
  13. package/dist/hooks/user-prompt.js +696 -16571
  14. package/dist/hooks/user-prompt.js.map +13 -90
  15. package/dist/mcp-server.js +1689 -1676
  16. package/dist/mcp-server.js.map +23 -20
  17. package/dist/skills/backfill-runner.js +1824 -911
  18. package/dist/skills/backfill-runner.js.map +27 -20
  19. package/dist/skills/{setup-runner.js → pane-runner.js} +1910 -1020
  20. package/dist/{hooks/pre-compact.js.map → skills/pane-runner.js.map} +28 -24
  21. package/dist/skills/status-runner.js +1568 -753
  22. package/dist/skills/status-runner.js.map +23 -19
  23. package/hooks/hooks.json +10 -42
  24. package/hooks/register.tsx +574 -0
  25. package/package.json +1 -1
  26. package/skills/insights/SKILL.md +3 -7
  27. package/dist/hooks/post-tool-use.js +0 -16905
  28. package/dist/hooks/post-tool-use.js.map +0 -97
  29. package/dist/hooks/pre-compact.js +0 -17087
  30. package/dist/skills/setup-runner.js.map +0 -95
  31. package/scripts/honcho-statusline.sh +0 -101
  32. package/skills/briefing/SKILL.md +0 -20
  33. package/skills/config/SKILL.md +0 -288
  34. package/skills/import/SKILL.md +0 -73
  35. package/skills/setup/SKILL.md +0 -60
  36. package/skills/status/SKILL.md +0 -30
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ // @bun
2
3
  var __create = Object.create;
3
4
  var __getProtoOf = Object.getPrototypeOf;
4
5
  var __defProp = Object.defineProperty;
@@ -36,8 +37,9 @@ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports,
36
37
  // node_modules/@honcho-ai/sdk/dist/api-version.js
37
38
  var require_api_version = __commonJS(function(exports) {
38
39
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.API_VERSION = undefined;
40
+ exports.VERSION = exports.API_VERSION = undefined;
40
41
  exports.API_VERSION = "v3";
42
+ exports.VERSION = "2.9.0";
41
43
  });
42
44
 
43
45
  // node_modules/@honcho-ai/sdk/dist/http/errors.js
@@ -162,255 +164,6 @@ var require_errors = __commonJS(function(exports) {
162
164
  }
163
165
  });
164
166
 
165
- // node_modules/@honcho-ai/sdk/dist/http/client.js
166
- var require_client = __commonJS(function(exports) {
167
- Object.defineProperty(exports, "__esModule", { value: true });
168
- exports.HonchoHTTPClient = undefined;
169
- var errors_1 = require_errors();
170
- var DEFAULT_TIMEOUT = 60000;
171
- var DEFAULT_MAX_RETRIES = 2;
172
- var RETRY_STATUS_CODES = [429, 500, 502, 503, 504];
173
- var INITIAL_RETRY_DELAY = 500;
174
-
175
- class HonchoHTTPClient {
176
- constructor(config) {
177
- this.baseURL = config.baseURL.replace(/\/$/, "");
178
- this.apiKey = config.apiKey;
179
- this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
180
- this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
181
- this.defaultHeaders = {
182
- "Content-Type": "application/json",
183
- ...config.defaultHeaders
184
- };
185
- this.defaultQuery = config.defaultQuery;
186
- }
187
- async request(method, path, options = {}) {
188
- const url = this.buildURL(path, options.query);
189
- const headers = this.buildHeaders(options.headers);
190
- const timeout = options.timeout ?? this.timeout;
191
- let lastError;
192
- let attempt = 0;
193
- while (attempt <= this.maxRetries) {
194
- try {
195
- const response = await this.fetchWithTimeout(url, {
196
- method,
197
- headers,
198
- body: options.body ? JSON.stringify(options.body) : undefined,
199
- signal: options.signal
200
- }, timeout);
201
- if (response.ok) {
202
- const text = await response.text();
203
- if (!text) {
204
- return;
205
- }
206
- return JSON.parse(text);
207
- }
208
- const errorBody = await this.parseErrorBody(response);
209
- const retryAfter = this.parseRetryAfter(response);
210
- const error = (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody, retryAfter);
211
- if (RETRY_STATUS_CODES.includes(response.status) && attempt < this.maxRetries) {
212
- lastError = error;
213
- await this.sleep(this.getRetryDelay(attempt, retryAfter));
214
- attempt++;
215
- continue;
216
- }
217
- throw error;
218
- } catch (error) {
219
- if (error instanceof errors_1.TimeoutError || error instanceof errors_1.ConnectionError) {
220
- if (attempt < this.maxRetries) {
221
- lastError = error;
222
- await this.sleep(this.getRetryDelay(attempt));
223
- attempt++;
224
- continue;
225
- }
226
- }
227
- if (error instanceof errors_1.RateLimitError || error instanceof errors_1.ServerError || error instanceof errors_1.TimeoutError || error instanceof errors_1.ConnectionError) {
228
- throw error;
229
- }
230
- if (error instanceof TypeError && error.message.includes("fetch")) {
231
- const connError = new errors_1.ConnectionError(error.message);
232
- if (attempt < this.maxRetries) {
233
- lastError = connError;
234
- await this.sleep(this.getRetryDelay(attempt));
235
- attempt++;
236
- continue;
237
- }
238
- throw connError;
239
- }
240
- throw error;
241
- }
242
- }
243
- throw lastError || new Error("Request failed after retries");
244
- }
245
- async get(path, options) {
246
- return this.request("GET", path, options);
247
- }
248
- async post(path, options) {
249
- return this.request("POST", path, options);
250
- }
251
- async put(path, options) {
252
- return this.request("PUT", path, options);
253
- }
254
- async patch(path, options) {
255
- return this.request("PATCH", path, options);
256
- }
257
- async delete(path, options) {
258
- return this.request("DELETE", path, options);
259
- }
260
- async stream(method, path, options = {}) {
261
- const url = this.buildURL(path, options.query);
262
- const headers = {
263
- ...this.buildHeaders(options.headers),
264
- Accept: "text/event-stream"
265
- };
266
- const timeout = options.timeout ?? this.timeout;
267
- const response = await this.fetchWithTimeout(url, {
268
- method,
269
- headers,
270
- body: options.body ? JSON.stringify(options.body) : undefined,
271
- signal: options.signal
272
- }, timeout);
273
- if (!response.ok) {
274
- const errorBody = await this.parseErrorBody(response);
275
- throw (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody);
276
- }
277
- return response;
278
- }
279
- async upload(path, formData, options = {}) {
280
- const url = this.buildURL(path, options.query);
281
- const headers = {};
282
- if (this.apiKey) {
283
- headers.Authorization = `Bearer ${this.apiKey}`;
284
- }
285
- if (options.headers) {
286
- Object.assign(headers, options.headers);
287
- }
288
- const timeout = options.timeout ?? this.timeout;
289
- const response = await this.fetchWithTimeout(url, {
290
- method: "POST",
291
- headers,
292
- body: formData,
293
- signal: options.signal
294
- }, timeout);
295
- if (!response.ok) {
296
- const errorBody = await this.parseErrorBody(response);
297
- throw (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody);
298
- }
299
- const text = await response.text();
300
- if (!text) {
301
- return;
302
- }
303
- return JSON.parse(text);
304
- }
305
- buildURL(path, query) {
306
- const url = new URL(path, this.baseURL);
307
- const mergedQuery = {
308
- ...this.defaultQuery ?? {},
309
- ...query ?? {}
310
- };
311
- for (const [key, value] of Object.entries(mergedQuery)) {
312
- if (value !== undefined) {
313
- url.searchParams.set(key, String(value));
314
- }
315
- }
316
- return url.toString();
317
- }
318
- buildHeaders(extra) {
319
- const headers = { ...this.defaultHeaders };
320
- if (this.apiKey) {
321
- headers.Authorization = `Bearer ${this.apiKey}`;
322
- }
323
- if (extra) {
324
- Object.assign(headers, extra);
325
- }
326
- return headers;
327
- }
328
- async fetchWithTimeout(url, init, timeout) {
329
- const controller = new AbortController;
330
- const timeoutId = setTimeout(() => controller.abort(), timeout);
331
- if (init.signal) {
332
- init.signal.addEventListener("abort", () => controller.abort());
333
- }
334
- try {
335
- const response = await fetch(url, {
336
- ...init,
337
- signal: controller.signal
338
- });
339
- return response;
340
- } catch (error) {
341
- if (error instanceof DOMException && error.name === "AbortError") {
342
- throw new errors_1.TimeoutError(`Request timed out after ${timeout}ms`);
343
- }
344
- throw error;
345
- } finally {
346
- clearTimeout(timeoutId);
347
- }
348
- }
349
- async parseErrorBody(response) {
350
- try {
351
- const body = await response.json();
352
- return {
353
- message: body.detail || body.message || body.error,
354
- ...body
355
- };
356
- } catch {
357
- return { message: `HTTP ${response.status}` };
358
- }
359
- }
360
- parseRetryAfter(response) {
361
- const header = response.headers.get("Retry-After");
362
- if (!header)
363
- return;
364
- const seconds = Number.parseInt(header, 10);
365
- if (!Number.isNaN(seconds)) {
366
- return seconds * 1000;
367
- }
368
- const date = Date.parse(header);
369
- if (!Number.isNaN(date)) {
370
- return Math.max(0, date - Date.now());
371
- }
372
- return;
373
- }
374
- getRetryDelay(attempt, retryAfter) {
375
- if (retryAfter) {
376
- return retryAfter;
377
- }
378
- return INITIAL_RETRY_DELAY * 2 ** attempt;
379
- }
380
- sleep(ms) {
381
- return new Promise((resolve) => setTimeout(resolve, ms));
382
- }
383
- }
384
- exports.HonchoHTTPClient = HonchoHTTPClient;
385
- });
386
-
387
- // node_modules/@honcho-ai/sdk/dist/message.js
388
- var require_message = __commonJS(function(exports) {
389
- Object.defineProperty(exports, "__esModule", { value: true });
390
- exports.Message = undefined;
391
-
392
- class Message {
393
- constructor(id, content, peerId, sessionId, workspaceId, metadata, createdAt, tokenCount) {
394
- this.id = id;
395
- this.content = content;
396
- this.peerId = peerId;
397
- this.sessionId = sessionId;
398
- this.workspaceId = workspaceId;
399
- this.metadata = metadata;
400
- this.createdAt = createdAt;
401
- this.tokenCount = tokenCount;
402
- }
403
- static fromApiResponse(data) {
404
- return new Message(data.id, data.content, data.peer_id, data.session_id, data.workspace_id, data.metadata, data.created_at, data.token_count);
405
- }
406
- toString() {
407
- const truncatedContent = this.content.length > 50 ? `${this.content.slice(0, 50)}...` : this.content;
408
- return `Message(id='${this.id}', peerId='${this.peerId}', content='${truncatedContent}')`;
409
- }
410
- }
411
- exports.Message = Message;
412
- });
413
-
414
167
  // node_modules/@honcho-ai/sdk/dist/pagination.js
415
168
  var require_pagination = __commonJS(function(exports) {
416
169
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -13690,9 +13443,10 @@ var require_zod = __commonJS(function(exports) {
13690
13443
  // node_modules/@honcho-ai/sdk/dist/validation.js
13691
13444
  var require_validation = __commonJS(function(exports) {
13692
13445
  Object.defineProperty(exports, "__esModule", { value: true });
13693
- exports.ConclusionQueryParamsSchema = exports.LimitSchema = exports.WorkspaceConfigSchema = exports.WorkspaceMetadataSchema = exports.MessageAdditionToApiSchema = exports.MessageAdditionSchema = exports.PeerRemovalSchema = exports.PeerAdditionToApiSchema = exports.PeerAdditionSchema = exports.PeerCardContentSchema = exports.CardTargetSchema = exports.PeerGetRepresentationParamsSchema = exports.GetRepresentationParamsSchema = exports.FileUploadSchema = exports.QueueStatusOptionsSchema = exports.ContextParamsSchema = exports.RepresentationOptionsSchema = exports.ChatQuerySchema = exports.FilterSchema = exports.SearchQueryLikeSchema = exports.SearchQueryObjectSchema = exports.SearchQuerySchema = exports.MessageInputSchema = exports.MessageConfigurationSchema = exports.MessageMetadataSchema = exports.MessageContentSchema = exports.SessionPeerConfigSchema = exports.SessionIdSchema = exports.SessionConfigSchema = exports.DreamConfigSchema = exports.SummaryConfigSchema = exports.PeerCardConfigSchema = exports.ReasoningConfigSchema = exports.SessionMetadataSchema = exports.PeerIdSchema = exports.PeerConfigSchema = exports.PeerMetadataSchema = exports.HonchoConfigSchema = exports.WorkspaceIdSchema = undefined;
13446
+ exports.ConclusionQueryParamsSchema = exports.LimitSchema = exports.WorkspaceConfigSchema = exports.WorkspaceMetadataSchema = exports.MessageAdditionToApiSchema = exports.MessageAdditionSchema = exports.PeerRemovalSchema = exports.PeerAdditionToApiSchema = exports.PeerAdditionSchema = exports.PeerCardContentSchema = exports.CardTargetSchema = exports.PeerGetRepresentationParamsSchema = exports.GetRepresentationParamsSchema = exports.FileUploadSchema = exports.QueueStatusOptionsSchema = exports.ContextParamsSchema = exports.RepresentationOptionsSchema = exports.ChatQuerySchema = exports.FilterSchema = exports.SearchQueryLikeSchema = exports.SearchQueryObjectSchema = exports.SearchQuerySchema = exports.MessageInputSchema = exports.MessageConfigurationSchema = exports.MessageMetadataSchema = exports.MessageContentSchema = exports.SessionPeerConfigSchema = exports.SessionAllowlistSchema = exports.SessionScopesSchema = exports.ScopeSessionsSchema = exports.ScopeOptionSchema = exports.ScopeIdSchema = exports.SessionIdSchema = exports.SessionConfigSchema = exports.DialecticConfigSchema = exports.DreamConfigSchema = exports.SummaryConfigSchema = exports.PeerCardConfigSchema = exports.ReasoningConfigSchema = exports.SessionMetadataSchema = exports.PeerIdSchema = exports.PeerConfigSchema = exports.PeerMetadataSchema = exports.HonchoConfigSchema = exports.WorkspaceIdSchema = undefined;
13694
13447
  exports.normalizeSearchQuery = normalizeSearchQuery;
13695
13448
  exports.normalizeListOptions = normalizeListOptions;
13449
+ exports.scopeRecallFields = scopeRecallFields;
13696
13450
  exports.peerConfigToApi = peerConfigToApi;
13697
13451
  exports.peerConfigFromApi = peerConfigFromApi;
13698
13452
  exports.workspaceConfigToApi = workspaceConfigToApi;
@@ -13702,7 +13456,7 @@ var require_validation = __commonJS(function(exports) {
13702
13456
  exports.messageConfigToApi = messageConfigToApi;
13703
13457
  exports.messageConfigFromApi = messageConfigFromApi;
13704
13458
  var zod_1 = require_zod();
13705
- exports.WorkspaceIdSchema = zod_1.z.string().min(1, "Workspace ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Workspace ID may only contain letters, numbers, underscores, and hyphens").max(100, "Workspace ID can be at most 100 characters");
13459
+ exports.WorkspaceIdSchema = zod_1.z.string().min(1, "Workspace ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Workspace ID may only contain letters, numbers, underscores, and hyphens").max(512, "Workspace ID can be at most 512 characters");
13706
13460
  exports.HonchoConfigSchema = zod_1.z.object({
13707
13461
  apiKey: zod_1.z.string().optional(),
13708
13462
  environment: zod_1.z.enum(["local", "production"]).optional(),
@@ -13717,7 +13471,7 @@ var require_validation = __commonJS(function(exports) {
13717
13471
  exports.PeerConfigSchema = zod_1.z.object({
13718
13472
  observeMe: zod_1.z.boolean().nullable().optional()
13719
13473
  }).strict();
13720
- exports.PeerIdSchema = zod_1.z.string().min(1, "Peer ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Peer ID may only contain letters, numbers, underscores, and hyphens").max(100, "Peer ID can be at most 100 characters");
13474
+ exports.PeerIdSchema = zod_1.z.string().min(1, "Peer ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Peer ID may only contain letters, numbers, underscores, and hyphens").max(512, "Peer ID can be at most 512 characters");
13721
13475
  var PeerIdObjectSchema = zod_1.z.object({ id: exports.PeerIdSchema });
13722
13476
  exports.SessionMetadataSchema = zod_1.z.record(zod_1.z.string(), zod_1.z.unknown());
13723
13477
  exports.ReasoningConfigSchema = zod_1.z.object({
@@ -13726,32 +13480,92 @@ var require_validation = __commonJS(function(exports) {
13726
13480
  }).strict();
13727
13481
  exports.PeerCardConfigSchema = zod_1.z.object({
13728
13482
  use: zod_1.z.boolean().nullable().optional(),
13729
- create: zod_1.z.boolean().nullable().optional()
13483
+ create: zod_1.z.boolean().nullable().optional(),
13484
+ customInstructions: zod_1.z.string().nullable().optional()
13730
13485
  }).strict();
13731
13486
  exports.SummaryConfigSchema = zod_1.z.object({
13732
13487
  enabled: zod_1.z.boolean().nullable().optional(),
13733
13488
  messagesPerShortSummary: zod_1.z.number().int().min(10).nullable().optional(),
13734
- messagesPerLongSummary: zod_1.z.number().int().min(20).nullable().optional()
13489
+ messagesPerLongSummary: zod_1.z.number().int().min(20).nullable().optional(),
13490
+ customInstructions: zod_1.z.string().nullable().optional()
13735
13491
  }).strict();
13736
13492
  exports.DreamConfigSchema = zod_1.z.object({
13737
- enabled: zod_1.z.boolean().nullable().optional()
13493
+ enabled: zod_1.z.boolean().nullable().optional(),
13494
+ customInstructions: zod_1.z.string().nullable().optional()
13495
+ }).strict();
13496
+ exports.DialecticConfigSchema = zod_1.z.object({
13497
+ customInstructions: zod_1.z.string().nullable().optional()
13738
13498
  }).strict();
13739
13499
  exports.SessionConfigSchema = zod_1.z.object({
13500
+ customInstructions: zod_1.z.string().nullable().optional(),
13740
13501
  reasoning: exports.ReasoningConfigSchema.nullable().optional(),
13741
13502
  peerCard: exports.PeerCardConfigSchema.nullable().optional(),
13742
13503
  summary: exports.SummaryConfigSchema.nullable().optional(),
13743
- dream: exports.DreamConfigSchema.nullable().optional()
13504
+ dream: exports.DreamConfigSchema.nullable().optional(),
13505
+ dialectic: exports.DialecticConfigSchema.nullable().optional()
13744
13506
  }).strict();
13745
- exports.SessionIdSchema = zod_1.z.string().min(1, "Session ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Session ID may only contain letters, numbers, underscores, and hyphens").max(100, "Session ID can be at most 100 characters");
13507
+ exports.SessionIdSchema = zod_1.z.string().min(1, "Session ID must be a non-empty string").regex(/^[a-zA-Z0-9_-]+$/, "Session ID may only contain letters, numbers, underscores, and hyphens").max(512, "Session ID can be at most 512 characters");
13746
13508
  var SessionIdObjectSchema = zod_1.z.object({ id: exports.SessionIdSchema });
13747
- exports.SessionPeerConfigSchema = zod_1.z.object({
13748
- observeMe: zod_1.z.boolean().nullable().optional(),
13749
- observeOthers: zod_1.z.boolean().nullable().optional()
13750
- }).strict();
13751
- exports.MessageContentSchema = zod_1.z.string().refine((content) => content === "" || content.trim().length > 0, "Message content cannot be only whitespace");
13752
- exports.MessageMetadataSchema = zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional();
13753
- exports.MessageConfigurationSchema = zod_1.z.object({
13754
- reasoning: exports.ReasoningConfigSchema.nullable().optional()
13509
+ var SCOPE_PEER_PREFIX = "scope.";
13510
+ var SCOPE_ID_MAX_LENGTH = 512 - SCOPE_PEER_PREFIX.length;
13511
+ function scopeIdIssues(value) {
13512
+ if (value.length < 1) {
13513
+ return ["Scope ID must be a non-empty string"];
13514
+ }
13515
+ if (value.length > SCOPE_ID_MAX_LENGTH) {
13516
+ return [`Scope ID can be at most ${SCOPE_ID_MAX_LENGTH} characters`];
13517
+ }
13518
+ if (value.startsWith(SCOPE_PEER_PREFIX)) {
13519
+ return [
13520
+ `Scope ID must not start with the reserved prefix '${SCOPE_PEER_PREFIX}' (scope IDs are unprefixed)`
13521
+ ];
13522
+ }
13523
+ if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
13524
+ return [
13525
+ "Scope ID may only contain letters, numbers, underscores, and hyphens"
13526
+ ];
13527
+ }
13528
+ return [];
13529
+ }
13530
+ function addScopeIdIssues(values, ctx) {
13531
+ for (const value of values) {
13532
+ for (const message of scopeIdIssues(value)) {
13533
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message });
13534
+ }
13535
+ }
13536
+ }
13537
+ exports.ScopeIdSchema = zod_1.z.string().superRefine((val, ctx) => {
13538
+ addScopeIdIssues([val], ctx);
13539
+ });
13540
+ var ScopeIdLikeSchema = zod_1.z.union([zod_1.z.string(), zod_1.z.object({ id: zod_1.z.string() })]);
13541
+ exports.ScopeOptionSchema = zod_1.z.union([ScopeIdLikeSchema, zod_1.z.array(ScopeIdLikeSchema)]).transform((val) => Array.isArray(val) ? val.map((entry) => typeof entry === "string" ? entry : entry.id) : typeof val === "string" ? val : val.id).superRefine((resolved, ctx) => {
13542
+ if (Array.isArray(resolved)) {
13543
+ if (resolved.length === 0) {
13544
+ ctx.addIssue({
13545
+ code: zod_1.z.ZodIssueCode.custom,
13546
+ message: "scope must name at least one scope"
13547
+ });
13548
+ }
13549
+ if (resolved.length > 100) {
13550
+ ctx.addIssue({
13551
+ code: zod_1.z.ZodIssueCode.custom,
13552
+ message: "scope can name at most 100 scopes"
13553
+ });
13554
+ }
13555
+ }
13556
+ addScopeIdIssues(Array.isArray(resolved) ? resolved : [resolved], ctx);
13557
+ });
13558
+ exports.ScopeSessionsSchema = zod_1.z.array(exports.SessionIdSchema).min(1, "At least one session must be given").max(100, "At most 100 sessions can be given per call");
13559
+ exports.SessionScopesSchema = zod_1.z.array(exports.ScopeIdSchema).min(1, "scopes must name at least one scope").max(100, "scopes can name at most 100 scopes");
13560
+ exports.SessionAllowlistSchema = zod_1.z.array(zod_1.z.union([exports.SessionIdSchema, SessionIdObjectSchema])).min(1, "sessions must name at least one session").max(1000, "sessions can name at most 1000 sessions").transform((vals) => vals.map((v) => typeof v === "string" ? v : v.id));
13561
+ exports.SessionPeerConfigSchema = zod_1.z.object({
13562
+ observeMe: zod_1.z.boolean().nullable().optional(),
13563
+ observeOthers: zod_1.z.boolean().nullable().optional()
13564
+ }).strict();
13565
+ exports.MessageContentSchema = zod_1.z.string().refine((content) => content === "" || content.trim().length > 0, "Message content cannot be only whitespace");
13566
+ exports.MessageMetadataSchema = zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional();
13567
+ exports.MessageConfigurationSchema = zod_1.z.object({
13568
+ reasoning: exports.ReasoningConfigSchema.nullable().optional()
13755
13569
  }).strict().nullable().optional();
13756
13570
  exports.MessageInputSchema = zod_1.z.object({
13757
13571
  peerId: exports.PeerIdSchema,
@@ -13791,12 +13605,41 @@ var require_validation = __commonJS(function(exports) {
13791
13605
  }
13792
13606
  return { filters: input };
13793
13607
  }
13608
+ function scopeRecallFields(options) {
13609
+ return {
13610
+ scope: options.scope,
13611
+ filters: options.sessions ? { session_id: options.sessions } : undefined
13612
+ };
13613
+ }
13614
+ function scopeExclusivityIssues(data, ctx) {
13615
+ if (data.scope === undefined) {
13616
+ return;
13617
+ }
13618
+ if (data.sessions !== undefined) {
13619
+ ctx.addIssue({
13620
+ code: zod_1.z.ZodIssueCode.custom,
13621
+ message: "scope and sessions are mutually exclusive",
13622
+ path: ["sessions"]
13623
+ });
13624
+ }
13625
+ if (data.session !== undefined) {
13626
+ ctx.addIssue({
13627
+ code: zod_1.z.ZodIssueCode.custom,
13628
+ message: "scope and session are mutually exclusive",
13629
+ path: ["session"]
13630
+ });
13631
+ }
13632
+ }
13794
13633
  exports.ChatQuerySchema = zod_1.z.object({
13795
13634
  query: exports.SearchQuerySchema,
13796
13635
  target: zod_1.z.union([exports.PeerIdSchema, PeerIdObjectSchema]).optional().transform((val) => val ? typeof val === "string" ? val : val.id : undefined),
13797
13636
  session: zod_1.z.union([exports.SessionIdSchema, SessionIdObjectSchema]).optional().transform((val) => val ? typeof val === "string" ? val : val.id : undefined),
13798
- reasoningLevel: zod_1.z.enum(["minimal", "low", "medium", "high", "max"]).optional()
13799
- }).strict();
13637
+ scope: exports.ScopeOptionSchema.optional(),
13638
+ sessions: exports.SessionAllowlistSchema.optional(),
13639
+ reasoningLevel: zod_1.z.enum(["minimal", "low", "medium", "high", "max"]).optional(),
13640
+ responseFormat: zod_1.z.union([zod_1.z.instanceof(zod_1.z.ZodType), zod_1.z.record(zod_1.z.string(), zod_1.z.unknown())]).optional(),
13641
+ includeEvidence: zod_1.z.boolean().optional()
13642
+ }).strict().superRefine(scopeExclusivityIssues);
13800
13643
  exports.RepresentationOptionsSchema = zod_1.z.object({
13801
13644
  searchQuery: exports.SearchQueryLikeSchema.optional(),
13802
13645
  searchTopK: zod_1.z.number().int().min(1, "searchTopK must be at least 1").max(100, "searchTopK must be at most 100").optional(),
@@ -13809,9 +13652,32 @@ var require_validation = __commonJS(function(exports) {
13809
13652
  tokens: zod_1.z.int("Token limit must be an integer").optional(),
13810
13653
  peerTarget: exports.PeerIdSchema.optional(),
13811
13654
  peerPerspective: exports.PeerIdSchema.optional(),
13655
+ scope: exports.ScopeIdSchema.optional(),
13656
+ sessions: exports.SessionAllowlistSchema.optional(),
13812
13657
  limitToSession: zod_1.z.boolean().optional(),
13813
13658
  representationOptions: exports.RepresentationOptionsSchema.optional()
13814
13659
  }).strict().superRefine((data, ctx) => {
13660
+ if (data.sessions && !data.peerTarget) {
13661
+ ctx.addIssue({
13662
+ code: zod_1.z.ZodIssueCode.custom,
13663
+ message: "peerTarget is required when sessions is provided",
13664
+ path: ["sessions"]
13665
+ });
13666
+ }
13667
+ if (data.sessions && data.scope) {
13668
+ ctx.addIssue({
13669
+ code: zod_1.z.ZodIssueCode.custom,
13670
+ message: "sessions and scope are mutually exclusive",
13671
+ path: ["sessions"]
13672
+ });
13673
+ }
13674
+ if (data.sessions && data.limitToSession) {
13675
+ ctx.addIssue({
13676
+ code: zod_1.z.ZodIssueCode.custom,
13677
+ message: "sessions and limitToSession are mutually exclusive",
13678
+ path: ["sessions"]
13679
+ });
13680
+ }
13815
13681
  if (data.representationOptions?.searchQuery && !data.peerTarget) {
13816
13682
  ctx.addIssue({
13817
13683
  code: zod_1.z.ZodIssueCode.custom,
@@ -13826,6 +13692,20 @@ var require_validation = __commonJS(function(exports) {
13826
13692
  path: ["peerPerspective"]
13827
13693
  });
13828
13694
  }
13695
+ if (data.scope && !data.peerTarget) {
13696
+ ctx.addIssue({
13697
+ code: zod_1.z.ZodIssueCode.custom,
13698
+ message: "peerTarget is required when scope is provided",
13699
+ path: ["scope"]
13700
+ });
13701
+ }
13702
+ if (data.scope && data.peerPerspective) {
13703
+ ctx.addIssue({
13704
+ code: zod_1.z.ZodIssueCode.custom,
13705
+ message: "scope and peerPerspective are mutually exclusive",
13706
+ path: ["scope"]
13707
+ });
13708
+ }
13829
13709
  });
13830
13710
  exports.QueueStatusOptionsSchema = zod_1.z.object({
13831
13711
  observer: zod_1.z.union([exports.PeerIdSchema, PeerIdObjectSchema]).optional(),
@@ -13854,9 +13734,11 @@ var require_validation = __commonJS(function(exports) {
13854
13734
  }).strict();
13855
13735
  exports.PeerGetRepresentationParamsSchema = zod_1.z.object({
13856
13736
  session: zod_1.z.union([exports.SessionIdSchema, SessionIdObjectSchema]).optional(),
13737
+ scope: exports.ScopeOptionSchema.optional(),
13738
+ sessions: exports.SessionAllowlistSchema.optional(),
13857
13739
  target: zod_1.z.union([exports.PeerIdSchema, PeerIdObjectSchema]).optional(),
13858
13740
  options: exports.RepresentationOptionsSchema.optional()
13859
- }).strict();
13741
+ }).strict().superRefine(scopeExclusivityIssues);
13860
13742
  exports.CardTargetSchema = zod_1.z.union([exports.PeerIdSchema, PeerIdObjectSchema]).optional().transform((val) => val ? typeof val === "string" ? val : val.id : undefined);
13861
13743
  exports.PeerCardContentSchema = zod_1.z.array(zod_1.z.string());
13862
13744
  exports.PeerAdditionSchema = zod_1.z.union([
@@ -13917,7 +13799,8 @@ var require_validation = __commonJS(function(exports) {
13917
13799
  return;
13918
13800
  return {
13919
13801
  use: config.use,
13920
- create: config.create
13802
+ create: config.create,
13803
+ custom_instructions: config.customInstructions
13921
13804
  };
13922
13805
  }
13923
13806
  function peerCardConfigFromApi(config) {
@@ -13927,7 +13810,8 @@ var require_validation = __commonJS(function(exports) {
13927
13810
  return;
13928
13811
  return {
13929
13812
  use: config.use,
13930
- create: config.create
13813
+ create: config.create,
13814
+ customInstructions: config.custom_instructions
13931
13815
  };
13932
13816
  }
13933
13817
  function summaryConfigToApi(config) {
@@ -13938,7 +13822,8 @@ var require_validation = __commonJS(function(exports) {
13938
13822
  return {
13939
13823
  enabled: config.enabled,
13940
13824
  messages_per_short_summary: config.messagesPerShortSummary,
13941
- messages_per_long_summary: config.messagesPerLongSummary
13825
+ messages_per_long_summary: config.messagesPerLongSummary,
13826
+ custom_instructions: config.customInstructions
13942
13827
  };
13943
13828
  }
13944
13829
  function summaryConfigFromApi(config) {
@@ -13949,7 +13834,8 @@ var require_validation = __commonJS(function(exports) {
13949
13834
  return {
13950
13835
  enabled: config.enabled,
13951
13836
  messagesPerShortSummary: config.messages_per_short_summary,
13952
- messagesPerLongSummary: config.messages_per_long_summary
13837
+ messagesPerLongSummary: config.messages_per_long_summary,
13838
+ customInstructions: config.custom_instructions
13953
13839
  };
13954
13840
  }
13955
13841
  function dreamConfigToApi(config) {
@@ -13958,7 +13844,8 @@ var require_validation = __commonJS(function(exports) {
13958
13844
  if (config === undefined)
13959
13845
  return;
13960
13846
  return {
13961
- enabled: config.enabled
13847
+ enabled: config.enabled,
13848
+ custom_instructions: config.customInstructions
13962
13849
  };
13963
13850
  }
13964
13851
  function dreamConfigFromApi(config) {
@@ -13967,17 +13854,38 @@ var require_validation = __commonJS(function(exports) {
13967
13854
  if (config === undefined)
13968
13855
  return;
13969
13856
  return {
13970
- enabled: config.enabled
13857
+ enabled: config.enabled,
13858
+ customInstructions: config.custom_instructions
13859
+ };
13860
+ }
13861
+ function dialecticConfigToApi(config) {
13862
+ if (config === null)
13863
+ return null;
13864
+ if (config === undefined)
13865
+ return;
13866
+ return {
13867
+ custom_instructions: config.customInstructions
13868
+ };
13869
+ }
13870
+ function dialecticConfigFromApi(config) {
13871
+ if (config === null)
13872
+ return null;
13873
+ if (config === undefined)
13874
+ return;
13875
+ return {
13876
+ customInstructions: config.custom_instructions
13971
13877
  };
13972
13878
  }
13973
13879
  function workspaceConfigToApi(config) {
13974
13880
  if (!config)
13975
13881
  return;
13976
13882
  return {
13883
+ custom_instructions: config.customInstructions,
13977
13884
  reasoning: reasoningConfigToApi(config.reasoning),
13978
13885
  peer_card: peerCardConfigToApi(config.peerCard),
13979
13886
  summary: summaryConfigToApi(config.summary),
13980
- dream: dreamConfigToApi(config.dream)
13887
+ dream: dreamConfigToApi(config.dream),
13888
+ dialectic: dialecticConfigToApi(config.dialectic)
13981
13889
  };
13982
13890
  }
13983
13891
  function workspaceConfigFromApi(config) {
@@ -13985,20 +13893,24 @@ var require_validation = __commonJS(function(exports) {
13985
13893
  return;
13986
13894
  const apiConfig = config;
13987
13895
  return {
13896
+ customInstructions: apiConfig.custom_instructions,
13988
13897
  reasoning: reasoningConfigFromApi(apiConfig.reasoning),
13989
13898
  peerCard: peerCardConfigFromApi(apiConfig.peer_card),
13990
13899
  summary: summaryConfigFromApi(apiConfig.summary),
13991
- dream: dreamConfigFromApi(apiConfig.dream)
13900
+ dream: dreamConfigFromApi(apiConfig.dream),
13901
+ dialectic: dialecticConfigFromApi(apiConfig.dialectic)
13992
13902
  };
13993
13903
  }
13994
13904
  function sessionConfigToApi(config) {
13995
13905
  if (!config)
13996
13906
  return;
13997
13907
  return {
13908
+ custom_instructions: config.customInstructions,
13998
13909
  reasoning: reasoningConfigToApi(config.reasoning),
13999
13910
  peer_card: peerCardConfigToApi(config.peerCard),
14000
13911
  summary: summaryConfigToApi(config.summary),
14001
- dream: dreamConfigToApi(config.dream)
13912
+ dream: dreamConfigToApi(config.dream),
13913
+ dialectic: dialecticConfigToApi(config.dialectic)
14002
13914
  };
14003
13915
  }
14004
13916
  function sessionConfigFromApi(config) {
@@ -14006,10 +13918,12 @@ var require_validation = __commonJS(function(exports) {
14006
13918
  return;
14007
13919
  const apiConfig = config;
14008
13920
  return {
13921
+ customInstructions: apiConfig.custom_instructions,
14009
13922
  reasoning: reasoningConfigFromApi(apiConfig.reasoning),
14010
13923
  peerCard: peerCardConfigFromApi(apiConfig.peer_card),
14011
13924
  summary: summaryConfigFromApi(apiConfig.summary),
14012
- dream: dreamConfigFromApi(apiConfig.dream)
13925
+ dream: dreamConfigFromApi(apiConfig.dream),
13926
+ dialectic: dialecticConfigFromApi(apiConfig.dialectic)
14013
13927
  };
14014
13928
  }
14015
13929
  function messageConfigToApi(config) {
@@ -14081,10 +13995,12 @@ var require_validation = __commonJS(function(exports) {
14081
13995
  });
14082
13996
  exports.WorkspaceMetadataSchema = zod_1.z.record(zod_1.z.string(), zod_1.z.unknown());
14083
13997
  exports.WorkspaceConfigSchema = zod_1.z.object({
13998
+ customInstructions: zod_1.z.string().nullable().optional(),
14084
13999
  reasoning: exports.ReasoningConfigSchema.nullable().optional(),
14085
14000
  peerCard: exports.PeerCardConfigSchema.nullable().optional(),
14086
14001
  summary: exports.SummaryConfigSchema.nullable().optional(),
14087
- dream: exports.DreamConfigSchema.nullable().optional()
14002
+ dream: exports.DreamConfigSchema.nullable().optional(),
14003
+ dialectic: exports.DialecticConfigSchema.nullable().optional()
14088
14004
  }).strict();
14089
14005
  exports.LimitSchema = zod_1.z.number().int().min(1, "Limit must be a positive integer").max(100, "Limit must be less than or equal to 100");
14090
14006
  exports.ConclusionQueryParamsSchema = zod_1.z.object({
@@ -14098,22 +14014,46 @@ var require_validation = __commonJS(function(exports) {
14098
14014
  // node_modules/@honcho-ai/sdk/dist/conclusions.js
14099
14015
  var require_conclusions = __commonJS(function(exports) {
14100
14016
  Object.defineProperty(exports, "__esModule", { value: true });
14101
- exports.ConclusionScope = exports.Conclusion = undefined;
14017
+ exports.WorkspaceConclusions = exports.ConclusionsView = exports.Conclusion = undefined;
14102
14018
  var api_version_1 = require_api_version();
14019
+ var errors_1 = require_errors();
14103
14020
  var pagination_1 = require_pagination();
14104
14021
  var validation_1 = require_validation();
14022
+ var LIST_PAGE_CAP = 100;
14023
+ var VIEW_RESERVED_KEYS = [
14024
+ "observer",
14025
+ "observed",
14026
+ "observer_id",
14027
+ "observed_id"
14028
+ ];
14029
+ function rejectReservedFilterKeys(filters, reserved) {
14030
+ if (!filters)
14031
+ return;
14032
+ const clash = reserved.filter((k) => (k in filters)).sort();
14033
+ if (clash.length > 0) {
14034
+ let guidance = "Choose the peer pair via peer.conclusions / peer.conclusionsOf(target)";
14035
+ if (reserved.includes("session") || reserved.includes("session_id")) {
14036
+ guidance += "; use the session option to filter by session";
14037
+ }
14038
+ throw new Error(`Filter key(s) ${clash.join(", ")} are managed by this conclusions view ` + `and cannot be passed in filters. ${guidance}.`);
14039
+ }
14040
+ }
14105
14041
 
14106
14042
  class Conclusion {
14107
- constructor(id, content, observerId, observedId, sessionId, createdAt) {
14043
+ constructor(id, content, observerId, observedId, sessionId, createdAt, level = "explicit", sourceIds = null, timesDerived = 1, sourceMessageIds = null) {
14108
14044
  this.id = id;
14109
14045
  this.content = content;
14110
14046
  this.observerId = observerId;
14111
14047
  this.observedId = observedId;
14112
14048
  this.sessionId = sessionId;
14049
+ this.level = level;
14050
+ this.sourceIds = sourceIds;
14051
+ this.timesDerived = timesDerived;
14052
+ this.sourceMessageIds = sourceMessageIds;
14113
14053
  this.createdAt = createdAt;
14114
14054
  }
14115
14055
  static fromApiResponse(data) {
14116
- return new Conclusion(data.id, data.content, data.observer_id, data.observed_id, data.session_id, data.created_at);
14056
+ return new Conclusion(data.id, data.content, data.observer_id, data.observed_id, data.session_id, data.created_at, data.level, data.source_ids ?? null, data.times_derived ?? 1, data.source_message_ids ?? null);
14117
14057
  }
14118
14058
  toString() {
14119
14059
  const truncatedContent = this.content.length > 50 ? `${this.content.slice(0, 50)}...` : this.content;
@@ -14122,7 +14062,7 @@ var require_conclusions = __commonJS(function(exports) {
14122
14062
  }
14123
14063
  exports.Conclusion = Conclusion;
14124
14064
 
14125
- class ConclusionScope {
14065
+ class ConclusionsView {
14126
14066
  constructor(http, workspaceId, observer, observed, ensureWorkspace = async () => {
14127
14067
  return;
14128
14068
  }) {
@@ -14151,6 +14091,26 @@ var require_conclusions = __commonJS(function(exports) {
14151
14091
  await this._ensureWorkspace();
14152
14092
  return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/conclusions`, { body: params });
14153
14093
  }
14094
+ async _get(conclusionId) {
14095
+ await this._ensureWorkspace();
14096
+ const item = await this._http.get(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/conclusions/${conclusionId}`);
14097
+ if (item.observer_id !== this.observer || item.observed_id !== this.observed) {
14098
+ throw new errors_1.NotFoundError("Conclusion not found");
14099
+ }
14100
+ return item;
14101
+ }
14102
+ async _derived(conclusionId, params) {
14103
+ return this._list({
14104
+ filters: {
14105
+ source_ids: { contains: conclusionId },
14106
+ observer_id: this.observer,
14107
+ observed_id: this.observed
14108
+ },
14109
+ page: params.page,
14110
+ size: params.size,
14111
+ reverse: params.reverse
14112
+ });
14113
+ }
14154
14114
  async _delete(conclusionId) {
14155
14115
  await this._ensureWorkspace();
14156
14116
  await this._http.delete(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/conclusions/${conclusionId}`);
@@ -14160,14 +14120,18 @@ var require_conclusions = __commonJS(function(exports) {
14160
14120
  return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/peers/${peerId}/representation`, { body: params });
14161
14121
  }
14162
14122
  async list(options) {
14123
+ rejectReservedFilterKeys(options?.filters, [
14124
+ ...VIEW_RESERVED_KEYS,
14125
+ "session",
14126
+ "session_id"
14127
+ ]);
14163
14128
  const resolvedSessionId = options?.session ? typeof options.session === "string" ? options.session : options.session.id : undefined;
14164
14129
  const filters = {
14165
14130
  observer_id: this.observer,
14166
- observed_id: this.observed
14131
+ observed_id: this.observed,
14132
+ ...resolvedSessionId ? { session_id: resolvedSessionId } : {},
14133
+ ...options?.filters
14167
14134
  };
14168
- if (resolvedSessionId) {
14169
- filters.session_id = resolvedSessionId;
14170
- }
14171
14135
  const reverse = options?.reverse;
14172
14136
  const response = await this._list({
14173
14137
  filters,
@@ -14180,19 +14144,55 @@ var require_conclusions = __commonJS(function(exports) {
14180
14144
  };
14181
14145
  return new pagination_1.Page(response, (item) => Conclusion.fromApiResponse(item), fetchNextPage);
14182
14146
  }
14183
- async query(query, topK = 10, distance) {
14184
- const filters = {
14185
- observer_id: this.observer,
14186
- observed_id: this.observed
14187
- };
14147
+ async query(query, topK = 10, distance, filters) {
14148
+ rejectReservedFilterKeys(filters, VIEW_RESERVED_KEYS);
14188
14149
  const response = await this._query({
14189
14150
  query,
14190
14151
  top_k: topK,
14191
14152
  distance,
14192
- filters
14153
+ filters: {
14154
+ observer_id: this.observer,
14155
+ observed_id: this.observed,
14156
+ ...filters
14157
+ }
14193
14158
  });
14194
14159
  return (response ?? []).map((item) => Conclusion.fromApiResponse(item));
14195
14160
  }
14161
+ async get(conclusionId) {
14162
+ const response = await this._get(conclusionId);
14163
+ return Conclusion.fromApiResponse(response);
14164
+ }
14165
+ async getMany(conclusionIds) {
14166
+ if (conclusionIds.length === 0)
14167
+ return [];
14168
+ const conclusions = [];
14169
+ for (let start = 0;start < conclusionIds.length; start += LIST_PAGE_CAP) {
14170
+ const chunk = conclusionIds.slice(start, start + LIST_PAGE_CAP);
14171
+ const response = await this._list({
14172
+ filters: {
14173
+ id: { in: chunk },
14174
+ observer_id: this.observer,
14175
+ observed_id: this.observed
14176
+ },
14177
+ page: 1,
14178
+ size: chunk.length
14179
+ });
14180
+ conclusions.push(...(response.items ?? []).map((item) => Conclusion.fromApiResponse(item)));
14181
+ }
14182
+ return conclusions;
14183
+ }
14184
+ async derived(conclusionId, options) {
14185
+ const reverse = options?.reverse;
14186
+ const response = await this._derived(conclusionId, {
14187
+ page: options?.page ?? 1,
14188
+ size: options?.size ?? 50,
14189
+ reverse
14190
+ });
14191
+ const fetchNextPage = async (page, size) => {
14192
+ return this._derived(conclusionId, { page, size, reverse });
14193
+ };
14194
+ return new pagination_1.Page(response, (item) => Conclusion.fromApiResponse(item), fetchNextPage);
14195
+ }
14196
14196
  async delete(conclusionId) {
14197
14197
  await this._delete(conclusionId);
14198
14198
  }
@@ -14227,129 +14227,452 @@ var require_conclusions = __commonJS(function(exports) {
14227
14227
  return response.representation;
14228
14228
  }
14229
14229
  toString() {
14230
- return `ConclusionScope(workspaceId='${this.workspaceId}', observer='${this.observer}', observed='${this.observed}')`;
14231
- }
14232
- }
14233
- exports.ConclusionScope = ConclusionScope;
14234
- });
14235
-
14236
- // node_modules/@honcho-ai/sdk/dist/http/streaming.js
14237
- var require_streaming = __commonJS(function(exports) {
14238
- Object.defineProperty(exports, "__esModule", { value: true });
14239
- exports.DialecticStreamResponse = undefined;
14240
- exports.parseSSE = parseSSE;
14241
- exports.createDialecticStream = createDialecticStream;
14242
- async function* parseSSE(response) {
14243
- if (!response.body) {
14244
- throw new Error("Response body is null");
14245
- }
14246
- const reader = response.body.getReader();
14247
- const decoder = new TextDecoder;
14248
- let buffer = "";
14249
- try {
14250
- while (true) {
14251
- const { done, value } = await reader.read();
14252
- if (done)
14253
- break;
14254
- buffer += decoder.decode(value, { stream: true });
14255
- const lines = buffer.split(`
14256
- `);
14257
- buffer = lines.pop() || "";
14258
- for (const line of lines) {
14259
- if (line.startsWith("data: ")) {
14260
- const jsonStr = line.slice(6);
14261
- if (jsonStr.trim() === "[DONE]") {
14262
- return;
14263
- }
14264
- try {
14265
- const data = JSON.parse(jsonStr);
14266
- yield data;
14267
- } catch {}
14268
- }
14269
- }
14270
- }
14271
- if (buffer.startsWith("data: ")) {
14272
- const jsonStr = buffer.slice(6);
14273
- if (jsonStr.trim() !== "[DONE]") {
14274
- try {
14275
- const data = JSON.parse(jsonStr);
14276
- yield data;
14277
- } catch {}
14278
- }
14279
- }
14280
- } finally {
14281
- reader.releaseLock();
14230
+ return `ConclusionsView(workspaceId='${this.workspaceId}', observer='${this.observer}', observed='${this.observed}')`;
14282
14231
  }
14283
14232
  }
14233
+ exports.ConclusionsView = ConclusionsView;
14284
14234
 
14285
- class DialecticStreamResponse {
14286
- constructor(generator) {
14287
- this.chunks = [];
14288
- this.consumed = false;
14289
- this.generator = generator;
14235
+ class WorkspaceConclusions {
14236
+ constructor(http, workspaceId, ensureWorkspace = async () => {
14237
+ return;
14238
+ }) {
14239
+ this._http = http;
14240
+ this.workspaceId = workspaceId;
14241
+ this._ensureWorkspace = ensureWorkspace;
14290
14242
  }
14291
- async* [Symbol.asyncIterator]() {
14292
- if (this.consumed) {
14293
- for (const chunk of this.chunks) {
14294
- yield chunk;
14243
+ async _list(params) {
14244
+ await this._ensureWorkspace();
14245
+ return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/conclusions/list`, {
14246
+ body: params.filters ? { filters: params.filters } : undefined,
14247
+ query: {
14248
+ page: params.page,
14249
+ size: params.size,
14250
+ reverse: params.reverse ? "true" : undefined
14295
14251
  }
14296
- return;
14297
- }
14298
- for await (const chunk of this.generator) {
14299
- this.chunks.push(chunk);
14300
- yield chunk;
14301
- }
14302
- this.consumed = true;
14252
+ });
14303
14253
  }
14304
- async getFinalResponse() {
14305
- if (!this.consumed) {
14306
- for await (const _ of this) {}
14307
- }
14308
- return this.chunks.join("");
14254
+ async list(options) {
14255
+ const filters = options?.filters;
14256
+ const reverse = options?.reverse;
14257
+ const response = await this._list({
14258
+ filters,
14259
+ page: options?.page ?? 1,
14260
+ size: options?.size ?? 50,
14261
+ reverse
14262
+ });
14263
+ const fetchNextPage = async (page, size) => {
14264
+ return this._list({ filters, page, size, reverse });
14265
+ };
14266
+ return new pagination_1.Page(response, (item) => Conclusion.fromApiResponse(item), fetchNextPage);
14309
14267
  }
14310
- async toArray() {
14311
- if (!this.consumed) {
14312
- for await (const _ of this) {}
14268
+ async get(conclusionId) {
14269
+ await this._ensureWorkspace();
14270
+ const item = await this._http.get(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/conclusions/${conclusionId}`);
14271
+ return Conclusion.fromApiResponse(item);
14272
+ }
14273
+ async getMany(conclusionIds) {
14274
+ if (conclusionIds.length === 0)
14275
+ return [];
14276
+ const conclusions = [];
14277
+ for (let start = 0;start < conclusionIds.length; start += LIST_PAGE_CAP) {
14278
+ const chunk = conclusionIds.slice(start, start + LIST_PAGE_CAP);
14279
+ const response = await this._list({
14280
+ filters: { id: { in: chunk } },
14281
+ page: 1,
14282
+ size: chunk.length
14283
+ });
14284
+ conclusions.push(...(response.items ?? []).map((item) => Conclusion.fromApiResponse(item)));
14313
14285
  }
14314
- return [...this.chunks];
14286
+ return conclusions;
14315
14287
  }
14316
- }
14317
- exports.DialecticStreamResponse = DialecticStreamResponse;
14318
- function createDialecticStream(response) {
14319
- async function* streamContent() {
14320
- for await (const chunk of parseSSE(response)) {
14321
- if (chunk.done) {
14322
- return;
14323
- }
14324
- const content = chunk.delta?.content;
14325
- if (content) {
14326
- yield content;
14327
- }
14328
- }
14288
+ toString() {
14289
+ return `WorkspaceConclusions(workspaceId='${this.workspaceId}')`;
14329
14290
  }
14330
- return new DialecticStreamResponse(streamContent());
14331
14291
  }
14292
+ exports.WorkspaceConclusions = WorkspaceConclusions;
14332
14293
  });
14333
14294
 
14334
- // node_modules/@honcho-ai/sdk/dist/session_context.js
14335
- var require_session_context = __commonJS(function(exports) {
14295
+ // node_modules/@honcho-ai/sdk/dist/http/client.js
14296
+ var require_client = __commonJS(function(exports) {
14336
14297
  Object.defineProperty(exports, "__esModule", { value: true });
14337
- exports.SessionContext = exports.SessionSummaries = exports.Summary = undefined;
14338
- var message_1 = require_message();
14298
+ exports.HonchoHTTPClient = exports.HOST_HEADER = undefined;
14299
+ exports.defaultHostHeader = defaultHostHeader;
14300
+ var api_version_1 = require_api_version();
14301
+ var errors_1 = require_errors();
14302
+ var DEFAULT_TIMEOUT = 60000;
14303
+ var DEFAULT_MAX_RETRIES = 2;
14304
+ var RETRY_STATUS_CODES = [429, 500, 502, 503, 504];
14305
+ var INITIAL_RETRY_DELAY = 500;
14306
+ exports.HOST_HEADER = "X-Honcho-Host";
14307
+ function defaultHostHeader() {
14308
+ const product = `honcho-typescript/${api_version_1.VERSION}`;
14309
+ const platform = typeof process !== "undefined" && typeof process.platform === "string" ? process.platform : undefined;
14310
+ return platform ? `${product} (${platform})` : product;
14311
+ }
14339
14312
 
14340
- class Summary {
14341
- constructor(data) {
14342
- this.content = data.content;
14343
- this.messageId = data.messageId;
14344
- this.summaryType = data.summaryType;
14345
- this.createdAt = data.createdAt;
14346
- this.tokenCount = data.tokenCount;
14347
- }
14348
- static fromApiResponse(data) {
14349
- return new Summary({
14350
- content: data.content,
14351
- messageId: data.message_id,
14352
- summaryType: data.summary_type,
14313
+ class HonchoHTTPClient {
14314
+ constructor(config) {
14315
+ this.baseURL = config.baseURL.replace(/\/$/, "");
14316
+ this.apiKey = config.apiKey;
14317
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
14318
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
14319
+ this.defaultHeaders = {
14320
+ "Content-Type": "application/json",
14321
+ [exports.HOST_HEADER]: defaultHostHeader(),
14322
+ ...config.defaultHeaders
14323
+ };
14324
+ this.defaultQuery = config.defaultQuery;
14325
+ }
14326
+ async request(method, path, options = {}) {
14327
+ const url = this.buildURL(path, options.query);
14328
+ const headers = this.buildHeaders(options.headers);
14329
+ const timeout = options.timeout ?? this.timeout;
14330
+ let lastError;
14331
+ let attempt = 0;
14332
+ while (attempt <= this.maxRetries) {
14333
+ try {
14334
+ const response = await this.fetchWithTimeout(url, {
14335
+ method,
14336
+ headers,
14337
+ body: options.body ? JSON.stringify(options.body) : undefined,
14338
+ signal: options.signal
14339
+ }, timeout);
14340
+ if (response.ok) {
14341
+ const text = await response.text();
14342
+ if (!text) {
14343
+ return;
14344
+ }
14345
+ return JSON.parse(text);
14346
+ }
14347
+ const errorBody = await this.parseErrorBody(response);
14348
+ const retryAfter = this.parseRetryAfter(response);
14349
+ const error = (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody, retryAfter);
14350
+ if (RETRY_STATUS_CODES.includes(response.status) && attempt < this.maxRetries) {
14351
+ lastError = error;
14352
+ await this.sleep(this.getRetryDelay(attempt, retryAfter));
14353
+ attempt++;
14354
+ continue;
14355
+ }
14356
+ throw error;
14357
+ } catch (error) {
14358
+ if (error instanceof errors_1.TimeoutError || error instanceof errors_1.ConnectionError) {
14359
+ if (attempt < this.maxRetries) {
14360
+ lastError = error;
14361
+ await this.sleep(this.getRetryDelay(attempt));
14362
+ attempt++;
14363
+ continue;
14364
+ }
14365
+ }
14366
+ if (error instanceof errors_1.RateLimitError || error instanceof errors_1.ServerError || error instanceof errors_1.TimeoutError || error instanceof errors_1.ConnectionError) {
14367
+ throw error;
14368
+ }
14369
+ throw error;
14370
+ }
14371
+ }
14372
+ throw lastError || new Error("Request failed after retries");
14373
+ }
14374
+ async get(path, options) {
14375
+ return this.request("GET", path, options);
14376
+ }
14377
+ async post(path, options) {
14378
+ return this.request("POST", path, options);
14379
+ }
14380
+ async put(path, options) {
14381
+ return this.request("PUT", path, options);
14382
+ }
14383
+ async patch(path, options) {
14384
+ return this.request("PATCH", path, options);
14385
+ }
14386
+ async delete(path, options) {
14387
+ return this.request("DELETE", path, options);
14388
+ }
14389
+ async stream(method, path, options = {}) {
14390
+ const url = this.buildURL(path, options.query);
14391
+ const headers = {
14392
+ ...this.buildHeaders(options.headers),
14393
+ Accept: "text/event-stream"
14394
+ };
14395
+ const timeout = options.timeout ?? this.timeout;
14396
+ const response = await this.fetchWithTimeout(url, {
14397
+ method,
14398
+ headers,
14399
+ body: options.body ? JSON.stringify(options.body) : undefined,
14400
+ signal: options.signal
14401
+ }, timeout);
14402
+ if (!response.ok) {
14403
+ const errorBody = await this.parseErrorBody(response);
14404
+ throw (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody);
14405
+ }
14406
+ return response;
14407
+ }
14408
+ async upload(path, formData, options = {}) {
14409
+ const url = this.buildURL(path, options.query);
14410
+ const headers = {};
14411
+ if (this.apiKey) {
14412
+ headers.Authorization = `Bearer ${this.apiKey}`;
14413
+ }
14414
+ if (options.headers) {
14415
+ Object.assign(headers, options.headers);
14416
+ }
14417
+ const timeout = options.timeout ?? this.timeout;
14418
+ const response = await this.fetchWithTimeout(url, {
14419
+ method: "POST",
14420
+ headers,
14421
+ body: formData,
14422
+ signal: options.signal
14423
+ }, timeout);
14424
+ if (!response.ok) {
14425
+ const errorBody = await this.parseErrorBody(response);
14426
+ throw (0, errors_1.createErrorFromResponse)(response.status, errorBody.message || `HTTP ${response.status}`, errorBody);
14427
+ }
14428
+ const text = await response.text();
14429
+ if (!text) {
14430
+ return;
14431
+ }
14432
+ return JSON.parse(text);
14433
+ }
14434
+ buildURL(path, query) {
14435
+ const url = new URL(path, this.baseURL);
14436
+ const mergedQuery = {
14437
+ ...this.defaultQuery ?? {},
14438
+ ...query ?? {}
14439
+ };
14440
+ for (const [key, value] of Object.entries(mergedQuery)) {
14441
+ if (value === undefined) {
14442
+ continue;
14443
+ }
14444
+ if (Array.isArray(value)) {
14445
+ for (const entry of value) {
14446
+ url.searchParams.append(key, String(entry));
14447
+ }
14448
+ continue;
14449
+ }
14450
+ url.searchParams.set(key, String(value));
14451
+ }
14452
+ return url.toString();
14453
+ }
14454
+ buildHeaders(extra) {
14455
+ const headers = { ...this.defaultHeaders };
14456
+ if (this.apiKey) {
14457
+ headers.Authorization = `Bearer ${this.apiKey}`;
14458
+ }
14459
+ if (extra) {
14460
+ Object.assign(headers, extra);
14461
+ }
14462
+ return headers;
14463
+ }
14464
+ async fetchWithTimeout(url, init, timeout) {
14465
+ const controller = new AbortController;
14466
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
14467
+ if (init.signal) {
14468
+ init.signal.addEventListener("abort", () => controller.abort());
14469
+ }
14470
+ try {
14471
+ const response = await fetch(url, {
14472
+ ...init,
14473
+ signal: controller.signal
14474
+ });
14475
+ return response;
14476
+ } catch (error) {
14477
+ if (error instanceof DOMException && error.name === "AbortError") {
14478
+ throw new errors_1.TimeoutError(`Request timed out after ${timeout}ms`);
14479
+ }
14480
+ if (error instanceof TypeError) {
14481
+ throw new errors_1.ConnectionError(error.message);
14482
+ }
14483
+ throw error;
14484
+ } finally {
14485
+ clearTimeout(timeoutId);
14486
+ }
14487
+ }
14488
+ async parseErrorBody(response) {
14489
+ try {
14490
+ const body = await response.json();
14491
+ return {
14492
+ message: body.detail || body.message || body.error,
14493
+ ...body
14494
+ };
14495
+ } catch {
14496
+ return { message: `HTTP ${response.status}` };
14497
+ }
14498
+ }
14499
+ parseRetryAfter(response) {
14500
+ const header = response.headers.get("Retry-After");
14501
+ if (!header)
14502
+ return;
14503
+ const seconds = Number.parseInt(header, 10);
14504
+ if (!Number.isNaN(seconds)) {
14505
+ return seconds * 1000;
14506
+ }
14507
+ const date = Date.parse(header);
14508
+ if (!Number.isNaN(date)) {
14509
+ return Math.max(0, date - Date.now());
14510
+ }
14511
+ return;
14512
+ }
14513
+ getRetryDelay(attempt, retryAfter) {
14514
+ if (retryAfter) {
14515
+ return retryAfter;
14516
+ }
14517
+ return INITIAL_RETRY_DELAY * 2 ** attempt;
14518
+ }
14519
+ sleep(ms) {
14520
+ return new Promise((resolve) => setTimeout(resolve, ms));
14521
+ }
14522
+ }
14523
+ exports.HonchoHTTPClient = HonchoHTTPClient;
14524
+ });
14525
+
14526
+ // node_modules/@honcho-ai/sdk/dist/http/streaming.js
14527
+ var require_streaming = __commonJS(function(exports) {
14528
+ Object.defineProperty(exports, "__esModule", { value: true });
14529
+ exports.DialecticStreamResponse = undefined;
14530
+ exports.parseSSE = parseSSE;
14531
+ exports.createDialecticStream = createDialecticStream;
14532
+ async function* parseSSE(response) {
14533
+ if (!response.body) {
14534
+ throw new Error("Response body is null");
14535
+ }
14536
+ const reader = response.body.getReader();
14537
+ const decoder = new TextDecoder;
14538
+ let buffer = "";
14539
+ try {
14540
+ while (true) {
14541
+ const { done, value } = await reader.read();
14542
+ if (done)
14543
+ break;
14544
+ buffer += decoder.decode(value, { stream: true });
14545
+ const lines = buffer.split(`
14546
+ `);
14547
+ buffer = lines.pop() || "";
14548
+ for (const line of lines) {
14549
+ if (line.startsWith("data: ")) {
14550
+ const jsonStr = line.slice(6);
14551
+ if (jsonStr.trim() === "[DONE]") {
14552
+ return;
14553
+ }
14554
+ try {
14555
+ const data = JSON.parse(jsonStr);
14556
+ yield data;
14557
+ } catch {}
14558
+ }
14559
+ }
14560
+ }
14561
+ if (buffer.startsWith("data: ")) {
14562
+ const jsonStr = buffer.slice(6);
14563
+ if (jsonStr.trim() !== "[DONE]") {
14564
+ try {
14565
+ const data = JSON.parse(jsonStr);
14566
+ yield data;
14567
+ } catch {}
14568
+ }
14569
+ }
14570
+ } finally {
14571
+ reader.releaseLock();
14572
+ }
14573
+ }
14574
+
14575
+ class DialecticStreamResponse {
14576
+ constructor(generator, evidenceSource) {
14577
+ this.chunks = [];
14578
+ this.consumed = false;
14579
+ this.generator = generator;
14580
+ this.evidenceSource = evidenceSource;
14581
+ }
14582
+ get evidence() {
14583
+ return this.evidenceSource?.() ?? null;
14584
+ }
14585
+ async* [Symbol.asyncIterator]() {
14586
+ if (this.consumed) {
14587
+ for (const chunk of this.chunks) {
14588
+ yield chunk;
14589
+ }
14590
+ return;
14591
+ }
14592
+ for await (const chunk of this.generator) {
14593
+ this.chunks.push(chunk);
14594
+ yield chunk;
14595
+ }
14596
+ this.consumed = true;
14597
+ }
14598
+ async getFinalResponse() {
14599
+ if (!this.consumed) {
14600
+ for await (const _ of this) {}
14601
+ }
14602
+ return this.chunks.join("");
14603
+ }
14604
+ async toArray() {
14605
+ if (!this.consumed) {
14606
+ for await (const _ of this) {}
14607
+ }
14608
+ return [...this.chunks];
14609
+ }
14610
+ }
14611
+ exports.DialecticStreamResponse = DialecticStreamResponse;
14612
+ function createDialecticStream(response) {
14613
+ let evidence = null;
14614
+ async function* streamContent() {
14615
+ for await (const chunk of parseSSE(response)) {
14616
+ if (chunk.done) {
14617
+ evidence = chunk.evidence ?? null;
14618
+ return;
14619
+ }
14620
+ const content = chunk.delta?.content;
14621
+ if (content) {
14622
+ yield content;
14623
+ }
14624
+ }
14625
+ }
14626
+ return new DialecticStreamResponse(streamContent(), () => evidence);
14627
+ }
14628
+ });
14629
+
14630
+ // node_modules/@honcho-ai/sdk/dist/message.js
14631
+ var require_message = __commonJS(function(exports) {
14632
+ Object.defineProperty(exports, "__esModule", { value: true });
14633
+ exports.Message = undefined;
14634
+
14635
+ class Message {
14636
+ constructor(id, content, peerId, sessionId, workspaceId, metadata, createdAt, tokenCount) {
14637
+ this.id = id;
14638
+ this.content = content;
14639
+ this.peerId = peerId;
14640
+ this.sessionId = sessionId;
14641
+ this.workspaceId = workspaceId;
14642
+ this.metadata = metadata;
14643
+ this.createdAt = createdAt;
14644
+ this.tokenCount = tokenCount;
14645
+ }
14646
+ static fromApiResponse(data) {
14647
+ return new Message(data.id, data.content, data.peer_id, data.session_id, data.workspace_id, data.metadata, data.created_at, data.token_count);
14648
+ }
14649
+ toString() {
14650
+ const truncatedContent = this.content.length > 50 ? `${this.content.slice(0, 50)}...` : this.content;
14651
+ return `Message(id='${this.id}', peerId='${this.peerId}', content='${truncatedContent}')`;
14652
+ }
14653
+ }
14654
+ exports.Message = Message;
14655
+ });
14656
+
14657
+ // node_modules/@honcho-ai/sdk/dist/session_context.js
14658
+ var require_session_context = __commonJS(function(exports) {
14659
+ Object.defineProperty(exports, "__esModule", { value: true });
14660
+ exports.SessionContext = exports.SessionSummaries = exports.Summary = undefined;
14661
+ var message_1 = require_message();
14662
+
14663
+ class Summary {
14664
+ constructor(data) {
14665
+ this.content = data.content;
14666
+ this.messageId = data.messageId;
14667
+ this.summaryType = data.summaryType;
14668
+ this.createdAt = data.createdAt;
14669
+ this.tokenCount = data.tokenCount;
14670
+ }
14671
+ static fromApiResponse(data) {
14672
+ return new Summary({
14673
+ content: data.content,
14674
+ messageId: data.message_id,
14675
+ summaryType: data.summary_type,
14353
14676
  createdAt: data.created_at,
14354
14677
  tokenCount: data.token_count
14355
14678
  });
@@ -14505,12 +14828,18 @@ var require_session = __commonJS(function(exports) {
14505
14828
  get createdAt() {
14506
14829
  return this._createdAt;
14507
14830
  }
14831
+ get uid() {
14832
+ return this._uid;
14833
+ }
14508
14834
  get isActive() {
14509
14835
  return this._isActive;
14510
14836
  }
14837
+ get scopes() {
14838
+ return this._scopes;
14839
+ }
14511
14840
  constructor(id, workspaceId, http, metadata, configuration, ensureWorkspace = async () => {
14512
14841
  return;
14513
- }, createdAt, isActive) {
14842
+ }, createdAt, isActive, uid, scopes) {
14514
14843
  this.id = id;
14515
14844
  this.workspaceId = workspaceId;
14516
14845
  this._http = http;
@@ -14519,12 +14848,15 @@ var require_session = __commonJS(function(exports) {
14519
14848
  this._ensureWorkspace = ensureWorkspace;
14520
14849
  this._createdAt = createdAt;
14521
14850
  this._isActive = isActive;
14851
+ this._uid = uid;
14852
+ this._scopes = scopes;
14522
14853
  }
14523
14854
  _applySessionResponse(session) {
14524
14855
  this._metadata = session.metadata || {};
14525
14856
  this._configuration = (0, validation_1.sessionConfigFromApi)(session.configuration) || {};
14526
14857
  this._createdAt = session.created_at;
14527
14858
  this._isActive = session.is_active;
14859
+ this._uid = session.uid;
14528
14860
  }
14529
14861
  async _getOrCreate(params) {
14530
14862
  await this._ensureWorkspace();
@@ -14648,7 +14980,7 @@ var require_session = __commonJS(function(exports) {
14648
14980
  }
14649
14981
  async peers() {
14650
14982
  const peersPage = await this._listPeers();
14651
- return peersPage.items.map((peer) => new peer_1.Peer(peer.id, this.workspaceId, this._http, peer.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peer.configuration) ?? undefined, () => this._ensureWorkspace(), peer.created_at));
14983
+ return peersPage.items.map((peer) => new peer_1.Peer(peer.id, this.workspaceId, this._http, peer.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peer.configuration) ?? undefined, () => this._ensureWorkspace(), peer.created_at, peer.uid));
14652
14984
  }
14653
14985
  async getPeerConfiguration(peer) {
14654
14986
  const peerId = typeof peer === "string" ? peer : peer.id;
@@ -14732,7 +15064,7 @@ var require_session = __commonJS(function(exports) {
14732
15064
  }
14733
15065
  async clone(messageId) {
14734
15066
  const clonedSessionData = await this._clone(messageId ? { message_id: messageId } : undefined);
14735
- return new Session(clonedSessionData.id, this.workspaceId, this._http, clonedSessionData.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(clonedSessionData.configuration) ?? undefined, () => this._ensureWorkspace(), clonedSessionData.created_at, clonedSessionData.is_active);
15067
+ return new Session(clonedSessionData.id, this.workspaceId, this._http, clonedSessionData.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(clonedSessionData.configuration) ?? undefined, () => this._ensureWorkspace(), clonedSessionData.created_at, clonedSessionData.is_active, clonedSessionData.uid);
14736
15068
  }
14737
15069
  async context(options) {
14738
15070
  const opts = options || {};
@@ -14744,6 +15076,8 @@ var require_session = __commonJS(function(exports) {
14744
15076
  tokens: opts.tokens,
14745
15077
  peerTarget: peerTargetId,
14746
15078
  peerPerspective: peerPerspectiveId,
15079
+ scope: opts.scope !== undefined ? (0, utils_1.resolveId)(opts.scope) : undefined,
15080
+ sessions: opts.sessions,
14747
15081
  limitToSession: opts.limitToSession,
14748
15082
  representationOptions: opts.representationOptions ? {
14749
15083
  ...opts.representationOptions,
@@ -14756,6 +15090,8 @@ var require_session = __commonJS(function(exports) {
14756
15090
  search_query: searchQuery,
14757
15091
  peer_target: contextParams.peerTarget,
14758
15092
  peer_perspective: contextParams.peerPerspective,
15093
+ scope: contextParams.scope,
15094
+ sessions: contextParams.sessions,
14759
15095
  limit_to_session: contextParams.limitToSession,
14760
15096
  search_top_k: contextParams.representationOptions?.searchTopK,
14761
15097
  search_max_distance: contextParams.representationOptions?.searchMaxDistance,
@@ -14872,6 +15208,7 @@ var require_session = __commonJS(function(exports) {
14872
15208
  var require_peer = __commonJS(function(exports) {
14873
15209
  Object.defineProperty(exports, "__esModule", { value: true });
14874
15210
  exports.Peer = exports.PeerContext = undefined;
15211
+ var zod_1 = require_zod();
14875
15212
  var api_version_1 = require_api_version();
14876
15213
  var conclusions_1 = require_conclusions();
14877
15214
  var streaming_1 = require_streaming();
@@ -14906,9 +15243,12 @@ var require_peer = __commonJS(function(exports) {
14906
15243
  get createdAt() {
14907
15244
  return this._createdAt;
14908
15245
  }
15246
+ get uid() {
15247
+ return this._uid;
15248
+ }
14909
15249
  constructor(id, workspaceId, http, metadata, configuration, ensureWorkspace = async () => {
14910
15250
  return;
14911
- }, createdAt) {
15251
+ }, createdAt, uid) {
14912
15252
  this.id = id;
14913
15253
  this.workspaceId = workspaceId;
14914
15254
  this._http = http;
@@ -14916,6 +15256,7 @@ var require_peer = __commonJS(function(exports) {
14916
15256
  this._configuration = configuration;
14917
15257
  this._ensureWorkspace = ensureWorkspace;
14918
15258
  this._createdAt = createdAt;
15259
+ this._uid = uid;
14919
15260
  }
14920
15261
  async _getOrCreate(params) {
14921
15262
  await this._ensureWorkspace();
@@ -14936,6 +15277,15 @@ var require_peer = __commonJS(function(exports) {
14936
15277
  }
14937
15278
  });
14938
15279
  }
15280
+ static toResponseFormatSchema(responseFormat) {
15281
+ if (!responseFormat) {
15282
+ return;
15283
+ }
15284
+ if (responseFormat instanceof zod_1.ZodType) {
15285
+ return zod_1.z.toJSONSchema(responseFormat);
15286
+ }
15287
+ return responseFormat;
15288
+ }
14939
15289
  async _chat(params) {
14940
15290
  await this._ensureWorkspace();
14941
15291
  return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/peers/${this.id}/chat`, { body: params });
@@ -14977,19 +15327,28 @@ var require_peer = __commonJS(function(exports) {
14977
15327
  query,
14978
15328
  target: targetId,
14979
15329
  session: resolvedSessionId,
14980
- reasoningLevel: options?.reasoningLevel
15330
+ scope: options?.scope,
15331
+ sessions: options?.sessions,
15332
+ reasoningLevel: options?.reasoningLevel,
15333
+ responseFormat: options?.responseFormat,
15334
+ includeEvidence: options?.includeEvidence
14981
15335
  });
15336
+ const zodSchema = options?.responseFormat instanceof zod_1.ZodType ? options.responseFormat : undefined;
14982
15337
  const response = await this._chat({
14983
15338
  query: chatParams.query,
14984
15339
  stream: false,
14985
15340
  target: chatParams.target,
14986
15341
  session_id: chatParams.session,
14987
- reasoning_level: chatParams.reasoningLevel
15342
+ ...(0, validation_1.scopeRecallFields)(chatParams),
15343
+ reasoning_level: chatParams.reasoningLevel,
15344
+ response_format: Peer.toResponseFormatSchema(options?.responseFormat),
15345
+ include_evidence: chatParams.includeEvidence ? true : undefined
14988
15346
  });
14989
- if (!response.content) {
14990
- return null;
15347
+ const content = response.content ? zodSchema ? zodSchema.parse(JSON.parse(response.content)) : response.content : null;
15348
+ if (!chatParams.includeEvidence) {
15349
+ return content;
14991
15350
  }
14992
- return response.content;
15351
+ return { content, evidence: response.evidence ?? null };
14993
15352
  }
14994
15353
  async chatStream(query, options) {
14995
15354
  const targetId = options?.target ? typeof options.target === "string" ? options.target : options.target.id : undefined;
@@ -14998,13 +15357,20 @@ var require_peer = __commonJS(function(exports) {
14998
15357
  query,
14999
15358
  target: targetId,
15000
15359
  session: resolvedSessionId,
15001
- reasoningLevel: options?.reasoningLevel
15360
+ scope: options?.scope,
15361
+ sessions: options?.sessions,
15362
+ reasoningLevel: options?.reasoningLevel,
15363
+ responseFormat: options?.responseFormat,
15364
+ includeEvidence: options?.includeEvidence
15002
15365
  });
15003
15366
  const response = await this._chatStream({
15004
15367
  query: chatParams.query,
15005
15368
  target: chatParams.target,
15006
15369
  session_id: chatParams.session,
15007
- reasoning_level: chatParams.reasoningLevel
15370
+ ...(0, validation_1.scopeRecallFields)(chatParams),
15371
+ reasoning_level: chatParams.reasoningLevel,
15372
+ response_format: Peer.toResponseFormatSchema(options?.responseFormat),
15373
+ include_evidence: chatParams.includeEvidence ? true : undefined
15008
15374
  });
15009
15375
  return (0, streaming_1.createDialecticStream)(response);
15010
15376
  }
@@ -15031,7 +15397,7 @@ var require_peer = __commonJS(function(exports) {
15031
15397
  reverse
15032
15398
  });
15033
15399
  };
15034
- return new pagination_1.Page(sessionsPage, (session) => new session_1.Session(session.id, this.workspaceId, this._http, session.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(session.configuration) ?? undefined, () => this._ensureWorkspace(), session.created_at, session.is_active), fetchNextPage);
15400
+ return new pagination_1.Page(sessionsPage, (session) => new session_1.Session(session.id, this.workspaceId, this._http, session.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(session.configuration) ?? undefined, () => this._ensureWorkspace(), session.created_at, session.is_active, session.uid), fetchNextPage);
15035
15401
  }
15036
15402
  message(content, options) {
15037
15403
  const validatedContent = validation_1.MessageContentSchema.parse(content);
@@ -15050,6 +15416,7 @@ var require_peer = __commonJS(function(exports) {
15050
15416
  const peer = await this._getOrCreate({ id: this.id });
15051
15417
  this._metadata = peer.metadata || {};
15052
15418
  this._createdAt = peer.created_at;
15419
+ this._uid = peer.uid;
15053
15420
  return this._metadata;
15054
15421
  }
15055
15422
  async setMetadata(metadata) {
@@ -15061,6 +15428,7 @@ var require_peer = __commonJS(function(exports) {
15061
15428
  const peer = await this._getOrCreate({ id: this.id });
15062
15429
  this._configuration = (0, validation_1.peerConfigFromApi)(peer.configuration) || {};
15063
15430
  this._createdAt = peer.created_at;
15431
+ this._uid = peer.uid;
15064
15432
  return this._configuration;
15065
15433
  }
15066
15434
  async setConfiguration(configuration) {
@@ -15073,6 +15441,7 @@ var require_peer = __commonJS(function(exports) {
15073
15441
  this._metadata = peer.metadata || {};
15074
15442
  this._configuration = (0, validation_1.peerConfigFromApi)(peer.configuration) || {};
15075
15443
  this._createdAt = peer.created_at;
15444
+ this._uid = peer.uid;
15076
15445
  }
15077
15446
  async search(query, options) {
15078
15447
  const validatedQuery = validation_1.SearchQuerySchema.parse(query);
@@ -15108,6 +15477,8 @@ var require_peer = __commonJS(function(exports) {
15108
15477
  const searchQuery = (0, validation_1.normalizeSearchQuery)(options?.searchQuery);
15109
15478
  const getRepresentationParams = validation_1.PeerGetRepresentationParamsSchema.parse({
15110
15479
  session: options?.session,
15480
+ scope: options?.scope,
15481
+ sessions: options?.sessions,
15111
15482
  target: options?.target,
15112
15483
  options: {
15113
15484
  searchQuery,
@@ -15121,6 +15492,7 @@ var require_peer = __commonJS(function(exports) {
15121
15492
  const targetId = getRepresentationParams.target ? typeof getRepresentationParams.target === "string" ? getRepresentationParams.target : getRepresentationParams.target.id : undefined;
15122
15493
  const response = await this._getRepresentation({
15123
15494
  session_id: sessionId,
15495
+ ...(0, validation_1.scopeRecallFields)(getRepresentationParams),
15124
15496
  target: targetId,
15125
15497
  search_query: searchQuery,
15126
15498
  search_top_k: getRepresentationParams.options?.searchTopK,
@@ -15151,11 +15523,11 @@ var require_peer = __commonJS(function(exports) {
15151
15523
  return PeerContext.fromApiResponse(response);
15152
15524
  }
15153
15525
  get conclusions() {
15154
- return new conclusions_1.ConclusionScope(this._http, this.workspaceId, this.id, this.id, () => this._ensureWorkspace());
15526
+ return new conclusions_1.ConclusionsView(this._http, this.workspaceId, this.id, this.id, () => this._ensureWorkspace());
15155
15527
  }
15156
15528
  conclusionsOf(target) {
15157
15529
  const targetId = typeof target === "string" ? target : target.id;
15158
- return new conclusions_1.ConclusionScope(this._http, this.workspaceId, this.id, targetId, () => this._ensureWorkspace());
15530
+ return new conclusions_1.ConclusionsView(this._http, this.workspaceId, this.id, targetId, () => this._ensureWorkspace());
15159
15531
  }
15160
15532
  toString() {
15161
15533
  return `Peer(id='${this.id}')`;
@@ -15164,15 +15536,125 @@ var require_peer = __commonJS(function(exports) {
15164
15536
  exports.Peer = Peer;
15165
15537
  });
15166
15538
 
15539
+ // node_modules/@honcho-ai/sdk/dist/scope.js
15540
+ var require_scope = __commonJS(function(exports) {
15541
+ Object.defineProperty(exports, "__esModule", { value: true });
15542
+ exports.Scope = undefined;
15543
+ var api_version_1 = require_api_version();
15544
+ var pagination_1 = require_pagination();
15545
+ var session_1 = require_session();
15546
+ var utils_1 = require_utils();
15547
+ var validation_1 = require_validation();
15548
+
15549
+ class Scope {
15550
+ get metadata() {
15551
+ return this._metadata;
15552
+ }
15553
+ get createdAt() {
15554
+ return this._createdAt;
15555
+ }
15556
+ get sessionCount() {
15557
+ return this._sessionCount;
15558
+ }
15559
+ constructor(id, workspaceId, http, metadata, ensureWorkspace = async () => {
15560
+ return;
15561
+ }, createdAt, sessionCount) {
15562
+ this.id = id;
15563
+ this.workspaceId = workspaceId;
15564
+ this._http = http;
15565
+ this._metadata = metadata;
15566
+ this._ensureWorkspace = ensureWorkspace;
15567
+ this._createdAt = createdAt;
15568
+ this._sessionCount = sessionCount;
15569
+ }
15570
+ get _basePath() {
15571
+ return `/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/scopes/${this.id}`;
15572
+ }
15573
+ async _addSessions(sessionIds) {
15574
+ await this._ensureWorkspace();
15575
+ await this._http.post(`${this._basePath}/sessions`, {
15576
+ body: { session_ids: sessionIds }
15577
+ });
15578
+ }
15579
+ async _removeSessions(sessionIds) {
15580
+ await this._ensureWorkspace();
15581
+ await this._http.post(`${this._basePath}/sessions/remove`, {
15582
+ body: { session_ids: sessionIds }
15583
+ });
15584
+ }
15585
+ async _removeSession(sessionId) {
15586
+ await this._ensureWorkspace();
15587
+ await this._http.delete(`${this._basePath}/sessions/${sessionId}`);
15588
+ }
15589
+ async _listSessions(params) {
15590
+ await this._ensureWorkspace();
15591
+ return this._http.post(`${this._basePath}/sessions/list`, {
15592
+ query: {
15593
+ page: params?.page,
15594
+ size: params?.size,
15595
+ reverse: params?.reverse ? "true" : undefined
15596
+ }
15597
+ });
15598
+ }
15599
+ async _getStatus() {
15600
+ await this._ensureWorkspace();
15601
+ return this._http.get(`${this._basePath}/status`);
15602
+ }
15603
+ async addSessions(sessions) {
15604
+ const sessionIds = validation_1.ScopeSessionsSchema.parse(sessions.map(utils_1.resolveId));
15605
+ await this._addSessions(sessionIds);
15606
+ }
15607
+ async removeSessions(sessions) {
15608
+ const sessionIds = validation_1.ScopeSessionsSchema.parse(sessions.map(utils_1.resolveId));
15609
+ await this._removeSessions(sessionIds);
15610
+ }
15611
+ async removeSession(session) {
15612
+ await this._removeSession(validation_1.SessionIdSchema.parse((0, utils_1.resolveId)(session)));
15613
+ }
15614
+ async sessions(options) {
15615
+ const reverse = options?.reverse;
15616
+ const sessionsPage = await this._listSessions({
15617
+ page: options?.page,
15618
+ size: options?.size,
15619
+ reverse
15620
+ });
15621
+ const fetchNextPage = async (page, size) => {
15622
+ return this._listSessions({ page, size, reverse });
15623
+ };
15624
+ return new pagination_1.Page(sessionsPage, (session) => new session_1.Session(session.id, this.workspaceId, this._http, session.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(session.configuration) ?? undefined, () => this._ensureWorkspace(), session.created_at, session.is_active, session.uid), fetchNextPage);
15625
+ }
15626
+ async status() {
15627
+ const response = await this._getStatus();
15628
+ return {
15629
+ backfillStatus: Object.fromEntries(Object.entries(response.backfill_status ?? {}).map(([sessionId, job]) => [
15630
+ sessionId,
15631
+ {
15632
+ state: job.state,
15633
+ updatedAt: job.updated_at,
15634
+ docsCopied: job.docs_copied
15635
+ }
15636
+ ]))
15637
+ };
15638
+ }
15639
+ toString() {
15640
+ return `Scope(id='${this.id}', workspaceId='${this.workspaceId}')`;
15641
+ }
15642
+ }
15643
+ exports.Scope = Scope;
15644
+ });
15645
+
15167
15646
  // node_modules/@honcho-ai/sdk/dist/client.js
15168
15647
  var require_client2 = __commonJS(function(exports) {
15169
15648
  Object.defineProperty(exports, "__esModule", { value: true });
15170
15649
  exports.Honcho = undefined;
15171
15650
  var api_version_1 = require_api_version();
15651
+ var conclusions_1 = require_conclusions();
15172
15652
  var client_1 = require_client();
15653
+ var streaming_1 = require_streaming();
15173
15654
  var message_1 = require_message();
15174
15655
  var pagination_1 = require_pagination();
15175
15656
  var peer_1 = require_peer();
15657
+ var scope_1 = require_scope();
15176
15658
  var session_1 = require_session();
15177
15659
  var utils_1 = require_utils();
15178
15660
  var validation_1 = require_validation();
@@ -15185,9 +15667,15 @@ var require_client2 = __commonJS(function(exports) {
15185
15667
  get configuration() {
15186
15668
  return this._configuration;
15187
15669
  }
15670
+ get uid() {
15671
+ return this._uid;
15672
+ }
15188
15673
  get http() {
15189
15674
  return this._http;
15190
15675
  }
15676
+ get conclusions() {
15677
+ return new conclusions_1.WorkspaceConclusions(this._http, this.workspaceId, () => this._ensureWorkspace());
15678
+ }
15191
15679
  get baseURL() {
15192
15680
  return this._http.baseURL;
15193
15681
  }
@@ -15210,13 +15698,15 @@ var require_client2 = __commonJS(function(exports) {
15210
15698
  });
15211
15699
  }
15212
15700
  async _getOrCreateWorkspace(id, params) {
15213
- return this._http.post(`/${api_version_1.API_VERSION}/workspaces`, {
15701
+ const workspace = await this._http.post(`/${api_version_1.API_VERSION}/workspaces`, {
15214
15702
  body: {
15215
15703
  id,
15216
15704
  metadata: params?.metadata,
15217
15705
  configuration: (0, validation_1.workspaceConfigToApi)(params?.configuration)
15218
15706
  }
15219
15707
  });
15708
+ this._uid = workspace.uid;
15709
+ return workspace;
15220
15710
  }
15221
15711
  async _ensureWorkspace() {
15222
15712
  if (!this._workspaceReady) {
@@ -15244,7 +15734,8 @@ var require_client2 = __commonJS(function(exports) {
15244
15734
  },
15245
15735
  query: {
15246
15736
  page: params?.page,
15247
- size: params?.size
15737
+ size: params?.size,
15738
+ reverse: params?.reverse ? "true" : undefined
15248
15739
  }
15249
15740
  });
15250
15741
  }
@@ -15274,13 +15765,35 @@ var require_client2 = __commonJS(function(exports) {
15274
15765
  async _getOrCreatePeer(workspaceId, params) {
15275
15766
  return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/peers`, { body: params });
15276
15767
  }
15768
+ async _getOrCreateScope(workspaceId, params) {
15769
+ return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/scopes`, { body: params });
15770
+ }
15771
+ async _getScope(workspaceId, scopeId) {
15772
+ return this._http.get(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/scopes/${scopeId}`);
15773
+ }
15774
+ async _listScopes(workspaceId, params) {
15775
+ return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/scopes/list`, {
15776
+ body: { filters: params?.filters },
15777
+ query: {
15778
+ page: params?.page,
15779
+ size: params?.size,
15780
+ reverse: params?.reverse ? "true" : undefined,
15781
+ include_session_count: params?.includeSessionCount ? "true" : undefined
15782
+ }
15783
+ });
15784
+ }
15277
15785
  async _listSessions(workspaceId, params) {
15278
15786
  return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/sessions/list`, {
15279
- body: { filters: params?.filters },
15787
+ body: {
15788
+ filters: params?.filters,
15789
+ scope: params?.scope,
15790
+ in_no_scope: params?.inNoScope ? true : undefined
15791
+ },
15280
15792
  query: {
15281
15793
  page: params?.page,
15282
15794
  size: params?.size,
15283
- reverse: params?.reverse ? "true" : undefined
15795
+ reverse: params?.reverse ? "true" : undefined,
15796
+ include_scopes: params?.includeScopes ? "true" : undefined
15284
15797
  }
15285
15798
  });
15286
15799
  }
@@ -15289,7 +15802,22 @@ var require_client2 = __commonJS(function(exports) {
15289
15802
  body: {
15290
15803
  id: params.id,
15291
15804
  metadata: params.metadata,
15292
- configuration: (0, validation_1.sessionConfigToApi)(params.configuration)
15805
+ configuration: (0, validation_1.sessionConfigToApi)(params.configuration),
15806
+ peers: params.peers,
15807
+ scopes: params.scopes
15808
+ }
15809
+ });
15810
+ }
15811
+ async _workspaceChat(workspaceId, params) {
15812
+ await this._ensureWorkspace();
15813
+ return this._http.post(`/${api_version_1.API_VERSION}/workspaces/${workspaceId}/chat`, { body: params });
15814
+ }
15815
+ async _workspaceChatStream(workspaceId, params) {
15816
+ await this._ensureWorkspace();
15817
+ return this._http.stream("POST", `/${api_version_1.API_VERSION}/workspaces/${workspaceId}/chat`, {
15818
+ body: {
15819
+ ...params,
15820
+ stream: true
15293
15821
  }
15294
15822
  });
15295
15823
  }
@@ -15303,7 +15831,7 @@ var require_client2 = __commonJS(function(exports) {
15303
15831
  configuration: (0, validation_1.peerConfigToApi)(validatedConfiguration),
15304
15832
  metadata: validatedMetadata
15305
15833
  });
15306
- return new peer_1.Peer(validatedId, this.workspaceId, this._http, peerData.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peerData.configuration) ?? undefined, () => this._ensureWorkspace(), peerData.created_at);
15834
+ return new peer_1.Peer(validatedId, this.workspaceId, this._http, peerData.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peerData.configuration) ?? undefined, () => this._ensureWorkspace(), peerData.created_at, peerData.uid);
15307
15835
  }
15308
15836
  async peers(options) {
15309
15837
  await this._ensureWorkspace();
@@ -15329,19 +15857,55 @@ var require_client2 = __commonJS(function(exports) {
15329
15857
  reverse
15330
15858
  });
15331
15859
  };
15332
- return new pagination_1.Page(peersPage, (peer) => new peer_1.Peer(peer.id, this.workspaceId, this._http, peer.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peer.configuration) ?? undefined, () => this._ensureWorkspace(), peer.created_at), fetchNextPage);
15860
+ return new pagination_1.Page(peersPage, (peer) => new peer_1.Peer(peer.id, this.workspaceId, this._http, peer.metadata ?? undefined, (0, validation_1.peerConfigFromApi)(peer.configuration) ?? undefined, () => this._ensureWorkspace(), peer.created_at, peer.uid), fetchNextPage);
15333
15861
  }
15334
15862
  async session(id, options) {
15335
15863
  await this._ensureWorkspace();
15336
15864
  const validatedId = validation_1.SessionIdSchema.parse(id);
15337
15865
  const validatedMetadata = options?.metadata ? validation_1.SessionMetadataSchema.parse(options.metadata) : undefined;
15338
15866
  const validatedConfiguration = options?.configuration ? validation_1.SessionConfigSchema.parse(options.configuration) : undefined;
15867
+ const validatedPeers = options?.peers !== undefined ? validation_1.PeerAdditionToApiSchema.parse(options.peers) : undefined;
15868
+ const validatedScopes = options?.scopes !== undefined ? validation_1.SessionScopesSchema.parse(options.scopes.map(utils_1.resolveId)) : undefined;
15339
15869
  const sessionData = await this._getOrCreateSession(this.workspaceId, {
15340
15870
  id: validatedId,
15341
15871
  configuration: validatedConfiguration,
15342
- metadata: validatedMetadata
15872
+ metadata: validatedMetadata,
15873
+ peers: validatedPeers,
15874
+ scopes: validatedScopes
15875
+ });
15876
+ return new session_1.Session(validatedId, this.workspaceId, this._http, sessionData.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(sessionData.configuration) ?? undefined, () => this._ensureWorkspace(), sessionData.created_at, sessionData.is_active, sessionData.uid);
15877
+ }
15878
+ async scope(id, options) {
15879
+ await this._ensureWorkspace();
15880
+ const validatedId = validation_1.ScopeIdSchema.parse(id);
15881
+ const scopeData = await this._getOrCreateScope(this.workspaceId, {
15882
+ id: validatedId,
15883
+ metadata: options?.metadata
15884
+ });
15885
+ return new scope_1.Scope(validatedId, this.workspaceId, this._http, scopeData.metadata ?? undefined, () => this._ensureWorkspace(), scopeData.created_at);
15886
+ }
15887
+ async getScope(id) {
15888
+ await this._ensureWorkspace();
15889
+ const validatedId = validation_1.ScopeIdSchema.parse(id);
15890
+ const scopeData = await this._getScope(this.workspaceId, validatedId);
15891
+ return new scope_1.Scope(validatedId, this.workspaceId, this._http, scopeData.metadata ?? undefined, () => this._ensureWorkspace(), scopeData.created_at);
15892
+ }
15893
+ async scopes(options) {
15894
+ await this._ensureWorkspace();
15895
+ const listOptions = {
15896
+ filters: options?.filters ? validation_1.FilterSchema.parse(options.filters) : undefined,
15897
+ reverse: options?.reverse,
15898
+ includeSessionCount: options?.includeSessionCount
15899
+ };
15900
+ const scopesPage = await this._listScopes(this.workspaceId, {
15901
+ ...listOptions,
15902
+ page: options?.page,
15903
+ size: options?.size
15343
15904
  });
15344
- return new session_1.Session(validatedId, this.workspaceId, this._http, sessionData.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(sessionData.configuration) ?? undefined, () => this._ensureWorkspace(), sessionData.created_at, sessionData.is_active);
15905
+ const fetchNextPage = async (page, size) => {
15906
+ return this._listScopes(this.workspaceId, { ...listOptions, page, size });
15907
+ };
15908
+ return new pagination_1.Page(scopesPage, (scope) => new scope_1.Scope(scope.id, this.workspaceId, this._http, scope.metadata ?? undefined, () => this._ensureWorkspace(), scope.created_at, scope.session_count), fetchNextPage);
15345
15909
  }
15346
15910
  async sessions(options) {
15347
15911
  await this._ensureWorkspace();
@@ -15349,25 +15913,32 @@ var require_client2 = __commonJS(function(exports) {
15349
15913
  "filters",
15350
15914
  "page",
15351
15915
  "size",
15352
- "reverse"
15916
+ "reverse",
15917
+ "scope",
15918
+ "inNoScope",
15919
+ "includeScopes"
15353
15920
  ]);
15354
15921
  const validatedFilter = normalizedOptions.filters ? validation_1.FilterSchema.parse(normalizedOptions.filters) : undefined;
15355
- const reverse = normalizedOptions.reverse;
15356
- const sessionsPage = await this._listSessions(this.workspaceId, {
15922
+ const listOptions = {
15357
15923
  filters: validatedFilter,
15924
+ reverse: normalizedOptions.reverse,
15925
+ scope: normalizedOptions.scope,
15926
+ inNoScope: normalizedOptions.inNoScope,
15927
+ includeScopes: normalizedOptions.includeScopes
15928
+ };
15929
+ const sessionsPage = await this._listSessions(this.workspaceId, {
15930
+ ...listOptions,
15358
15931
  page: normalizedOptions.page,
15359
- size: normalizedOptions.size,
15360
- reverse
15932
+ size: normalizedOptions.size
15361
15933
  });
15362
15934
  const fetchNextPage = async (page, size) => {
15363
15935
  return this._listSessions(this.workspaceId, {
15364
- filters: validatedFilter,
15936
+ ...listOptions,
15365
15937
  page,
15366
- size,
15367
- reverse
15938
+ size
15368
15939
  });
15369
15940
  };
15370
- return new pagination_1.Page(sessionsPage, (session) => new session_1.Session(session.id, this.workspaceId, this._http, session.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(session.configuration) ?? undefined, () => this._ensureWorkspace(), session.created_at, session.is_active), fetchNextPage);
15941
+ return new pagination_1.Page(sessionsPage, (session) => new session_1.Session(session.id, this.workspaceId, this._http, session.metadata ?? undefined, (0, validation_1.sessionConfigFromApi)(session.configuration) ?? undefined, () => this._ensureWorkspace(), session.created_at, session.is_active, session.uid, session.scopes), fetchNextPage);
15371
15942
  }
15372
15943
  async getMetadata() {
15373
15944
  await this._ensureWorkspace();
@@ -15407,19 +15978,23 @@ var require_client2 = __commonJS(function(exports) {
15407
15978
  const normalizedOptions = (0, validation_1.normalizeListOptions)(options, [
15408
15979
  "filters",
15409
15980
  "page",
15410
- "size"
15981
+ "size",
15982
+ "reverse"
15411
15983
  ]);
15412
15984
  const validatedFilter = normalizedOptions.filters ? validation_1.FilterSchema.parse(normalizedOptions.filters) : undefined;
15985
+ const reverse = normalizedOptions.reverse;
15413
15986
  const workspacesPage = await this._listWorkspaces({
15414
15987
  filters: validatedFilter,
15415
15988
  page: normalizedOptions.page,
15416
- size: normalizedOptions.size
15989
+ size: normalizedOptions.size,
15990
+ reverse
15417
15991
  });
15418
15992
  const fetchNextPage = async (page, size) => {
15419
15993
  return this._listWorkspaces({
15420
15994
  filters: validatedFilter,
15421
15995
  page,
15422
- size
15996
+ size,
15997
+ reverse
15423
15998
  });
15424
15999
  };
15425
16000
  return new pagination_1.Page(workspacesPage, (workspace) => workspace.id, fetchNextPage);
@@ -15431,14 +16006,47 @@ var require_client2 = __commonJS(function(exports) {
15431
16006
  await this._ensureWorkspace();
15432
16007
  const validatedQuery = validation_1.SearchQuerySchema.parse(query);
15433
16008
  const validatedFilters = options?.filters ? validation_1.FilterSchema.parse(options.filters) : undefined;
16009
+ const validatedScope = options?.scope !== undefined ? validation_1.ScopeIdSchema.parse((0, utils_1.resolveId)(options.scope)) : undefined;
15434
16010
  const validatedLimit = options?.limit ? validation_1.LimitSchema.parse(options.limit) : undefined;
15435
16011
  const response = await this._searchWorkspace(this.workspaceId, {
15436
16012
  query: validatedQuery,
15437
16013
  filters: validatedFilters,
16014
+ scope: validatedScope,
15438
16015
  limit: validatedLimit
15439
16016
  });
15440
16017
  return response.map(message_1.Message.fromApiResponse);
15441
16018
  }
16019
+ async chat(query, options) {
16020
+ const validatedQuery = validation_1.SearchQuerySchema.parse(query);
16021
+ const resolvedSessionId = options?.session ? (0, utils_1.resolveId)(options.session) : undefined;
16022
+ const response = await this._workspaceChat(this.workspaceId, {
16023
+ query: validatedQuery,
16024
+ stream: false,
16025
+ session_id: resolvedSessionId,
16026
+ reasoning_level: options?.reasoningLevel,
16027
+ response_format: options?.responseFormat,
16028
+ scope: options?.scope,
16029
+ include_evidence: options?.includeEvidence ? true : undefined
16030
+ });
16031
+ const content = response.content || null;
16032
+ if (!options?.includeEvidence) {
16033
+ return content;
16034
+ }
16035
+ return { content, evidence: response.evidence ?? null };
16036
+ }
16037
+ async chatStream(query, options) {
16038
+ const validatedQuery = validation_1.SearchQuerySchema.parse(query);
16039
+ const resolvedSessionId = options?.session ? (0, utils_1.resolveId)(options.session) : undefined;
16040
+ const response = await this._workspaceChatStream(this.workspaceId, {
16041
+ query: validatedQuery,
16042
+ session_id: resolvedSessionId,
16043
+ reasoning_level: options?.reasoningLevel,
16044
+ response_format: options?.responseFormat,
16045
+ scope: options?.scope,
16046
+ include_evidence: options?.includeEvidence ? true : undefined
16047
+ });
16048
+ return (0, streaming_1.createDialecticStream)(response);
16049
+ }
15442
16050
  async queueStatus(options) {
15443
16051
  await this._ensureWorkspace();
15444
16052
  const observerId = options?.observer ? (0, utils_1.resolveId)(options.observer) : undefined;
@@ -15468,6 +16076,20 @@ var require_client2 = __commonJS(function(exports) {
15468
16076
  }
15469
16077
  });
15470
16078
  }
16079
+ async dreams(options) {
16080
+ await this._ensureWorkspace();
16081
+ const body = {};
16082
+ if (options?.observed)
16083
+ body.observed_id = (0, utils_1.resolveId)(options.observed);
16084
+ if (options?.observer)
16085
+ body.observer_id = (0, utils_1.resolveId)(options.observer);
16086
+ const fetchPage = (page, size) => this._http.post(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/dreams/list`, { body, query: { page, size } });
16087
+ return new pagination_1.Page(await fetchPage(options?.page, options?.size), undefined, fetchPage);
16088
+ }
16089
+ async getDream(runId) {
16090
+ await this._ensureWorkspace();
16091
+ return this._http.get(`/${api_version_1.API_VERSION}/workspaces/${this.workspaceId}/dreams/${runId}`);
16092
+ }
15471
16093
  toString() {
15472
16094
  return `Honcho(workspaceId='${this.workspaceId}', baseURL='${this._http.baseURL}')`;
15473
16095
  }
@@ -15478,7 +16100,7 @@ var require_client2 = __commonJS(function(exports) {
15478
16100
  // node_modules/@honcho-ai/sdk/dist/index.js
15479
16101
  var require_dist = __commonJS(function(exports) {
15480
16102
  Object.defineProperty(exports, "__esModule", { value: true });
15481
- exports.Summary = exports.SessionSummaries = exports.SessionContext = exports.Session = exports.PeerContext = exports.Peer = exports.Page = exports.Message = exports.DialecticStreamResponse = exports.UnprocessableEntityError = exports.TimeoutError = exports.ServerError = exports.RateLimitError = exports.PermissionDeniedError = exports.NotFoundError = exports.HonchoError = exports.ConnectionError = exports.ConflictError = exports.BadRequestError = exports.AuthenticationError = exports.ConclusionScope = exports.Conclusion = exports.Honcho = undefined;
16103
+ exports.Summary = exports.SessionSummaries = exports.SessionContext = exports.Session = exports.Scope = exports.PeerContext = exports.Peer = exports.Page = exports.Message = exports.DialecticStreamResponse = exports.UnprocessableEntityError = exports.TimeoutError = exports.ServerError = exports.RateLimitError = exports.PermissionDeniedError = exports.NotFoundError = exports.HonchoError = exports.ConnectionError = exports.ConflictError = exports.BadRequestError = exports.AuthenticationError = exports.WorkspaceConclusions = exports.ConclusionsView = exports.ConclusionScope = exports.Conclusion = exports.Honcho = undefined;
15482
16104
  var client_1 = require_client2();
15483
16105
  Object.defineProperty(exports, "Honcho", { enumerable: true, get: function() {
15484
16106
  return client_1.Honcho;
@@ -15488,7 +16110,13 @@ var require_dist = __commonJS(function(exports) {
15488
16110
  return conclusions_1.Conclusion;
15489
16111
  } });
15490
16112
  Object.defineProperty(exports, "ConclusionScope", { enumerable: true, get: function() {
15491
- return conclusions_1.ConclusionScope;
16113
+ return conclusions_1.ConclusionsView;
16114
+ } });
16115
+ Object.defineProperty(exports, "ConclusionsView", { enumerable: true, get: function() {
16116
+ return conclusions_1.ConclusionsView;
16117
+ } });
16118
+ Object.defineProperty(exports, "WorkspaceConclusions", { enumerable: true, get: function() {
16119
+ return conclusions_1.WorkspaceConclusions;
15492
16120
  } });
15493
16121
  var errors_1 = require_errors();
15494
16122
  Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function() {
@@ -15543,6 +16171,10 @@ var require_dist = __commonJS(function(exports) {
15543
16171
  Object.defineProperty(exports, "PeerContext", { enumerable: true, get: function() {
15544
16172
  return peer_1.PeerContext;
15545
16173
  } });
16174
+ var scope_1 = require_scope();
16175
+ Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
16176
+ return scope_1.Scope;
16177
+ } });
15546
16178
  var session_1 = require_session();
15547
16179
  Object.defineProperty(exports, "Session", { enumerable: true, get: function() {
15548
16180
  return session_1.Session;
@@ -15560,277 +16192,452 @@ var require_dist = __commonJS(function(exports) {
15560
16192
  });
15561
16193
 
15562
16194
  // src/hooks/save-user-message.ts
15563
- var import_sdk = __toESM(require_dist(), 1);
16195
+ var import_sdk2 = __toESM(require_dist(), 1);
15564
16196
 
15565
16197
  // src/config.ts
15566
- import { homedir as homedir2 } from "os";
15567
- import { join as join3, basename, dirname, resolve, sep } from "path";
16198
+ import { join as join3, dirname as dirname2 } from "path";
15568
16199
  import { fileURLToPath } from "url";
15569
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
16200
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
16201
+
16202
+ // node_modules/@honcho-ai/harness-plugin-core/dist/config.js
16203
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
16204
+ import { homedir } from "node:os";
16205
+ import { join as join2 } from "node:path";
16206
+
16207
+ // node_modules/@honcho-ai/harness-plugin-core/dist/legacy/v01.js
16208
+ var isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
16209
+ var str = (v) => typeof v === "string" && v ? v : undefined;
16210
+ function v01Reader(file, host) {
16211
+ const hosts = isObj(file.hosts) ? file.hosts : {};
16212
+ const v1 = typeof file.schemaVersion === "number" && file.schemaVersion >= 1;
16213
+ const pick = (b) => {
16214
+ const o = isObj(b) ? b : {};
16215
+ if (v1)
16216
+ return { apiKey: isObj(o.auth) ? str(o.auth.apiKey) : undefined, peerName: str(o.peerName), workspace: str(o.workspace), baseUrl: str(o.baseUrl) };
16217
+ return {
16218
+ apiKey: (isObj(o.auth) ? str(o.auth.apiKey) : undefined) ?? str(o.apiKey),
16219
+ peerName: str(o.peerName),
16220
+ workspace: str(o.workspace) ?? str(o.workspaceId),
16221
+ baseUrl: str(o.baseUrl) ?? str(o.environmentUrl) ?? (isObj(o.endpoint) ? str(o.endpoint.baseUrl) : undefined)
16222
+ };
16223
+ };
16224
+ const own = pick(hosts[host]);
16225
+ const top = pick(file);
16226
+ return {
16227
+ apiKey: own.apiKey ?? top.apiKey,
16228
+ peerName: own.peerName ?? top.peerName,
16229
+ workspace: own.workspace ?? top.workspace,
16230
+ aiPeer: isObj(hosts[host]) ? str(hosts[host].aiPeer) : undefined,
16231
+ baseUrl: own.baseUrl ?? top.baseUrl
16232
+ };
16233
+ }
15570
16234
 
15571
- // src/git.ts
15572
- import { execSync } from "child_process";
15573
- import { existsSync } from "fs";
15574
- import { join } from "path";
15575
- function isGitRepo(cwd) {
15576
- return existsSync(join(cwd, ".git"));
16235
+ // node_modules/@honcho-ai/harness-plugin-core/dist/oauth.js
16236
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
16237
+ import { dirname, join } from "node:path";
16238
+ var OAUTH_TOKEN_URL = "https://api.honcho.dev/oauth/token";
16239
+ var OAUTH_SCOPE = "write";
16240
+ var REQUEST_TIMEOUT_MS = 1e4;
16241
+ var REFRESH_SKEW_S = 60;
16242
+ var LOCK_STALE_MS = REQUEST_TIMEOUT_MS + 5000;
16243
+ var LOCK_WAIT_MS = LOCK_STALE_MS + 5000;
16244
+ var PERMANENT_ERRORS = new Set(["invalid_grant", "invalid_client", "unauthorized_client"]);
16245
+
16246
+ class OAuthError extends Error {
16247
+ code;
16248
+ constructor(code, description) {
16249
+ super(description || code);
16250
+ this.code = code;
16251
+ this.name = "OAuthError";
16252
+ }
16253
+ }
16254
+ function isCloud(baseUrl) {
16255
+ return normalizeBaseUrl(baseUrl || DEFAULT_BASE_URL) === DEFAULT_BASE_URL;
16256
+ }
16257
+ function accessValid(t, skewS = REFRESH_SKEW_S, nowS = Date.now() / 1000) {
16258
+ return !!t?.accessToken && nowS < t.accessExpiresAt - skewS;
15577
16259
  }
15578
- function gitCommand(cwd, args) {
16260
+ async function post(url, form, t) {
16261
+ const f = t?.fetch ?? fetch;
16262
+ let res;
15579
16263
  try {
15580
- return execSync(`git ${args}`, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
16264
+ res = await f(url, {
16265
+ method: "POST",
16266
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
16267
+ body: new URLSearchParams(form).toString(),
16268
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
16269
+ });
16270
+ } catch (e) {
16271
+ throw new OAuthError("connection_error", `could not reach ${url}: ${e.message}`);
16272
+ }
16273
+ let body = null;
16274
+ try {
16275
+ body = await res.json();
15581
16276
  } catch {
15582
- return null;
16277
+ body = null;
15583
16278
  }
16279
+ return { status: res.status, body };
15584
16280
  }
15585
- function captureGitState(cwd) {
15586
- if (!isGitRepo(cwd)) {
15587
- return null;
16281
+ function errorOf(r) {
16282
+ const b = r.body;
16283
+ if (b && typeof b === "object" && typeof b.error === "string")
16284
+ return new OAuthError(b.error, b.error_description);
16285
+ return new OAuthError("invalid_response");
16286
+ }
16287
+ function tokensFrom(body, clientId, prev) {
16288
+ if (!body || typeof body.access_token !== "string" || !Number.isFinite(Number(body.expires_in))) {
16289
+ throw new OAuthError("invalid_response", "malformed token response");
15588
16290
  }
15589
- const branch = gitCommand(cwd, "rev-parse --abbrev-ref HEAD") || "unknown";
15590
- const commit = gitCommand(cwd, "rev-parse --short HEAD") || "unknown";
15591
- const commitMessage = gitCommand(cwd, "log -1 --format=%s") || "";
15592
- const statusOutput = gitCommand(cwd, "status --porcelain") || "";
15593
- const isDirty = statusOutput.length > 0;
15594
- const dirtyFiles = isDirty ? statusOutput.split(`
15595
- `).filter((line) => line.trim()).map((line) => line.slice(3).trim()).slice(0, 20) : [];
15596
16291
  return {
15597
- branch,
15598
- commit,
15599
- commitMessage,
15600
- isDirty,
15601
- dirtyFiles,
15602
- timestamp: new Date().toISOString()
16292
+ accessToken: body.access_token,
16293
+ refreshToken: body.refresh_token || prev?.refreshToken || "",
16294
+ accessExpiresAt: Math.floor(Date.now() / 1000) + Number(body.expires_in),
16295
+ clientId,
16296
+ scope: body.scope || prev?.scope || OAUTH_SCOPE
15603
16297
  };
15604
16298
  }
15605
-
15606
- // src/cache.ts
15607
- import { homedir } from "os";
15608
- import { join as join2 } from "path";
15609
- import { existsSync as existsSync2, readFileSync, writeFileSync, mkdirSync } from "fs";
15610
- var CACHE_DIR = join2(homedir(), ".honcho");
15611
- var ID_CACHE_FILE = join2(CACHE_DIR, "cache.json");
15612
- var CONTEXT_CACHE_FILE = join2(CACHE_DIR, "context-cache.json");
15613
- function ensureCacheDir() {
15614
- if (!existsSync2(CACHE_DIR)) {
15615
- mkdirSync(CACHE_DIR, { recursive: true });
15616
- }
16299
+ async function refreshAccessToken(prev, opts = {}) {
16300
+ const r = await post(opts.tokenUrl ?? OAUTH_TOKEN_URL, { grant_type: "refresh_token", refresh_token: prev.refreshToken, client_id: prev.clientId }, opts);
16301
+ if (r.status !== 200)
16302
+ throw errorOf(r);
16303
+ return tokensFrom(r.body, prev.clientId, prev);
15617
16304
  }
15618
- function loadIdCache() {
15619
- ensureCacheDir();
15620
- if (!existsSync2(ID_CACHE_FILE)) {
15621
- return {};
15622
- }
15623
- try {
15624
- return JSON.parse(readFileSync(ID_CACHE_FILE, "utf-8"));
15625
- } catch {
16305
+ function isObj2(v) {
16306
+ return v !== null && typeof v === "object" && !Array.isArray(v);
16307
+ }
16308
+ function asTokens(v) {
16309
+ if (!isObj2(v) || typeof v.accessToken !== "string" || !v.accessToken)
16310
+ return;
16311
+ return {
16312
+ accessToken: v.accessToken,
16313
+ refreshToken: typeof v.refreshToken === "string" ? v.refreshToken : "",
16314
+ accessExpiresAt: Number(v.accessExpiresAt) || 0,
16315
+ clientId: typeof v.clientId === "string" ? v.clientId : "",
16316
+ scope: typeof v.scope === "string" ? v.scope : ""
16317
+ };
16318
+ }
16319
+ function readFile(path) {
16320
+ if (!existsSync(path))
15626
16321
  return {};
15627
- }
16322
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
16323
+ return isObj2(parsed) ? parsed : {};
15628
16324
  }
15629
- function saveIdCache(cache) {
15630
- ensureCacheDir();
15631
- writeFileSync(ID_CACHE_FILE, JSON.stringify(cache, null, 2));
16325
+ function readGrant(file, host, legacy) {
16326
+ return asTokens(effectiveBlock(file, host, legacy).oauth);
15632
16327
  }
15633
- function setCachedSessionId(cwd, name, id, instanceId) {
15634
- const cache = loadIdCache();
15635
- if (!cache.sessions)
15636
- cache.sessions = {};
15637
- cache.sessions[cwd] = { name, id, updatedAt: new Date().toISOString(), instanceId };
15638
- saveIdCache(cache);
16328
+ function holderAlive(token, ageMs) {
16329
+ if (token === "")
16330
+ return ageMs < 1000;
16331
+ const pid = Number(token.split(":")[0]);
16332
+ if (!Number.isInteger(pid) || pid <= 0)
16333
+ return true;
16334
+ try {
16335
+ process.kill(pid, 0);
16336
+ return true;
16337
+ } catch (e) {
16338
+ return e.code === "EPERM";
16339
+ }
15639
16340
  }
15640
- function getLastActiveCwd() {
15641
- const cache = loadIdCache();
15642
- if (!cache.sessions)
15643
- return null;
15644
- let latest = null;
15645
- for (const [cwd, entry] of Object.entries(cache.sessions)) {
15646
- if (!latest || entry.updatedAt > latest.updatedAt) {
15647
- latest = { cwd, updatedAt: entry.updatedAt };
16341
+ async function withConfigLock(path, fn) {
16342
+ const lock = `${path}.lock`;
16343
+ mkdirSync(dirname(path), { recursive: true });
16344
+ const start = Date.now();
16345
+ let fd;
16346
+ while (fd === undefined) {
16347
+ try {
16348
+ fd = openSync(lock, "wx", 384);
16349
+ } catch (e) {
16350
+ if (e.code !== "EEXIST")
16351
+ throw e;
16352
+ try {
16353
+ const age = Date.now() - statSync(lock).mtimeMs;
16354
+ if (age > LOCK_STALE_MS || !holderAlive(readFileSync(lock, "utf-8"), age))
16355
+ unlinkSync(lock);
16356
+ } catch {}
16357
+ if (Date.now() - start > LOCK_WAIT_MS)
16358
+ throw new Error(`timed out waiting for ${lock}`);
16359
+ await new Promise((r) => setTimeout(r, 50 + Math.random() * 50));
15648
16360
  }
15649
16361
  }
15650
- return latest?.cwd || null;
16362
+ const token = `${process.pid}:${Math.random().toString(36).slice(2)}`;
16363
+ try {
16364
+ writeFileSync(fd, token);
16365
+ return await fn();
16366
+ } finally {
16367
+ closeSync(fd);
16368
+ try {
16369
+ if (readFileSync(lock, "utf-8") === token)
16370
+ unlinkSync(lock);
16371
+ } catch {}
16372
+ }
15651
16373
  }
15652
- function getClaudeInstanceId() {
15653
- const cache = loadIdCache();
15654
- return cache.claudeInstanceId || null;
16374
+ function writeFileAtomic(path, data) {
16375
+ const tmp = join(dirname(path), `.${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2)}.tmp`);
16376
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + `
16377
+ `, { mode: 384 });
16378
+ renameSync(tmp, path);
15655
16379
  }
15656
- function setClaudeInstanceId(instanceId) {
15657
- const cache = loadIdCache();
15658
- cache.claudeInstanceId = instanceId;
15659
- saveIdCache(cache);
16380
+ async function updateConfigFile(path, mutate) {
16381
+ await withConfigLock(path, async () => {
16382
+ const file = readFile(path);
16383
+ mutate(file);
16384
+ writeFileAtomic(path, file);
16385
+ });
15660
16386
  }
15661
- function getInstanceIdForCwd(cwd) {
15662
- const cache = loadIdCache();
15663
- return cache.sessions?.[cwd]?.instanceId ?? null;
16387
+ function setGrant(file, host, tokens) {
16388
+ const block = hostBlock(file, host);
16389
+ if (tokens)
16390
+ block.oauth = tokens;
16391
+ else
16392
+ delete block.oauth;
15664
16393
  }
15665
- var CONTEXT_CACHE_KNOWN_KEYS = new Set([
15666
- "claudeContext",
15667
- "summaries",
15668
- "messageCount"
15669
- ]);
15670
- function loadContextCache() {
15671
- ensureCacheDir();
15672
- if (!existsSync2(CONTEXT_CACHE_FILE)) {
15673
- return {};
15674
- }
16394
+ function serverOf(block, baseUrl, env) {
16395
+ return baseUrl ?? (env.HONCHO_BASE_URL || undefined) ?? (typeof block.baseUrl === "string" && block.baseUrl ? block.baseUrl : undefined);
16396
+ }
16397
+ function pickCredential(file, opts) {
16398
+ const env = opts.env ?? process.env;
16399
+ if (env.HONCHO_API_KEY)
16400
+ return { token: env.HONCHO_API_KEY, source: "env" };
16401
+ const block = effectiveBlock(file, opts.host, opts.legacy);
16402
+ const g = isCloud(serverOf(block, opts.baseUrl, env)) ? asTokens(block.oauth) : undefined;
16403
+ if (g)
16404
+ return { token: g.accessToken, source: "oauth", expiresAt: g.accessExpiresAt, ...accessValid(g, 0) ? {} : { expired: true } };
16405
+ return typeof block.apiKey === "string" && block.apiKey ? { token: block.apiKey, source: "apiKey" } : null;
16406
+ }
16407
+ async function ensureFreshCredential(opts) {
16408
+ const env = opts.env ?? process.env;
16409
+ if (env.HONCHO_API_KEY)
16410
+ return { token: env.HONCHO_API_KEY, source: "env" };
16411
+ let file;
15675
16412
  try {
15676
- const raw = JSON.parse(readFileSync(CONTEXT_CACHE_FILE, "utf-8"));
15677
- let cleaned = false;
15678
- for (const key of Object.keys(raw)) {
15679
- if (!CONTEXT_CACHE_KNOWN_KEYS.has(key)) {
15680
- delete raw[key];
15681
- cleaned = true;
15682
- }
15683
- }
15684
- if (cleaned) {
15685
- writeFileSync(CONTEXT_CACHE_FILE, JSON.stringify(raw, null, 2));
15686
- }
15687
- return raw;
16413
+ file = readFile(opts.path);
15688
16414
  } catch {
15689
- return {};
16415
+ file = {};
16416
+ }
16417
+ const block = effectiveBlock(file, opts.host, opts.legacy);
16418
+ const g = isCloud(serverOf(block, opts.baseUrl, env)) ? asTokens(block.oauth) : undefined;
16419
+ if (!g || accessValid(g) || !g.refreshToken)
16420
+ return pickCredential(file, opts);
16421
+ let error;
16422
+ try {
16423
+ await withConfigLock(opts.path, async () => {
16424
+ const current = readGrant(readFile(opts.path), opts.host, opts.legacy);
16425
+ if (!current || accessValid(current))
16426
+ return;
16427
+ const next = await refreshAccessToken(current, opts);
16428
+ const latest = readFile(opts.path);
16429
+ setGrant(latest, opts.host, next);
16430
+ writeFileAtomic(opts.path, latest);
16431
+ });
16432
+ } catch (e) {
16433
+ error = e instanceof OAuthError ? e.code : e.message;
15690
16434
  }
16435
+ try {
16436
+ file = readFile(opts.path);
16437
+ } catch {}
16438
+ const cred = pickCredential(file, opts);
16439
+ if (cred && error) {
16440
+ cred.error = error;
16441
+ if (PERMANENT_ERRORS.has(error))
16442
+ cred.reauthRequired = true;
16443
+ }
16444
+ return cred;
15691
16445
  }
15692
- function saveContextCache(cache) {
15693
- ensureCacheDir();
15694
- writeFileSync(CONTEXT_CACHE_FILE, JSON.stringify(cache, null, 2));
16446
+
16447
+ // node_modules/@honcho-ai/harness-plugin-core/dist/config.js
16448
+ var DEFAULT_BASE_URL = "https://api.honcho.dev";
16449
+ var CONFIG_SCHEMA_VERSION = 2;
16450
+ function isObj3(v) {
16451
+ return v !== null && typeof v === "object" && !Array.isArray(v);
15695
16452
  }
15696
- function incrementMessageCount() {
15697
- const cache = loadContextCache();
15698
- cache.messageCount = (cache.messageCount || 0) + 1;
15699
- saveContextCache(cache);
15700
- return cache.messageCount;
16453
+ function str2(v) {
16454
+ return typeof v === "string" && v ? v : undefined;
15701
16455
  }
15702
- function getMessageCount() {
15703
- const cache = loadContextCache();
15704
- return cache.messageCount || 0;
16456
+ function normalizeBaseUrl(input) {
16457
+ let s = input.trim();
16458
+ if (!s)
16459
+ return s;
16460
+ if (!s.startsWith("http://") && !s.startsWith("https://")) {
16461
+ const host = s.split("/")[0].split(":")[0].toLowerCase();
16462
+ const local = host === "localhost" || host === "127.0.0.1" || host === "::1";
16463
+ s = `${local ? "http" : "https"}://${s}`;
16464
+ }
16465
+ try {
16466
+ const u = new URL(s);
16467
+ u.hostname = u.hostname.toLowerCase();
16468
+ const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");
16469
+ return `${u.protocol}//${u.host}${path}`;
16470
+ } catch {
16471
+ return s;
16472
+ }
15705
16473
  }
15706
- function resetMessageCount() {
15707
- const cache = loadContextCache();
15708
- cache.messageCount = 0;
15709
- saveContextCache(cache);
16474
+ function resolveConfig(file, opts) {
16475
+ const env = opts.env ?? process.env;
16476
+ const { host } = opts;
16477
+ const block = effectiveBlock(file, host, opts.legacy);
16478
+ return {
16479
+ host,
16480
+ peerName: str2(env.HONCHO_PEER_NAME) ?? str2(block.peerName) ?? str2(env.USER) ?? str2(env.USERNAME) ?? "user",
16481
+ workspace: str2(env.HONCHO_WORKSPACE) ?? str2(block.workspace) ?? opts.defaults?.workspace ?? host,
16482
+ aiPeer: str2(env.HONCHO_AI_PEER) ?? str2(block.aiPeer) ?? opts.defaults?.aiPeer ?? host,
16483
+ baseUrl: normalizeBaseUrl(str2(env.HONCHO_BASE_URL) ?? str2(block.baseUrl) ?? DEFAULT_BASE_URL),
16484
+ warnings: checkConfig(file).map((i) => i.message)
16485
+ };
15710
16486
  }
15711
- var GIT_STATE_FILE = join2(CACHE_DIR, "git-state.json");
15712
- function loadGitStateCache() {
15713
- ensureCacheDir();
15714
- if (!existsSync2(GIT_STATE_FILE)) {
16487
+ function configPath(env = process.env) {
16488
+ if (env.HONCHO_CONFIG_PATH)
16489
+ return env.HONCHO_CONFIG_PATH;
16490
+ const home = env.HOME || env.USERPROFILE || homedir();
16491
+ return join2(home, ".honcho", "config.json");
16492
+ }
16493
+ function readConfigFile(env = process.env) {
16494
+ const path = configPath(env);
16495
+ if (!existsSync2(path))
15715
16496
  return {};
15716
- }
15717
16497
  try {
15718
- return JSON.parse(readFileSync(GIT_STATE_FILE, "utf-8"));
16498
+ const parsed = JSON.parse(readFileSync2(path, "utf-8"));
16499
+ return isObj3(parsed) ? parsed : {};
15719
16500
  } catch {
15720
16501
  return {};
15721
16502
  }
15722
16503
  }
15723
- function saveGitStateCache(cache) {
15724
- ensureCacheDir();
15725
- writeFileSync(GIT_STATE_FILE, JSON.stringify(cache, null, 2));
16504
+ async function saveHost(path, host, patch, legacy) {
16505
+ await updateConfigFile(path, (file) => {
16506
+ if (isNewer(file))
16507
+ throw new Error(`${path} was written by a newer Honcho plugin; update this one.`);
16508
+ const block = writeBlock(file, host, hostMigration(file, host, [], legacy));
16509
+ if ("baseUrl" in patch && !("apiKey" in patch) && !sameServer(patch.baseUrl, str2(block.baseUrl)))
16510
+ delete block.apiKey;
16511
+ for (const [k, v] of Object.entries(patch)) {
16512
+ if (v === undefined)
16513
+ delete block[k];
16514
+ else
16515
+ block[k] = v;
16516
+ }
16517
+ block.schemaVersion = CONFIG_SCHEMA_VERSION;
16518
+ });
16519
+ }
16520
+ var MOVABLE = ["apiKey", "peerName", "workspace", "aiPeer", "baseUrl"];
16521
+ function isNewer(file) {
16522
+ return isObj3(file) && typeof file.schemaVersion === "number" && file.schemaVersion > CONFIG_SCHEMA_VERSION;
15726
16523
  }
15727
- function getCachedGitState(cwd) {
15728
- const cache = loadGitStateCache();
15729
- return cache[cwd] || null;
16524
+ function isMigrated(block) {
16525
+ return isObj3(block) && typeof block.schemaVersion === "number" && block.schemaVersion >= CONFIG_SCHEMA_VERSION;
15730
16526
  }
15731
- function setCachedGitState(cwd, state) {
15732
- const cache = loadGitStateCache();
15733
- cache[cwd] = state;
15734
- saveGitStateCache(cache);
16527
+ function sameServer(a, b) {
16528
+ return normalizeBaseUrl(a ?? DEFAULT_BASE_URL) === normalizeBaseUrl(b ?? DEFAULT_BASE_URL);
15735
16529
  }
15736
- function detectGitChanges(previous, current) {
15737
- const changes = [];
15738
- if (!previous) {
15739
- changes.push({
15740
- type: "initial",
15741
- description: `Session started on branch '${current.branch}' at ${current.commit}`
15742
- });
15743
- return changes;
15744
- }
15745
- if (previous.branch !== current.branch) {
15746
- changes.push({
15747
- type: "branch_switch",
15748
- description: `Branch switched from '${previous.branch}' to '${current.branch}'`,
15749
- from: previous.branch,
15750
- to: current.branch
15751
- });
15752
- }
15753
- if (previous.commit !== current.commit) {
15754
- changes.push({
15755
- type: "new_commits",
15756
- description: `New commit: ${current.commit} - ${current.commitMessage}`,
15757
- from: previous.commit,
15758
- to: current.commit
15759
- });
15760
- }
15761
- if (!previous.isDirty && current.isDirty) {
15762
- changes.push({
15763
- type: "files_changed",
15764
- description: `Uncommitted changes detected: ${current.dirtyFiles.slice(0, 5).join(", ")}${current.dirtyFiles.length > 5 ? "..." : ""}`
15765
- });
15766
- }
15767
- return changes;
16530
+ var LEGACY_HOST_KEYS = ["auth", "endpoint", "environmentUrl", "workspaceId"];
16531
+ function isGrant(v) {
16532
+ return isObj3(v) && typeof v.accessToken === "string" && v.accessToken !== "";
15768
16533
  }
15769
- var MAX_MESSAGE_SIZE = 24000;
15770
- function chunkContent(content, maxSize = MAX_MESSAGE_SIZE) {
15771
- if (content.length <= maxSize) {
15772
- return [content];
15773
- }
15774
- const chunks = [];
15775
- let remaining = content;
15776
- while (remaining.length > 0) {
15777
- if (remaining.length <= maxSize) {
15778
- chunks.push(remaining);
15779
- break;
15780
- }
15781
- let splitIndex = remaining.lastIndexOf(`
15782
- `, maxSize);
15783
- if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
15784
- splitIndex = remaining.lastIndexOf(" ", maxSize);
15785
- }
15786
- if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
15787
- splitIndex = maxSize;
15788
- }
15789
- chunks.push(remaining.slice(0, splitIndex));
15790
- remaining = remaining.slice(splitIndex).trimStart();
15791
- }
15792
- if (chunks.length > 1) {
15793
- return chunks.map((chunk, i) => `[Part ${i + 1}/${chunks.length}] ${chunk}`);
15794
- }
15795
- return chunks;
16534
+ function legacyGrantOf(b) {
16535
+ return !isGrant(b.oauth) && isObj3(b.auth) && isObj3(b.auth.oauth) ? b.auth.oauth : undefined;
15796
16536
  }
15797
- var HONCHO_MAX_BATCH = 100;
15798
- async function addMessagesBatched(session, messages, resolveFallback) {
15799
- let active = session;
15800
- let usedFallback = false;
15801
- for (let i = 0;i < messages.length; i += HONCHO_MAX_BATCH) {
15802
- const batch = messages.slice(i, i + HONCHO_MAX_BATCH);
15803
- try {
15804
- await active.addMessages(batch);
15805
- } catch (e) {
15806
- if (usedFallback || !resolveFallback)
15807
- throw e;
15808
- active = await resolveFallback(e);
15809
- usedFallback = true;
15810
- await active.addMessages(batch);
16537
+ function checkConfig(file) {
16538
+ if (!isObj3(file))
16539
+ return [];
16540
+ if (isNewer(file)) {
16541
+ return [{ path: "schemaVersion", message: `This file is schema version ${file.schemaVersion}, newer than this plugin understands; update the plugin.` }];
16542
+ }
16543
+ const issues = [];
16544
+ const hosts = isObj3(file.hosts) ? file.hosts : {};
16545
+ const byWorkspace = new Map;
16546
+ for (const h of Object.keys(hosts).filter((k) => isObj3(hosts[k]))) {
16547
+ const block = hosts[h];
16548
+ const peer = str2(block.peerName);
16549
+ if (!peer)
16550
+ continue;
16551
+ const ws = str2(block.workspace) ?? h;
16552
+ const peers = byWorkspace.get(ws) ?? new Map;
16553
+ peers.set(peer, [...peers.get(peer) ?? [], h]);
16554
+ byWorkspace.set(ws, peers);
16555
+ }
16556
+ for (const [ws, peers] of byWorkspace) {
16557
+ if (peers.size < 2)
16558
+ continue;
16559
+ const list = [...peers].map(([p, hs]) => `${hs.join(", ")}: "${p}"`).join("; ");
16560
+ issues.push({ path: "hosts", message: `Hosts in workspace "${ws}" use different peerNames (${list}), so the user is split across peers.` });
16561
+ }
16562
+ return issues;
16563
+ }
16564
+ function hostMigration(file, host, deadKeys = [], legacy = v01Reader) {
16565
+ if (isNewer(file))
16566
+ return { set: {}, remove: [] };
16567
+ const f = isObj3(file) ? file : {};
16568
+ const hosts = isObj3(f.hosts) ? f.hosts : {};
16569
+ const block = isObj3(hosts[host]) ? hosts[host] : {};
16570
+ const set = {};
16571
+ const drop = [];
16572
+ const grant = legacyGrantOf(block);
16573
+ if (grant)
16574
+ set.oauth = grant;
16575
+ if (!isMigrated(block)) {
16576
+ const old = { ...legacy(f, host) };
16577
+ const signedIn = isGrant(block.oauth) || grant !== undefined;
16578
+ if (old.baseUrl && sameServer(old.baseUrl, undefined))
16579
+ old.baseUrl = undefined;
16580
+ for (const key of MOVABLE) {
16581
+ if (signedIn && (key === "apiKey" || key === "baseUrl"))
16582
+ continue;
16583
+ if (old[key] !== undefined && block[key] !== old[key])
16584
+ set[key] = old[key];
16585
+ else if (old[key] === undefined && block[key] !== undefined)
16586
+ drop.push(key);
15811
16587
  }
16588
+ set.schemaVersion = CONFIG_SCHEMA_VERSION;
15812
16589
  }
16590
+ const remove = [...drop, ...LEGACY_HOST_KEYS, ...deadKeys].filter((k) => (k in block) && !(k in set));
16591
+ return { set, remove };
15813
16592
  }
15814
- function clearIdCache() {
15815
- ensureCacheDir();
15816
- writeFileSync(ID_CACHE_FILE, "{}");
16593
+ function effectiveBlock(file, host, legacy) {
16594
+ return writeBlock(structuredClone(isObj3(file) ? file : {}), host, hostMigration(file, host, [], legacy));
15817
16595
  }
15818
- function clearPeerCache() {
15819
- const cache = loadIdCache();
15820
- delete cache.peers;
15821
- saveIdCache(cache);
16596
+ function hostBlock(file, host) {
16597
+ if (host === "__proto__" || host === "constructor" || host === "prototype")
16598
+ throw new Error(`invalid host name: ${host}`);
16599
+ if (!isObj3(file.hosts))
16600
+ file.hosts = {};
16601
+ return isObj3(file.hosts[host]) ? file.hosts[host] : file.hosts[host] = {};
15822
16602
  }
15823
- function clearUserContextOnly() {
15824
- const cache = loadContextCache();
15825
- delete cache.userContext;
15826
- saveContextCache(cache);
16603
+ function writeBlock(file, host, { set, remove }) {
16604
+ const block = hostBlock(file, host);
16605
+ Object.assign(block, set);
16606
+ for (const k of remove)
16607
+ delete block[k];
16608
+ return block;
15827
16609
  }
15828
- function clearClaudeContextOnly() {
15829
- const cache = loadContextCache();
15830
- delete cache.claudeContext;
15831
- saveContextCache(cache);
16610
+ async function migrateHost(path, host, deadKeys = [], legacy) {
16611
+ const peek = hostMigration(readConfigFile({ HONCHO_CONFIG_PATH: path }), host, deadKeys, legacy);
16612
+ if (!Object.keys(peek.set).length && !peek.remove.length)
16613
+ return [];
16614
+ let changed = [];
16615
+ await updateConfigFile(path, (file) => {
16616
+ const m = hostMigration(file, host, deadKeys, legacy);
16617
+ changed = [...Object.keys(m.set).filter((k) => k !== "schemaVersion"), ...m.remove.map((k) => `-${k}`)];
16618
+ if (Object.keys(m.set).length || m.remove.length)
16619
+ writeBlock(file, host, m);
16620
+ });
16621
+ return changed;
16622
+ }
16623
+ // node_modules/@honcho-ai/harness-plugin-core/dist/legacy/claude-honcho.js
16624
+ var isObj4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
16625
+ var str3 = (v) => typeof v === "string" && v ? v : undefined;
16626
+ function claudeHonchoReader(file, host) {
16627
+ const hosts = isObj4(file.hosts) ? file.hosts : {};
16628
+ const found = hosts[host] ?? hosts[host.replace(/_/g, "-")] ?? hosts[host.replace(/-/g, "_")];
16629
+ const block = isObj4(found) ? found : undefined;
16630
+ const endpoint = block?.endpoint ?? file.endpoint;
16631
+ const override = file.globalOverride === true;
16632
+ return {
16633
+ apiKey: str3(block?.apiKey) ?? str3(file.apiKey),
16634
+ baseUrl: str3(endpoint?.baseUrl)?.replace(/\/v3\/?$/, "") ?? (endpoint?.environment === "local" ? "http://localhost:8000" : undefined),
16635
+ peerName: str3(file.peerName),
16636
+ workspace: str3(override || !block ? file.workspace : block.workspace),
16637
+ aiPeer: str3(override ? file.aiPeer ?? block?.aiPeer : block ? block.aiPeer : file[host === "cursor" ? "cursorPeer" : "claudePeer"])
16638
+ };
15832
16639
  }
15833
- // node_modules/@honcho-ai/harness-plugin-core/src/telemetry.ts
16640
+ // node_modules/@honcho-ai/harness-plugin-core/dist/telemetry.js
15834
16641
  var HEADER_HOST = "X-Honcho-Host";
15835
16642
  var HEADER_PLUGIN = "X-Honcho-Plugin";
15836
16643
  var HEADER_AGENT_MODEL = "X-Honcho-Agent-Model";
@@ -15879,31 +16686,10 @@ function telemetryHeaders(id = {}, extra) {
15879
16686
  return headers;
15880
16687
  }
15881
16688
  // src/config.ts
16689
+ var LEGACY = claudeHonchoReader;
15882
16690
  function sanitizeForSessionName(s) {
15883
16691
  return s.toLowerCase().replace(/[^a-z0-9-_]/g, "-");
15884
16692
  }
15885
- var SESSION_START_COMPONENTS = ["directives", "summary", "peerCard", "peerRepresentation", "briefing"];
15886
- var PER_TURN_COMPONENTS = ["userContext", "assistantContext", "sessionContext", "dialectic"];
15887
- function normalizePerTurn(components) {
15888
- return components.map((c) => c === "context" ? "userContext" : c);
15889
- }
15890
- var DEFAULT_INJECTION = {
15891
- sessionStart: ["directives", "summary", "peerCard"],
15892
- perTurn: ["userContext"],
15893
- showContents: [],
15894
- searchTopK: 10,
15895
- maxConclusions: 15,
15896
- searchMaxDistance: 0.6,
15897
- searchQuerySource: "prompt",
15898
- sessionContextTokens: 1500,
15899
- dialecticTemplate: "Return a compact, factual list of anything from the user's history — preferences, prior decisions, relevant past work — that would help with the following. Write in the third person as background notes; do not address the user, ask questions, or offer next steps. If nothing relevant exists, say so in one line. Relevant to: %{user_query}",
15900
- dialecticReasoning: "medium"
15901
- };
15902
- var REASONING_LEVELS = ["minimal", "low", "medium", "high", "max"];
15903
- var HONCHO_BASE_URLS = {
15904
- production: "https://api.honcho.dev/v3",
15905
- local: "http://localhost:8000/v3"
15906
- };
15907
16693
  var _detectedHost = null;
15908
16694
  function setDetectedHost(host) {
15909
16695
  _detectedHost = host;
@@ -15931,13 +16717,6 @@ var DEFAULT_AI_PEER = {
15931
16717
  claude_code: "claude",
15932
16718
  obsidian: "honcho"
15933
16719
  };
15934
- function coerceBoolean(value) {
15935
- if (typeof value === "string") {
15936
- const v = value.trim().toLowerCase();
15937
- return v !== "false" && v !== "0" && v !== "";
15938
- }
15939
- return Boolean(value);
15940
- }
15941
16720
  var _stdinText = null;
15942
16721
  function cacheStdin(text) {
15943
16722
  _stdinText = text;
@@ -15964,31 +16743,14 @@ async function initHook() {
15964
16743
  process.exit(0);
15965
16744
  setDetectedHost(detectHost(input));
15966
16745
  }
15967
- function deepEqual(a, b) {
15968
- if (a === b)
15969
- return true;
15970
- if (a == null || b == null)
15971
- return a === b;
15972
- if (typeof a !== typeof b)
15973
- return false;
15974
- if (typeof a !== "object")
15975
- return false;
15976
- const aObj = a;
15977
- const bObj = b;
15978
- const keys = new Set([...Object.keys(aObj), ...Object.keys(bObj)]);
15979
- for (const key of keys) {
15980
- if (!deepEqual(aObj[key], bObj[key]))
15981
- return false;
15982
- }
15983
- return true;
15984
- }
15985
- var CONFIG_DIR = join3(homedir2(), ".honcho");
15986
- var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
15987
16746
  function getConfigPath() {
15988
- return CONFIG_FILE;
16747
+ return configPath();
16748
+ }
16749
+ function getConfigDir() {
16750
+ return dirname2(configPath());
15989
16751
  }
15990
16752
  function configExists() {
15991
- return existsSync3(CONFIG_FILE);
16753
+ return existsSync3(configPath());
15992
16754
  }
15993
16755
  function getPluginVersion() {
15994
16756
  const root = process.env.CLAUDE_PLUGIN_ROOT;
@@ -15998,330 +16760,142 @@ function getPluginVersion() {
15998
16760
  ];
15999
16761
  for (const manifest of candidates) {
16000
16762
  try {
16001
- const version = JSON.parse(readFileSync2(manifest, "utf-8")).version;
16763
+ const version = JSON.parse(readFileSync3(manifest, "utf-8")).version;
16002
16764
  if (typeof version === "string" && version)
16003
16765
  return version;
16004
16766
  } catch {}
16005
16767
  }
16006
16768
  return "unknown";
16007
16769
  }
16008
- function loadConfig2(host) {
16009
- const resolvedHost = host ?? getDetectedHost();
16010
- if (configExists()) {
16011
- try {
16012
- const content = readFileSync2(CONFIG_FILE, "utf-8");
16013
- const raw = JSON.parse(content);
16014
- return resolveConfig2(raw, resolvedHost);
16015
- } catch {}
16016
- }
16017
- return loadConfigFromEnv(resolvedHost);
16770
+ function legacyEndpoint(value) {
16771
+ if (value === "local")
16772
+ return "http://localhost:8000";
16773
+ if (value?.startsWith("http"))
16774
+ return value.replace(/\/v3\/?$/, "");
16775
+ return;
16018
16776
  }
16019
- function resolveConfig2(raw, host) {
16020
- const hostBlock = raw.hosts?.[host] ?? raw.hosts?.[host.replace(/_/g, "-")] ?? raw.hosts?.[host.replace(/-/g, "_")];
16021
- const apiKey = process.env.HONCHO_API_KEY || hostBlock?.apiKey || raw.apiKey;
16022
- if (!apiKey)
16023
- return null;
16024
- const peerName = raw.peerName || process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || "user";
16025
- let workspace;
16026
- let aiPeer;
16027
- if (raw.globalOverride === true) {
16028
- workspace = raw.workspace ?? DEFAULT_WORKSPACE[host];
16029
- aiPeer = raw.aiPeer ?? hostBlock?.aiPeer ?? DEFAULT_AI_PEER[host];
16030
- } else if (hostBlock) {
16031
- workspace = hostBlock.workspace ?? DEFAULT_WORKSPACE[host];
16032
- aiPeer = hostBlock.aiPeer ?? DEFAULT_AI_PEER[host];
16033
- } else {
16034
- workspace = process.env.HONCHO_WORKSPACE ?? raw.workspace ?? DEFAULT_WORKSPACE[host];
16035
- if (host === "cursor") {
16036
- aiPeer = raw.cursorPeer ?? DEFAULT_AI_PEER["cursor"];
16037
- } else {
16038
- aiPeer = raw.claudePeer ?? DEFAULT_AI_PEER["claude_code"];
16039
- }
16040
- }
16041
- const config = {
16042
- apiKey,
16043
- peerName,
16044
- workspace,
16045
- aiPeer,
16046
- sessionStrategy: hostBlock?.sessionStrategy ?? raw.sessionStrategy,
16047
- sessionPeerPrefix: hostBlock?.sessionPeerPrefix ?? raw.sessionPeerPrefix,
16048
- sessions: raw.sessions,
16049
- saveMessages: hostBlock?.saveMessages ?? raw.saveMessages,
16050
- saveToolUse: hostBlock?.saveToolUse ?? raw.saveToolUse,
16051
- saveGitEvents: hostBlock?.saveGitEvents ?? raw.saveGitEvents,
16052
- reasoningLevel: hostBlock?.reasoningLevel ?? raw.reasoningLevel,
16053
- observationMode: hostBlock?.observationMode ?? raw.observationMode,
16054
- messageUpload: hostBlock?.messageUpload ?? raw.messageUpload,
16055
- contextRefresh: hostBlock?.contextRefresh ?? raw.contextRefresh,
16056
- endpoint: hostBlock?.endpoint ?? raw.endpoint,
16057
- redactPatterns: hostBlock?.redactPatterns ?? raw.redactPatterns,
16058
- injection: hostBlock?.injection ?? raw.injection,
16059
- rememberTool: hostBlock?.rememberTool ?? raw.rememberTool,
16060
- enabled: hostBlock?.enabled ?? raw.enabled,
16061
- logging: hostBlock?.logging ?? raw.logging,
16062
- globalOverride: raw.globalOverride
16063
- };
16064
- return mergeWithEnvVars(config);
16777
+ function legacyEnv(host = getDetectedHost()) {
16778
+ const env = process.env;
16779
+ const peerVar = host === "cursor" ? "HONCHO_CURSOR_PEER" : "HONCHO_CLAUDE_PEER";
16780
+ const candidates = [
16781
+ ["HONCHO_BASE_URL", "baseUrl", "HONCHO_ENDPOINT", legacyEndpoint(env.HONCHO_ENDPOINT)],
16782
+ ["HONCHO_AI_PEER", "aiPeer", peerVar, env[peerVar] || undefined]
16783
+ ];
16784
+ const set = candidates.filter(([newVar, , , value]) => value && !env[newVar]);
16785
+ if (!set.length)
16786
+ return {};
16787
+ const block = effectiveBlock(readConfigFile(), host, LEGACY);
16788
+ if (block.apiKey || block.oauth)
16789
+ return {};
16790
+ return Object.fromEntries(set.filter(([, setting]) => !block[setting]).map(([newVar, , oldVar, value]) => [newVar, [oldVar, value]]));
16065
16791
  }
16066
- function loadConfigFromEnv(host) {
16067
- const apiKey = process.env.HONCHO_API_KEY;
16068
- if (!apiKey) {
16069
- return null;
16070
- }
16071
- const resolvedHost = host ?? getDetectedHost();
16072
- const peerName = process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || "user";
16073
- const workspace = process.env.HONCHO_WORKSPACE || DEFAULT_WORKSPACE[resolvedHost];
16074
- const hostPeerEnv = resolvedHost === "cursor" ? process.env.HONCHO_CURSOR_PEER : process.env.HONCHO_CLAUDE_PEER;
16075
- const aiPeer = process.env.HONCHO_AI_PEER || hostPeerEnv || DEFAULT_AI_PEER[resolvedHost];
16076
- const endpoint = process.env.HONCHO_ENDPOINT;
16077
- const config = {
16078
- apiKey,
16079
- peerName,
16080
- workspace,
16081
- aiPeer,
16082
- saveMessages: process.env.HONCHO_SAVE_MESSAGES !== "false",
16083
- saveToolUse: process.env.HONCHO_SAVE_TOOL_USE === "true",
16084
- saveGitEvents: process.env.HONCHO_SAVE_GIT_EVENTS === "true",
16085
- enabled: process.env.HONCHO_ENABLED !== "false",
16086
- logging: process.env.HONCHO_LOGGING !== "false"
16087
- };
16088
- if (endpoint) {
16089
- if (endpoint === "local") {
16090
- config.endpoint = { environment: "local" };
16091
- } else if (endpoint.startsWith("http")) {
16092
- config.endpoint = { baseUrl: endpoint };
16093
- }
16094
- }
16095
- return config;
16792
+ function honchoEnv(host) {
16793
+ const legacy = Object.entries(legacyEnv(host));
16794
+ if (!legacy.length)
16795
+ return process.env;
16796
+ return { ...process.env, ...Object.fromEntries(legacy.map(([k, [, value]]) => [k, value])) };
16096
16797
  }
16097
- function mergeWithEnvVars(config) {
16098
- if (process.env.HONCHO_API_KEY) {
16099
- config.apiKey = process.env.HONCHO_API_KEY;
16100
- }
16101
- if (process.env.HONCHO_PEER_NAME) {
16102
- config.peerName = process.env.HONCHO_PEER_NAME;
16103
- }
16104
- if (process.env.HONCHO_ENABLED === "false") {
16105
- config.enabled = false;
16106
- }
16107
- if (process.env.HONCHO_LOGGING === "false") {
16108
- config.logging = false;
16109
- }
16110
- if (process.env.HONCHO_SAVE_TOOL_USE !== undefined) {
16111
- config.saveToolUse = process.env.HONCHO_SAVE_TOOL_USE === "true";
16112
- }
16113
- if (process.env.HONCHO_SAVE_GIT_EVENTS !== undefined) {
16114
- config.saveGitEvents = process.env.HONCHO_SAVE_GIT_EVENTS === "true";
16115
- }
16116
- return config;
16798
+ function resolveHost(host) {
16799
+ return resolveConfig(readConfigFile(), {
16800
+ host,
16801
+ env: honchoEnv(host),
16802
+ defaults: { workspace: DEFAULT_WORKSPACE[host], aiPeer: DEFAULT_AI_PEER[host] },
16803
+ legacy: LEGACY
16804
+ });
16117
16805
  }
16118
- function saveConfig(config) {
16119
- if (!existsSync3(CONFIG_DIR)) {
16120
- mkdirSync2(CONFIG_DIR, { recursive: true });
16121
- }
16122
- let existing = {};
16123
- if (existsSync3(CONFIG_FILE)) {
16124
- try {
16125
- existing = JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
16126
- } catch {}
16127
- }
16128
- if (config.sessions !== undefined) {
16129
- existing.sessions = config.sessions;
16130
- }
16131
- const host = getDetectedHost();
16132
- if (!existing.hosts)
16133
- existing.hosts = {};
16134
- const existingHost = existing.hosts[host] ?? {};
16135
- const hostEntry = {};
16136
- const setHostIfExplicit = (key, value, rootValue) => {
16137
- if (value === undefined)
16138
- return;
16139
- const hasHostOverride = Object.prototype.hasOwnProperty.call(existingHost, key);
16140
- if (hasHostOverride || !deepEqual(value, rootValue)) {
16141
- hostEntry[key] = value;
16142
- }
16806
+ function isLoggingEnabled(host = getDetectedHost()) {
16807
+ if (process.env.HONCHO_LOGGING === "false")
16808
+ return false;
16809
+ const file = readConfigFile();
16810
+ const hosts = file.hosts && typeof file.hosts === "object" ? file.hosts : {};
16811
+ const own = [hosts[host], hosts[host.replace(/_/g, "-")]].map((block) => block && typeof block === "object" ? block.logging : undefined).find((v) => v !== undefined);
16812
+ return (own ?? file.logging) !== false;
16813
+ }
16814
+ function loadConfig2(host = getDetectedHost()) {
16815
+ const cfg = resolveHost(host);
16816
+ const cred = pickCredential(readConfigFile(), { host, baseUrl: cfg.baseUrl, env: honchoEnv(host), legacy: LEGACY });
16817
+ if (!cred)
16818
+ return null;
16819
+ const { token, ...authState } = cred;
16820
+ return {
16821
+ apiKey: token,
16822
+ auth: { ...authState, host },
16823
+ peerName: cfg.peerName,
16824
+ workspace: cfg.workspace,
16825
+ aiPeer: cfg.aiPeer,
16826
+ baseUrl: cfg.baseUrl
16143
16827
  };
16144
- setHostIfExplicit("workspace", config.workspace, existing.workspace ?? DEFAULT_WORKSPACE[host]);
16145
- setHostIfExplicit("aiPeer", config.aiPeer, existing.aiPeer ?? DEFAULT_AI_PEER[host]);
16146
- const enabledForSave = process.env.HONCHO_ENABLED === "false" && config.enabled === false ? existingHost.enabled : config.enabled;
16147
- const loggingForSave = process.env.HONCHO_LOGGING === "false" && config.logging === false ? existingHost.logging : config.logging;
16148
- setHostIfExplicit("enabled", enabledForSave, existing.enabled);
16149
- setHostIfExplicit("logging", loggingForSave, existing.logging);
16150
- setHostIfExplicit("saveMessages", config.saveMessages, existing.saveMessages);
16151
- setHostIfExplicit("sessionStrategy", config.sessionStrategy, existing.sessionStrategy);
16152
- setHostIfExplicit("sessionPeerPrefix", config.sessionPeerPrefix, existing.sessionPeerPrefix);
16153
- setHostIfExplicit("reasoningLevel", config.reasoningLevel, existing.reasoningLevel);
16154
- setHostIfExplicit("observationMode", config.observationMode, existing.observationMode);
16155
- setHostIfExplicit("messageUpload", config.messageUpload, existing.messageUpload);
16156
- setHostIfExplicit("contextRefresh", config.contextRefresh, existing.contextRefresh);
16157
- setHostIfExplicit("redactPatterns", config.redactPatterns, existing.redactPatterns);
16158
- setHostIfExplicit("endpoint", config.endpoint, existing.endpoint);
16159
- setHostIfExplicit("injection", config.injection, existing.injection);
16160
- setHostIfExplicit("rememberTool", config.rememberTool, existing.rememberTool);
16161
- if (existingHost.apiKey !== undefined) {
16162
- hostEntry.apiKey = existingHost.apiKey;
16163
- }
16164
- existing.hosts[host] = hostEntry;
16165
- writeFileSync2(CONFIG_FILE, JSON.stringify(existing, null, 2));
16166
16828
  }
16167
- function saveRootField(field, value) {
16168
- if (!existsSync3(CONFIG_DIR)) {
16169
- mkdirSync2(CONFIG_DIR, { recursive: true });
16170
- }
16171
- let existing = {};
16172
- if (existsSync3(CONFIG_FILE)) {
16173
- try {
16174
- existing = JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
16175
- } catch {}
16176
- }
16177
- existing[field] = value;
16178
- writeFileSync2(CONFIG_FILE, JSON.stringify(existing, null, 2));
16829
+ async function saveConfig(config, field) {
16830
+ const host = getDetectedHost();
16831
+ const env = honchoEnv(host);
16832
+ const write = (key, envVar) => key === field || !env[envVar];
16833
+ const patch = {};
16834
+ if (write("peerName", "HONCHO_PEER_NAME"))
16835
+ patch.peerName = config.peerName;
16836
+ if (write("workspace", "HONCHO_WORKSPACE"))
16837
+ patch.workspace = config.workspace === DEFAULT_WORKSPACE[host] ? undefined : config.workspace;
16838
+ if (write("aiPeer", "HONCHO_AI_PEER"))
16839
+ patch.aiPeer = config.aiPeer === DEFAULT_AI_PEER[host] ? undefined : config.aiPeer;
16840
+ if (write("baseUrl", "HONCHO_BASE_URL"))
16841
+ patch.baseUrl = config.baseUrl === DEFAULT_BASE_URL ? undefined : config.baseUrl;
16842
+ await saveHost(configPath(), host, patch, LEGACY);
16179
16843
  }
16180
- function resolveWorktreeMainRoot(dir) {
16181
- try {
16182
- const gitPath = join3(dir, ".git");
16183
- if (!statSync(gitPath).isFile())
16184
- return null;
16185
- const match = readFileSync2(gitPath, "utf-8").match(/^gitdir:\s*(.+?)\s*$/m);
16186
- if (!match)
16187
- return null;
16188
- const gitdir = resolve(dir, match[1]);
16189
- const idx = gitdir.lastIndexOf(`${sep}worktrees${sep}`);
16190
- if (idx === -1)
16191
- return null;
16192
- const gitContainer = gitdir.slice(0, idx);
16193
- if (basename(gitContainer) === ".git")
16194
- return dirname(gitContainer);
16195
- if (gitContainer.endsWith(".git"))
16196
- return gitContainer;
16197
- return null;
16198
- } catch {
16199
- return null;
16200
- }
16844
+ function getConfigIssues(host = getDetectedHost()) {
16845
+ return checkConfig(readConfigFile()).filter((i) => i.path === "schemaVersion" || i.path === "hosts" && i.message.includes(host)).map((i) => i.message);
16201
16846
  }
16202
- var MAX_GIT_WALK_UP = 12;
16203
- function worktreeMainRootFor(cwd) {
16847
+ var DEAD_HOST_KEYS = [
16848
+ "sessionStrategy",
16849
+ "sessionPeerPrefix",
16850
+ "sessions",
16851
+ "injection",
16852
+ "contextRefresh",
16853
+ "messageUpload",
16854
+ "reasoningLevel",
16855
+ "statusline",
16856
+ "saveToolUse",
16857
+ "saveGitEvents",
16858
+ "redactPatterns",
16859
+ "rememberTool",
16860
+ "observationMode",
16861
+ "saveMessages",
16862
+ "enabled",
16863
+ "globalOverride",
16864
+ "linkedHosts"
16865
+ ];
16866
+ async function migrateConfig(host = getDetectedHost()) {
16204
16867
  try {
16205
- let dir = resolve(cwd);
16206
- for (let i = 0;i < MAX_GIT_WALK_UP; i++) {
16207
- if (existsSync3(join3(dir, ".git")))
16208
- return resolveWorktreeMainRoot(dir);
16209
- const parent = dirname(dir);
16210
- if (parent === dir)
16211
- break;
16212
- dir = parent;
16213
- }
16868
+ const changed = await migrateHost(configPath(), host, DEAD_HOST_KEYS, LEGACY);
16869
+ if (changed.length)
16870
+ return `[honcho] Moved your Honcho settings into hosts.${host} in ~/.honcho/config.json.`;
16214
16871
  } catch {}
16215
- return null;
16216
- }
16217
- function getSessionForPath(cwd, mainRoot) {
16218
- const config = loadConfig2();
16219
- if (!config?.sessions)
16220
- return null;
16221
- if (config.sessions[cwd])
16222
- return config.sessions[cwd];
16223
- const mr = mainRoot === undefined ? worktreeMainRootFor(cwd) : mainRoot;
16224
- if (mr && config.sessions[mr])
16225
- return config.sessions[mr];
16226
- return null;
16872
+ return;
16227
16873
  }
16228
- function deriveSessionName(strategy, cwd, opts = {}) {
16229
- const usePrefix = opts.sessionPeerPrefix !== false;
16230
- const peerPart = opts.peerName ? sanitizeForSessionName(opts.peerName) : "user";
16231
- const repoPart = sanitizeForSessionName(basename(cwd));
16232
- const base = usePrefix ? `${peerPart}-${repoPart}` : repoPart;
16233
- switch (strategy) {
16234
- case "git-branch": {
16235
- if (opts.branch) {
16236
- const branchPart = sanitizeForSessionName(opts.branch);
16237
- return `${base}-${branchPart}`;
16238
- }
16239
- return base;
16240
- }
16241
- case "chat-instance": {
16242
- if (opts.instanceId) {
16243
- return usePrefix ? `${peerPart}-chat-${opts.instanceId}` : `chat-${opts.instanceId}`;
16244
- }
16245
- return base;
16246
- }
16247
- case "per-directory":
16248
- default:
16249
- return base;
16250
- }
16874
+ function getSessionName(sessionId) {
16875
+ const id = sessionId || process.env.CLAUDE_CODE_SESSION_ID;
16876
+ return id ? sanitizeForSessionName(id) : null;
16251
16877
  }
16252
- function getSessionName(cwd, instanceId) {
16253
- const config = loadConfig2();
16254
- const strategy = config?.sessionStrategy ?? "per-directory";
16255
- const mainRoot = worktreeMainRootFor(cwd);
16256
- if (strategy === "per-directory") {
16257
- const configuredSession = getSessionForPath(cwd, mainRoot);
16258
- if (configuredSession) {
16259
- return configuredSession;
16260
- }
16261
- }
16262
- let branch;
16263
- if (strategy === "git-branch") {
16264
- branch = captureGitState(cwd)?.branch;
16265
- }
16266
- let resolvedInstanceId;
16267
- if (strategy === "chat-instance") {
16268
- resolvedInstanceId = instanceId || getInstanceIdForCwd(cwd) || getClaudeInstanceId() || undefined;
16269
- }
16270
- return deriveSessionName(strategy, mainRoot ?? cwd, {
16271
- peerName: config?.peerName,
16272
- sessionPeerPrefix: config?.sessionPeerPrefix,
16273
- branch,
16274
- instanceId: resolvedInstanceId
16275
- });
16878
+ function getKnownHosts() {
16879
+ const hosts = readConfigFile().hosts;
16880
+ return hosts && typeof hosts === "object" ? Object.keys(hosts) : [];
16276
16881
  }
16277
- function setSessionForPath(cwd, sessionName) {
16278
- const config = loadConfig2();
16279
- if (!config)
16882
+ async function refreshCredential(config) {
16883
+ const host = config.auth?.host ?? getDetectedHost();
16884
+ const cred = await ensureFreshCredential({ path: configPath(), host, baseUrl: config.baseUrl, env: honchoEnv(host), legacy: LEGACY });
16885
+ if (!cred)
16280
16886
  return;
16281
- if (!config.sessions) {
16282
- config.sessions = {};
16283
- }
16284
- config.sessions[cwd] = sessionName;
16285
- saveConfig(config);
16286
- }
16287
- function getInjectionConfig(config) {
16288
- const injection = (config === undefined ? loadConfig2() : config)?.injection;
16289
- const resolved = { ...DEFAULT_INJECTION, ...injection ?? {} };
16290
- resolved.perTurn = Array.isArray(resolved.perTurn) ? normalizePerTurn(resolved.perTurn) : DEFAULT_INJECTION.perTurn;
16291
- resolved.showContents = Array.isArray(resolved.showContents) ? normalizePerTurn(resolved.showContents) : DEFAULT_INJECTION.showContents;
16292
- return resolved;
16293
- }
16294
- function isLoggingEnabled() {
16295
- const config = loadConfig2();
16296
- return config?.logging !== false;
16297
- }
16298
- function isPluginEnabled() {
16299
- const config = loadConfig2();
16300
- return config?.enabled !== false;
16301
- }
16302
- function getKnownHosts() {
16303
- const cfgPath = getConfigPath();
16304
- if (!existsSync3(cfgPath))
16305
- return [];
16306
- try {
16307
- const raw = JSON.parse(readFileSync2(cfgPath, "utf-8"));
16308
- return raw.hosts ? Object.keys(raw.hosts) : [];
16309
- } catch {
16310
- return [];
16311
- }
16887
+ const { token, ...authState } = cred;
16888
+ config.apiKey = token;
16889
+ config.auth = { ...authState, host };
16312
16890
  }
16313
- function getHonchoBaseUrlForEndpoint(endpoint) {
16314
- if (endpoint?.baseUrl) {
16315
- const url = endpoint.baseUrl;
16316
- return url.endsWith("/v3") ? url : `${url}/v3`;
16891
+ function getAuthNotice(config) {
16892
+ if (config.auth?.reauthRequired) {
16893
+ return "[honcho] Your Honcho sign-in has expired. Run /honcho setup to sign in again.";
16317
16894
  }
16318
- if (endpoint?.environment === "local") {
16319
- return HONCHO_BASE_URLS.local;
16320
- }
16321
- return HONCHO_BASE_URLS.production;
16895
+ return;
16322
16896
  }
16323
16897
  function getHonchoBaseUrl(config) {
16324
- return getHonchoBaseUrlForEndpoint(config.endpoint);
16898
+ return `${config.baseUrl}/v3`;
16325
16899
  }
16326
16900
  function getTelemetryHeaders(host = getDetectedHost()) {
16327
16901
  return telemetryHeaders({
@@ -16340,24 +16914,126 @@ function getHonchoClientOptions(config) {
16340
16914
  defaultHeaders: getTelemetryHeaders()
16341
16915
  };
16342
16916
  }
16917
+ function isProductionEndpoint(config) {
16918
+ return config.baseUrl === DEFAULT_BASE_URL;
16919
+ }
16343
16920
  function getEndpointInfo(config) {
16344
- if (config.endpoint?.baseUrl) {
16345
- return { type: "custom", url: config.endpoint.baseUrl };
16921
+ return { type: isProductionEndpoint(config) ? "production" : "custom", url: config.baseUrl };
16922
+ }
16923
+
16924
+ // src/honcho-client.ts
16925
+ var import_sdk = __toESM(require_dist(), 1);
16926
+ async function createHonchoClient(config, overrides = {}) {
16927
+ await refreshCredential(config);
16928
+ return new import_sdk.Honcho({ ...getHonchoClientOptions(config), ...overrides });
16929
+ }
16930
+ function setClientApiKey(honcho, token) {
16931
+ honcho.http.apiKey = token;
16932
+ }
16933
+
16934
+ // src/cache.ts
16935
+ import { homedir as homedir2 } from "os";
16936
+ import { join as join4 } from "path";
16937
+ import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
16938
+ var CACHE_DIR = join4(homedir2(), ".honcho");
16939
+ var CONTEXT_CACHE_FILE = join4(CACHE_DIR, "context-cache.json");
16940
+ function ensureCacheDir() {
16941
+ if (!existsSync4(CACHE_DIR)) {
16942
+ mkdirSync2(CACHE_DIR, { recursive: true });
16943
+ }
16944
+ }
16945
+ var CONTEXT_CACHE_KNOWN_KEYS = new Set(["messageCount"]);
16946
+ function loadContextCache() {
16947
+ ensureCacheDir();
16948
+ if (!existsSync4(CONTEXT_CACHE_FILE)) {
16949
+ return {};
16950
+ }
16951
+ try {
16952
+ const raw = JSON.parse(readFileSync4(CONTEXT_CACHE_FILE, "utf-8"));
16953
+ let cleaned = false;
16954
+ for (const key of Object.keys(raw)) {
16955
+ if (!CONTEXT_CACHE_KNOWN_KEYS.has(key)) {
16956
+ delete raw[key];
16957
+ cleaned = true;
16958
+ }
16959
+ }
16960
+ if (cleaned) {
16961
+ writeFileSync2(CONTEXT_CACHE_FILE, JSON.stringify(raw, null, 2));
16962
+ }
16963
+ return raw;
16964
+ } catch {
16965
+ return {};
16966
+ }
16967
+ }
16968
+ function saveContextCache(cache) {
16969
+ ensureCacheDir();
16970
+ writeFileSync2(CONTEXT_CACHE_FILE, JSON.stringify(cache, null, 2));
16971
+ }
16972
+ function incrementMessageCount() {
16973
+ const cache = loadContextCache();
16974
+ cache.messageCount = (cache.messageCount || 0) + 1;
16975
+ saveContextCache(cache);
16976
+ return cache.messageCount;
16977
+ }
16978
+ function getMessageCount() {
16979
+ const cache = loadContextCache();
16980
+ return cache.messageCount || 0;
16981
+ }
16982
+ function resetMessageCount() {
16983
+ const cache = loadContextCache();
16984
+ cache.messageCount = 0;
16985
+ saveContextCache(cache);
16986
+ }
16987
+ var MAX_MESSAGE_SIZE = 24000;
16988
+ function chunkContent(content, maxSize = MAX_MESSAGE_SIZE) {
16989
+ if (content.length <= maxSize) {
16990
+ return [content];
16991
+ }
16992
+ const chunks = [];
16993
+ let remaining = content;
16994
+ while (remaining.length > 0) {
16995
+ if (remaining.length <= maxSize) {
16996
+ chunks.push(remaining);
16997
+ break;
16998
+ }
16999
+ let splitIndex = remaining.lastIndexOf(`
17000
+ `, maxSize);
17001
+ if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
17002
+ splitIndex = remaining.lastIndexOf(" ", maxSize);
17003
+ }
17004
+ if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
17005
+ splitIndex = maxSize;
17006
+ }
17007
+ chunks.push(remaining.slice(0, splitIndex));
17008
+ remaining = remaining.slice(splitIndex).trimStart();
16346
17009
  }
16347
- if (config.endpoint?.environment === "local") {
16348
- return { type: "local", url: HONCHO_BASE_URLS.local };
17010
+ if (chunks.length > 1) {
17011
+ return chunks.map((chunk, i) => `[Part ${i + 1}/${chunks.length}] ${chunk}`);
16349
17012
  }
16350
- return { type: "production", url: HONCHO_BASE_URLS.production };
17013
+ return chunks;
16351
17014
  }
16352
- var VALID_ENVIRONMENTS = new Set(["production", "local"]);
16353
- function getObservationMode(config) {
16354
- return config.observationMode ?? "unified";
17015
+ var HONCHO_MAX_BATCH = 100;
17016
+ async function addMessagesBatched(session, messages, resolveFallback) {
17017
+ let active = session;
17018
+ let usedFallback = false;
17019
+ for (let i = 0;i < messages.length; i += HONCHO_MAX_BATCH) {
17020
+ const batch = messages.slice(i, i + HONCHO_MAX_BATCH);
17021
+ try {
17022
+ await active.addMessages(batch);
17023
+ } catch (e) {
17024
+ if (usedFallback || !resolveFallback)
17025
+ throw e;
17026
+ active = await resolveFallback(e);
17027
+ usedFallback = true;
17028
+ await active.addMessages(batch);
17029
+ }
17030
+ }
16355
17031
  }
16356
17032
 
16357
17033
  // src/log.ts
16358
17034
  import { homedir as homedir3 } from "os";
16359
- import { join as join4 } from "path";
16360
- import { existsSync as existsSync4, appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
17035
+ import { join as join5 } from "path";
17036
+ import { existsSync as existsSync5, appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
16361
17037
 
16362
17038
  // src/unicode.ts
16363
17039
  var blocks = {
@@ -16458,8 +17134,8 @@ var box = {
16458
17134
  };
16459
17135
 
16460
17136
  // src/log.ts
16461
- var CACHE_DIR2 = join4(homedir3(), ".honcho");
16462
- var LOG_FILE = join4(CACHE_DIR2, "activity.log");
17137
+ var CACHE_DIR2 = join5(homedir3(), ".honcho");
17138
+ var LOG_FILE = join5(CACHE_DIR2, "activity.log");
16463
17139
  var MAX_LOG_SIZE = 100 * 1024;
16464
17140
  var sym = {
16465
17141
  check: symbols.check,
@@ -16474,7 +17150,7 @@ var sym = {
16474
17150
  line: box.horizontal
16475
17151
  };
16476
17152
  function ensureLogDir() {
16477
- if (!existsSync4(CACHE_DIR2)) {
17153
+ if (!existsSync5(CACHE_DIR2)) {
16478
17154
  mkdirSync3(CACHE_DIR2, { recursive: true });
16479
17155
  }
16480
17156
  }
@@ -16501,10 +17177,10 @@ function logActivity(level, source, message, data, options) {
16501
17177
  session: options?.session || currentSession || undefined
16502
17178
  };
16503
17179
  try {
16504
- if (existsSync4(LOG_FILE)) {
17180
+ if (existsSync5(LOG_FILE)) {
16505
17181
  const stats = statSync2(LOG_FILE).size;
16506
17182
  if (stats > MAX_LOG_SIZE) {
16507
- const content = readFileSync3(LOG_FILE, "utf-8");
17183
+ const content = readFileSync5(LOG_FILE, "utf-8");
16508
17184
  const truncated = content.slice(-50 * 1024);
16509
17185
  writeFileSync3(LOG_FILE, truncated);
16510
17186
  }
@@ -16528,22 +17204,38 @@ function logAsync(operation, message, results) {
16528
17204
  }
16529
17205
 
16530
17206
  // src/prompt-filters.ts
16531
- var TRIVIAL_REPLY_PATTERN = /^(yes|no|ok|sure|thanks|y|n|yep|nope|yeah|nah|continue|go ahead|do it|proceed)$/i;
16532
- function isTerseReply(prompt) {
16533
- return TRIVIAL_REPLY_PATTERN.test(prompt.trim());
16534
- }
17207
+ import { existsSync as existsSync6 } from "fs";
16535
17208
  var HARNESS_INJECTED_PATTERNS = [
16536
- /^<task-notification>/,
17209
+ /^<task-notification(?=[\s/>])/,
17210
+ /^<cross-session-message(?=[\s/>])/,
17211
+ /^<agent-message(?=[\s/>])/,
17212
+ /^<channel(?=[\s/>])/,
17213
+ /^<local-command-caveat(?=[\s/>])/,
16537
17214
  /^<local-command-stdout>/,
16538
17215
  /^<command-name>/,
16539
17216
  /^<command-message>/,
16540
- /^<system-reminder>/,
17217
+ /^<system-reminder(?=[\s/>])/,
16541
17218
  /^<bash-(stdout|stderr|input)>/,
16542
17219
  /^<<[\w-]+>>$/
16543
17220
  ];
17221
+ var LEADING_REMINDERS = /^(?:\s*<system-reminder(?=[\s>])[^>]*>[\s\S]*?<\/system-reminder>)+\s*/;
17222
+ function stripLeadingReminders(prompt) {
17223
+ return prompt.replace(LEADING_REMINDERS, "");
17224
+ }
17225
+ var SLASH_COMMAND_ENVELOPE = /^<command-(name|message)>/;
16544
17226
  function isHarnessInjected(prompt) {
16545
- const trimmed = prompt.trim();
16546
- return HARNESS_INJECTED_PATTERNS.some((p) => p.test(trimmed));
17227
+ const trimmed = stripLeadingReminders(prompt).trim();
17228
+ return !trimmed || HARNESS_INJECTED_PATTERNS.some((p) => p.test(trimmed));
17229
+ }
17230
+ var SLASH_COMMAND = /^\/([\w:-]+)(?:\s|$)/;
17231
+ function isSlashCommand(prompt) {
17232
+ const trimmed = stripLeadingReminders(prompt).trim();
17233
+ if (SLASH_COMMAND_ENVELOPE.test(trimmed))
17234
+ return true;
17235
+ const name = SLASH_COMMAND.exec(trimmed)?.[1];
17236
+ if (!name)
17237
+ return false;
17238
+ return name.includes(":") || !existsSync6(`/${name}`);
16547
17239
  }
16548
17240
 
16549
17241
  // src/hooks/save-user-message.ts
@@ -16552,9 +17244,6 @@ async function handleSaveUserMessage() {
16552
17244
  if (!config) {
16553
17245
  process.exit(0);
16554
17246
  }
16555
- if (!isPluginEnabled() || config.saveMessages === false) {
16556
- process.exit(0);
16557
- }
16558
17247
  let hookInput = {};
16559
17248
  try {
16560
17249
  const input = getCachedStdin() ?? await readStdinText();
@@ -16569,36 +17258,31 @@ async function handleSaveUserMessage() {
16569
17258
  process.exit(0);
16570
17259
  }
16571
17260
  const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();
16572
- const instanceId = hookInput.session_id || getInstanceIdForCwd(cwd);
16573
- const sessionName = getSessionName(cwd, instanceId || undefined);
16574
- setLogContext(cwd, sessionName);
16575
- if (isHarnessInjected(prompt)) {
16576
- logHook("save-user-message", "Skipping upload (harness-injected content, not user input)");
17261
+ const sessionName = getSessionName(hookInput.session_id);
17262
+ setLogContext(cwd, sessionName ?? undefined);
17263
+ if (!sessionName) {
17264
+ logHook("save-user-message", "No Claude Code session id; skipping");
17265
+ process.exit(0);
17266
+ }
17267
+ if (isHarnessInjected(prompt) || isSlashCommand(prompt)) {
17268
+ logHook("save-user-message", "Skipping upload (slash command or harness-injected content)");
16577
17269
  process.exit(0);
16578
17270
  }
16579
17271
  try {
16580
- await postUserMessage(config, prompt, instanceId || undefined, sessionName);
17272
+ await postUserMessage(config, stripLeadingReminders(prompt), sessionName);
16581
17273
  } catch (e) {
16582
17274
  logHook("save-user-message", `Upload failed: ${e}`);
16583
17275
  }
16584
17276
  process.exit(0);
16585
17277
  }
16586
- async function postUserMessage(config, prompt, instanceId, sessionName) {
16587
- const honcho = new import_sdk.Honcho(getHonchoClientOptions(config));
17278
+ async function postUserMessage(config, prompt, sessionName) {
17279
+ const honcho = await createHonchoClient(config);
16588
17280
  const noEnsure = () => Promise.resolve();
16589
- const userPeer = new import_sdk.Peer(config.peerName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
17281
+ const userPeer = new import_sdk2.Peer(config.peerName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
16590
17282
  const createdAt = new Date().toISOString();
16591
- const configuration = isTerseReply(prompt) ? { reasoning: { enabled: false } } : undefined;
16592
- const messages = chunkContent(prompt).map((chunk) => userPeer.message(chunk, {
16593
- createdAt,
16594
- metadata: {
16595
- instance_id: instanceId || undefined,
16596
- session_affinity: sessionName
16597
- },
16598
- ...configuration ? { configuration } : {}
16599
- }));
17283
+ const messages = chunkContent(prompt).map((chunk) => userPeer.message(chunk, { createdAt }));
16600
17284
  logApiCall("session.addMessages", "POST", `user prompt (${prompt.length} chars, ${messages.length} msg, direct)`);
16601
- const session = new import_sdk.Session(sessionName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
17285
+ const session = new import_sdk2.Session(sessionName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
16602
17286
  await addMessagesBatched(session, messages, (e) => {
16603
17287
  logHook("save-user-message", `Direct upload failed, retrying via get-or-create: ${e}`);
16604
17288
  return honcho.session(sessionName);
@@ -16612,5 +17296,5 @@ async function main() {
16612
17296
  // hooks/save-user-message.ts
16613
17297
  await main();
16614
17298
 
16615
- //# debugId=5B5849C855E0CD2664756E2164756E21
17299
+ //# debugId=12CAA3E8109D53AB64756E2164756E21
16616
17300
  //# sourceMappingURL=save-user-message.js.map