@posthog/agent 2.1.114 → 2.1.118

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.
@@ -904,7 +904,7 @@ var import_hono = require("hono");
904
904
  // package.json
905
905
  var package_default = {
906
906
  name: "@posthog/agent",
907
- version: "2.1.114",
907
+ version: "2.1.118",
908
908
  repository: "https://github.com/PostHog/twig",
909
909
  description: "TypeScript agent framework wrapping Claude Agent SDK with Git-based task execution for PostHog",
910
910
  exports: {
@@ -3353,12 +3353,10 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3353
3353
  toolUseCache;
3354
3354
  backgroundTerminals = {};
3355
3355
  clientCapabilities;
3356
- logWriter;
3357
3356
  options;
3358
3357
  lastSentConfigOptions;
3359
- constructor(client, logWriter, options) {
3358
+ constructor(client, options) {
3360
3359
  super(client);
3361
- this.logWriter = logWriter;
3362
3360
  this.options = options;
3363
3361
  this.toolUseCache = {};
3364
3362
  this.logger = new Logger({ debug: true, prefix: "[ClaudeAcpAgent]" });
@@ -3403,7 +3401,14 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3403
3401
  async newSession(params) {
3404
3402
  this.checkAuthStatus();
3405
3403
  const meta = params._meta;
3404
+ const taskId = meta?.persistence?.taskId;
3406
3405
  const sessionId = (0, import_uuid.v7)();
3406
+ this.logger.info("Creating new session", {
3407
+ sessionId,
3408
+ taskId,
3409
+ taskRunId: meta?.taskRunId,
3410
+ cwd: params.cwd
3411
+ });
3407
3412
  const permissionMode = meta?.permissionMode && TWIG_EXECUTION_MODES.includes(meta.permissionMode) ? meta.permissionMode : "default";
3408
3413
  const mcpServers = parseMcpServers(params);
3409
3414
  const options = buildSessionOptions({
@@ -3432,7 +3437,6 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3432
3437
  options.abortController
3433
3438
  );
3434
3439
  session.taskRunId = meta?.taskRunId;
3435
- this.registerPersistence(sessionId, meta);
3436
3440
  if (meta?.taskRunId) {
3437
3441
  await this.client.extNotification("_posthog/sdk_session", {
3438
3442
  taskRunId: meta.taskRunId,
@@ -3458,6 +3462,7 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3458
3462
  }
3459
3463
  async resumeSession(params) {
3460
3464
  const meta = params._meta;
3465
+ const taskId = meta?.persistence?.taskId;
3461
3466
  const sessionId = meta?.sessionId;
3462
3467
  if (!sessionId) {
3463
3468
  throw new Error("Cannot resume session without sessionId");
@@ -3465,6 +3470,12 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3465
3470
  if (this.sessionId === sessionId) {
3466
3471
  return {};
3467
3472
  }
3473
+ this.logger.info("Resuming session", {
3474
+ sessionId,
3475
+ taskId,
3476
+ taskRunId: meta?.taskRunId,
3477
+ cwd: params.cwd
3478
+ });
3468
3479
  const mcpServers = parseMcpServers(params);
3469
3480
  const permissionMode = meta?.permissionMode && TWIG_EXECUTION_MODES.includes(meta.permissionMode) ? meta.permissionMode : "default";
3470
3481
  const { query: q, session } = await this.initializeQuery({
@@ -3477,15 +3488,36 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3477
3488
  isResume: true,
3478
3489
  additionalDirectories: meta?.claudeCode?.options?.additionalDirectories
3479
3490
  });
3491
+ this.logger.info("Session query initialized, awaiting resumption", {
3492
+ sessionId,
3493
+ taskId,
3494
+ taskRunId: meta?.taskRunId
3495
+ });
3480
3496
  session.taskRunId = meta?.taskRunId;
3481
- this.registerPersistence(sessionId, meta);
3482
- const validation = await withTimeout(
3483
- q.initializationResult(),
3484
- SESSION_VALIDATION_TIMEOUT_MS
3485
- );
3486
- if (validation.result === "timeout") {
3487
- throw new Error("Session validation timed out");
3497
+ try {
3498
+ const result = await withTimeout(
3499
+ q.initializationResult(),
3500
+ SESSION_VALIDATION_TIMEOUT_MS
3501
+ );
3502
+ if (result.result === "timeout") {
3503
+ throw new Error(
3504
+ `Session resumption timed out for sessionId=${sessionId}`
3505
+ );
3506
+ }
3507
+ } catch (err) {
3508
+ this.logger.error("Session resumption failed", {
3509
+ sessionId,
3510
+ taskId,
3511
+ taskRunId: meta?.taskRunId,
3512
+ error: err instanceof Error ? err.message : String(err)
3513
+ });
3514
+ throw err;
3488
3515
  }
3516
+ this.logger.info("Session resumed successfully", {
3517
+ sessionId,
3518
+ taskId,
3519
+ taskRunId: meta?.taskRunId
3520
+ });
3489
3521
  this.deferBackgroundFetches(q, sessionId);
3490
3522
  const configOptions = await this.buildConfigOptions();
3491
3523
  return { configOptions };
@@ -3684,12 +3716,6 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
3684
3716
  this.logger.warn("Failed to fetch deferred session data", { err });
3685
3717
  });
3686
3718
  }
3687
- registerPersistence(sessionId, meta) {
3688
- const persistence = meta?.persistence;
3689
- if (persistence && this.logWriter) {
3690
- this.logWriter.register(sessionId, persistence);
3691
- }
3692
- }
3693
3719
  sendAvailableCommandsUpdate(sessionId, availableCommands) {
3694
3720
  setTimeout(() => {
3695
3721
  this.client.sessionUpdate({
@@ -3977,7 +4003,7 @@ function createClaudeConnection(config) {
3977
4003
  const agentStream = (0, import_sdk3.ndJsonStream)(agentWritable, streams.agent.readable);
3978
4004
  let agent = null;
3979
4005
  const agentConnection = new import_sdk3.AgentSideConnection((client) => {
3980
- agent = new ClaudeAcpAgent(client, logWriter, config.processCallbacks);
4006
+ agent = new ClaudeAcpAgent(client, config.processCallbacks);
3981
4007
  logger.info(`Created ${agent.adapterName} agent`);
3982
4008
  return agent;
3983
4009
  }, agentStream);
@@ -4221,17 +4247,17 @@ function createCodexConnection(config) {
4221
4247
  }
4222
4248
 
4223
4249
  // src/utils/gateway.ts
4224
- function getLlmGatewayUrl(posthogHost) {
4250
+ function getLlmGatewayUrl(posthogHost, product = "twig") {
4225
4251
  const url = new URL(posthogHost);
4226
4252
  const hostname = url.hostname;
4227
4253
  if (hostname === "localhost" || hostname === "127.0.0.1") {
4228
- return `${url.protocol}//localhost:3308/twig`;
4254
+ return `${url.protocol}//localhost:3308/${product}`;
4229
4255
  }
4230
4256
  if (hostname === "host.docker.internal") {
4231
- return `${url.protocol}//host.docker.internal:3308/twig`;
4257
+ return `${url.protocol}//host.docker.internal:3308/${product}`;
4232
4258
  }
4233
4259
  const region = hostname.match(/^(us|eu)\.posthog\.com$/)?.[1] ?? "us";
4234
- return `https://gateway.${region}.posthog.com/twig`;
4260
+ return `https://gateway.${region}.posthog.com/${product}`;
4235
4261
  }
4236
4262
 
4237
4263
  // src/posthog-api.ts
@@ -4417,11 +4443,15 @@ var SessionLogWriter = class _SessionLogWriter {
4417
4443
  }
4418
4444
  async flushAll() {
4419
4445
  const sessionIds = [...this.sessions.keys()];
4420
- const pendingCounts = sessionIds.map((id) => ({
4421
- id,
4422
- pending: this.pendingEntries.get(id)?.length ?? 0,
4423
- messages: this.messageCounts.get(id) ?? 0
4424
- }));
4446
+ const pendingCounts = sessionIds.map((id) => {
4447
+ const session = this.sessions.get(id);
4448
+ return {
4449
+ taskId: session?.context.taskId,
4450
+ runId: session?.context.runId,
4451
+ pending: this.pendingEntries.get(id)?.length ?? 0,
4452
+ messages: this.messageCounts.get(id) ?? 0
4453
+ };
4454
+ });
4425
4455
  this.logger.info("flushAll called", {
4426
4456
  sessions: sessionIds.length,
4427
4457
  pending: pendingCounts
@@ -4437,8 +4467,8 @@ var SessionLogWriter = class _SessionLogWriter {
4437
4467
  return;
4438
4468
  }
4439
4469
  this.logger.info("Session registered", {
4440
- sessionId,
4441
- taskId: context.taskId
4470
+ taskId: context.taskId,
4471
+ runId: context.runId
4442
4472
  });
4443
4473
  this.sessions.set(sessionId, { context });
4444
4474
  this.lastFlushAttemptTime.set(sessionId, Date.now());
@@ -4472,7 +4502,11 @@ var SessionLogWriter = class _SessionLogWriter {
4472
4502
  const count = (this.messageCounts.get(sessionId) ?? 0) + 1;
4473
4503
  this.messageCounts.set(sessionId, count);
4474
4504
  if (count % 10 === 1) {
4475
- this.logger.info("Messages received", { count, sessionId });
4505
+ this.logger.info("Messages received", {
4506
+ count,
4507
+ taskId: session.context.taskId,
4508
+ runId: session.context.runId
4509
+ });
4476
4510
  }
4477
4511
  try {
4478
4512
  const message = JSON.parse(line);
@@ -4503,7 +4537,8 @@ var SessionLogWriter = class _SessionLogWriter {
4503
4537
  }
4504
4538
  } catch {
4505
4539
  this.logger.warn("Failed to parse raw line for persistence", {
4506
- sessionId,
4540
+ taskId: session.context.taskId,
4541
+ runId: session.context.runId,
4507
4542
  lineLength: line.length
4508
4543
  });
4509
4544
  }
@@ -4518,7 +4553,8 @@ var SessionLogWriter = class _SessionLogWriter {
4518
4553
  const pending = this.pendingEntries.get(sessionId);
4519
4554
  if (!this.posthogAPI || !pending?.length) {
4520
4555
  this.logger.info("flush: nothing to persist", {
4521
- sessionId,
4556
+ taskId: session.context.taskId,
4557
+ runId: session.context.runId,
4522
4558
  hasPosthogAPI: !!this.posthogAPI,
4523
4559
  pendingCount: pending?.length ?? 0
4524
4560
  });
@@ -4539,7 +4575,8 @@ var SessionLogWriter = class _SessionLogWriter {
4539
4575
  );
4540
4576
  this.retryCounts.set(sessionId, 0);
4541
4577
  this.logger.info("Flushed session logs", {
4542
- sessionId,
4578
+ taskId: session.context.taskId,
4579
+ runId: session.context.runId,
4543
4580
  entryCount: pending.length
4544
4581
  });
4545
4582
  } catch (error) {
@@ -4548,7 +4585,11 @@ var SessionLogWriter = class _SessionLogWriter {
4548
4585
  if (retryCount >= _SessionLogWriter.MAX_FLUSH_RETRIES) {
4549
4586
  this.logger.error(
4550
4587
  `Dropping ${pending.length} session log entries after ${retryCount} failed flush attempts`,
4551
- { sessionId, error }
4588
+ {
4589
+ taskId: session.context.taskId,
4590
+ runId: session.context.runId,
4591
+ error
4592
+ }
4552
4593
  );
4553
4594
  this.retryCounts.set(sessionId, 0);
4554
4595
  } else {
@@ -4637,7 +4678,12 @@ var SessionLogWriter = class _SessionLogWriter {
4637
4678
  import_node_fs2.default.appendFileSync(logPath, `${JSON.stringify(entry)}
4638
4679
  `);
4639
4680
  } catch (error) {
4640
- this.logger.warn("Failed to write to local cache", { logPath, error });
4681
+ this.logger.warn("Failed to write to local cache", {
4682
+ taskId: session.context.taskId,
4683
+ runId: session.context.runId,
4684
+ logPath,
4685
+ error
4686
+ });
4641
4687
  }
4642
4688
  }
4643
4689
  };
@@ -10678,7 +10724,8 @@ Important:
10678
10724
  }
10679
10725
  configureEnvironment() {
10680
10726
  const { apiKey, apiUrl, projectId } = this.config;
10681
- const gatewayUrl = process.env.LLM_GATEWAY_URL || getLlmGatewayUrl(apiUrl);
10727
+ const product = this.config.mode === "background" ? "background_agents" : "twig";
10728
+ const gatewayUrl = process.env.LLM_GATEWAY_URL || getLlmGatewayUrl(apiUrl, product);
10682
10729
  const openaiBaseUrl = gatewayUrl.endsWith("/v1") ? gatewayUrl : `${gatewayUrl}/v1`;
10683
10730
  Object.assign(process.env, {
10684
10731
  // PostHog