@atolis-hq/wake 0.3.34 → 0.3.36

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.
@@ -37,7 +37,10 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
37
37
  const resources = createResourceService(journal, lookup);
38
38
  const pullRequests = createPullRequestService(journal, work, resources);
39
39
  const activities = options.activities ??
40
- createBuiltInActivityRegistry(journal, pullRequests, resources, wakeRoot, createGitHubAgentContextReader(journal, resources));
40
+ createBuiltInActivityRegistry(journal, pullRequests, resources, wakeRoot, createGitHubAgentContextReader(journal, resources, {
41
+ publicUiUrl: config.surfaces.web.publicUrl,
42
+ githubAdapters: githubAdapters(config),
43
+ }));
41
44
  const definitions = Object.fromEntries(Object.entries(config.orchestration.workflows).map(([name, definition]) => [
42
45
  name,
43
46
  compileWorkflow(name, definition, activities, Object.keys(config.orchestration.workflows)),
@@ -156,3 +159,6 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
156
159
  ...runtime,
157
160
  };
158
161
  }
162
+ function githubAdapters(config) {
163
+ return Object.entries(config.integrations).flatMap(([adapter, integration]) => integration.enabled && (integration.provider ?? adapter) === 'github' ? [adapter] : []);
164
+ }
@@ -108,4 +108,4 @@ export function resolveWakeVersion(options = {}) {
108
108
  return `g${headHash.slice(0, 7)}`;
109
109
  return '0.1.0-dev';
110
110
  }
111
- export const wakeVersion = "g01f75bf";
111
+ export const wakeVersion = "g3fd5716";
@@ -4,9 +4,9 @@ import { adapterId } from '../../contracts/identifiers.js';
4
4
  import { integrationStream } from '../../contracts/streams.js';
5
5
  import { boundedDiagnosticEvidence } from '../contracts/check-evidence.js';
6
6
  import { GitHubEventType, selectGitHubAdapterEvent } from '../contracts/events.js';
7
- import { createCommentHistoryReader } from './comment-history-reader.js';
8
- export function createGitHubAgentContextReader(journal, resources) {
9
- const commentHistory = createCommentHistoryReader(journal, resources);
7
+ import { createCommentHistoryReader, } from './comment-history-reader.js';
8
+ export function createGitHubAgentContextReader(journal, resources, options = {}) {
9
+ const commentHistory = createCommentHistoryReader(journal, resources, options);
10
10
  return {
11
11
  async forWorkItem(workItemId, options) {
12
12
  const comments = await commentHistory.forWorkItem(workItemId, options);
@@ -1,40 +1,149 @@
1
1
  import { ResourceCorrelationRole } from '../../../resources/index.js';
2
2
  import { adapterId } from '../../contracts/identifiers.js';
3
+ import { DeliveryEventType, selectDeliveryEvent } from '../../delivery/contracts/events.js';
4
+ import { DeliveryIntentEventType, selectDeliveryIntentEvent, } from '../../delivery/contracts/intents.js';
5
+ import { DeliveryResultKind } from '../../delivery/contracts/vocabulary.js';
3
6
  import { GitHubEventType, selectGitHubAdapterEvent } from '../contracts/events.js';
4
- export function createCommentHistoryReader(journal, resources) {
7
+ import { GitHubAdapter, UnknownGitHubIdentity } from '../contracts/vocabulary.js';
8
+ import { formatAgentRunComment } from './agent-run-comment.js';
9
+ export function createCommentHistoryReader(journal, resources, readerOptions = {}) {
5
10
  return {
6
11
  async forWorkItem(workItemId, options) {
7
- const keys = new Set((await Promise.all((await resources.correlationsForWork(workItemId))
12
+ const resourcesById = new Map((await Promise.all((await resources.correlationsForWork(workItemId))
8
13
  .filter((correlation) => correlation.role === ResourceCorrelationRole.Primary)
9
- .map((correlation) => resources.get(correlation.resourceId)))).flatMap((resource) => {
10
- if (resource === null || parseAdapterId(resource.externalKey.adapter) === null)
14
+ .map((correlation) => resources.get(correlation.resourceId)))).flatMap((resource) => resource === null ? [] : [[resource.resourceId, resource]]));
15
+ const keys = new Set([...resourcesById.values()].flatMap((resource) => {
16
+ if (parseAdapterId(resource.externalKey.adapter) === null)
11
17
  return [];
12
18
  return [`${resource.externalKey.adapter}:${resource.externalKey.key}`];
13
19
  }));
14
20
  if (keys.size === 0)
15
21
  return [];
16
- return (await journal.readAll(0)).flatMap((event) => {
17
- if (options?.observedSince !== undefined && event.occurredAt <= options.observedSince)
18
- return [];
19
- const observed = selectGitHubAdapterEvent(event);
20
- if (observed?.eventType !== GitHubEventType.CommentObserved)
21
- return [];
22
- if (!keys.has(`${observed.stream.id}:${observed.payload.externalKey}`))
23
- return [];
24
- return [
25
- {
26
- author: observed.payload.actor.id,
27
- occurredAt: observed.occurredAt,
28
- body: observed.payload.body,
29
- ...(observed.payload.reviewKind !== 'issue' || observed.payload.location === undefined
30
- ? {}
31
- : { location: observed.payload.location }),
32
- },
33
- ];
34
- });
22
+ const githubAdapters = new Set(readerOptions.githubAdapters ?? [GitHubAdapter]);
23
+ const githubResourceIds = new Set([...resourcesById.entries()].flatMap(([resourceId, resource]) => githubAdapters.has(resource.externalKey.adapter) ? [resourceId] : []));
24
+ return readCommentHistory(await journal.readAll(0), resourcesById, keys, githubResourceIds, options?.observedSince, readerOptions.publicUiUrl);
25
+ },
26
+ };
27
+ }
28
+ function readCommentHistory(events, resourcesById, keys, githubResourceIds, observedSince, publicUiUrl) {
29
+ const intents = commentIntents(events, githubResourceIds);
30
+ const observed = providerComments(events, keys);
31
+ const confirmed = confirmations(events, intents);
32
+ return reconcileCommentHistory(observed, confirmed, resourcesById, observedSince, publicUiUrl);
33
+ }
34
+ function commentIntents(events, githubResourceIds) {
35
+ const intents = new Map();
36
+ for (const event of events) {
37
+ const intent = selectDeliveryIntentEvent(event);
38
+ if (intent !== null &&
39
+ isCommentIntent(intent) &&
40
+ githubResourceIds.has(intent.payload.resourceId))
41
+ intents.set(intent.eventId, intent);
42
+ }
43
+ return intents;
44
+ }
45
+ function providerComments(events, keys) {
46
+ const observed = new Map();
47
+ for (const event of events) {
48
+ const comment = providerComment(event, keys);
49
+ if (comment !== null)
50
+ observed.set(event.eventId, comment);
51
+ }
52
+ return observed;
53
+ }
54
+ function confirmations(events, intents) {
55
+ const confirmed = new Map();
56
+ for (const event of events) {
57
+ const delivery = selectDeliveryEvent(event);
58
+ if (delivery === null || !isConfirmed(delivery))
59
+ continue;
60
+ const intent = intents.get(delivery.payload.intentEventId);
61
+ if (intent === undefined)
62
+ continue;
63
+ const candidate = { event, intent };
64
+ const current = confirmed.get(delivery.payload.intentEventId);
65
+ if (current === undefined || candidate.event.globalPosition < current.event.globalPosition)
66
+ confirmed.set(delivery.payload.intentEventId, candidate);
67
+ }
68
+ return confirmed;
69
+ }
70
+ function reconcileCommentHistory(observed, confirmed, resourcesById, observedSince, publicUiUrl) {
71
+ const history = new Map();
72
+ for (const entry of observed.values())
73
+ history.set(entry.event.eventId, {
74
+ entry: entry.value,
75
+ occurredAt: entry.event.occurredAt,
76
+ globalPosition: entry.event.globalPosition,
77
+ });
78
+ for (const [intentEventId, confirmation] of confirmed) {
79
+ const resource = resourcesById.get(confirmation.intent.payload.resourceId);
80
+ if (resource === undefined)
81
+ continue;
82
+ const resourceKey = `${resource.externalKey.adapter}:${resource.externalKey.key}`;
83
+ const matchingProvider = [...observed.values()].find((entry) => entry.resourceKey === resourceKey && deliveryMarker(entry.value.body) === intentEventId);
84
+ history.set(intentEventId, {
85
+ entry: matchingProvider?.value ??
86
+ syntheticComment(confirmation.intent, confirmation.event.occurredAt, publicUiUrl),
87
+ occurredAt: confirmation.event.occurredAt,
88
+ globalPosition: confirmation.event.globalPosition,
89
+ });
90
+ if (matchingProvider !== undefined)
91
+ history.delete(matchingProvider.event.eventId);
92
+ }
93
+ return [...history.values()]
94
+ .filter((entry) => observedSince === undefined || entry.occurredAt > observedSince)
95
+ .sort((left, right) => left.globalPosition - right.globalPosition)
96
+ .map((entry) => entry.entry);
97
+ }
98
+ function isCommentIntent(value) {
99
+ return (value.eventType === DeliveryIntentEventType.StatusPublishRequested ||
100
+ value.eventType === DeliveryIntentEventType.ReplyPublishRequested ||
101
+ value.eventType === DeliveryIntentEventType.AgentRunPublishRequested);
102
+ }
103
+ function isConfirmed(value) {
104
+ return (value.eventType === DeliveryEventType.Confirmed ||
105
+ (value.eventType === DeliveryEventType.Reconciled &&
106
+ value.payload.result === DeliveryResultKind.Confirmed));
107
+ }
108
+ function providerComment(event, keys) {
109
+ const observed = selectGitHubAdapterEvent(event);
110
+ if (observed?.eventType !== GitHubEventType.CommentObserved ||
111
+ !keys.has(`${observed.stream.id}:${observed.payload.externalKey}`))
112
+ return null;
113
+ return {
114
+ event,
115
+ resourceKey: `${observed.stream.id}:${observed.payload.externalKey}`,
116
+ value: {
117
+ author: observed.payload.actor.id,
118
+ occurredAt: observed.occurredAt,
119
+ body: observed.payload.body,
120
+ ...(observed.payload.reviewKind !== 'issue' || observed.payload.location === undefined
121
+ ? {}
122
+ : { location: observed.payload.location }),
35
123
  },
36
124
  };
37
125
  }
126
+ function syntheticComment(intent, occurredAt, publicUiUrl) {
127
+ return {
128
+ author: UnknownGitHubIdentity,
129
+ occurredAt,
130
+ body: deliveredCommentBody(intent, publicUiUrl),
131
+ };
132
+ }
133
+ function deliveredCommentBody(intent, publicUiUrl) {
134
+ const marker = `<!-- wake:delivery:${intent.eventId} -->`;
135
+ const body = intent.eventType === DeliveryIntentEventType.AgentRunPublishRequested
136
+ ? formatAgentRunComment({
137
+ idempotencyKey: intent.eventId,
138
+ ...intent.payload.report,
139
+ publicUiUrl,
140
+ })
141
+ : intent.payload.body;
142
+ return `${body}\n${marker}`.trim();
143
+ }
144
+ function deliveryMarker(body) {
145
+ return /<!--\s*wake:delivery:([^\s>]+)\s*-->/.exec(body)?.[1];
146
+ }
38
147
  function parseAdapterId(value) {
39
148
  try {
40
149
  return adapterId(value);
@@ -11,6 +11,7 @@ export function isGitHubWakeEcho(input) {
11
11
  input.labels.some(isGitHubWakeMarker));
12
12
  }
13
13
  export function createGitHubWakeLabelReconciler(input) {
14
+ const syncedDesiredLabels = new Map();
14
15
  const openWorkItemIds = async (workItemIds) => {
15
16
  const open = new Set();
16
17
  for (const workItemId of workItemIds) {
@@ -50,17 +51,22 @@ export function createGitHubWakeLabelReconciler(input) {
50
51
  const locator = parseGitHubIssueKey(resource.externalKey.key);
51
52
  if (locator === null)
52
53
  continue;
54
+ const fingerprint = desired.join('\u0000');
55
+ if (syncedDesiredLabels.get(resource.resourceId) === fingerprint)
56
+ continue;
53
57
  // One issue's persistent failure (rate limit, permissions, a stale
54
58
  // resource) must not stop every other open work item from being
55
59
  // reconciled this pass — each correlation is an independent GitHub
56
60
  // call with no ordering dependency on the others.
57
61
  try {
58
- const current = await input.getLabels(locator.owner, locator.repo, locator.number);
62
+ const current = await request(input, () => input.getLabels(locator.owner, locator.repo, locator.number));
59
63
  const next = reconcileGitHubWakeLabels(current, desired);
60
64
  if (!sameLabels(current, next))
61
- await input.setLabels(locator.owner, locator.repo, locator.number, next);
65
+ await request(input, () => input.setLabels(locator.owner, locator.repo, locator.number, next));
66
+ syncedDesiredLabels.set(resource.resourceId, fingerprint);
62
67
  }
63
68
  catch (error) {
69
+ syncedDesiredLabels.delete(resource.resourceId);
64
70
  onError({ workItemId: workflow.workItemId, ...locator }, error);
65
71
  }
66
72
  }
@@ -68,6 +74,9 @@ export function createGitHubWakeLabelReconciler(input) {
68
74
  },
69
75
  };
70
76
  }
77
+ function request(input, operation) {
78
+ return input.requests === undefined ? operation() : input.requests.run(operation);
79
+ }
71
80
  function defaultOnError(failure, error) {
72
81
  process.stderr.write(`GitHub label reconcile failed for ${failure.owner}/${failure.repo}#${failure.number}: ${error instanceof Error ? error.message : String(error)}\n`);
73
82
  }
@@ -33,11 +33,12 @@ export const gitHubConfigSchema = z
33
33
  polling: z
34
34
  .object({
35
35
  maxPerRepo: z.number().int().positive().default(25),
36
+ maxConcurrent: z.number().int().positive().default(4),
36
37
  commentPageSize: z.number().int().positive().max(100).default(25),
37
38
  lookbackMs: z.number().int().nonnegative().default(60_000),
38
39
  })
39
40
  .strict()
40
- .default({ maxPerRepo: 25, commentPageSize: 25, lookbackMs: 60_000 }),
41
+ .default({ maxPerRepo: 25, maxConcurrent: 4, commentPageSize: 25, lookbackMs: 60_000 }),
41
42
  intake: z.array(intakeRuleSchema).default([]),
42
43
  publication: z
43
44
  .object({ postStatusComments: z.boolean().default(true) })
@@ -0,0 +1,123 @@
1
+ export class GitHubRequestCooldownError extends Error {
2
+ retryAt;
3
+ constructor(retryAt) {
4
+ super(`GitHub provider is cooling down until ${new Date(retryAt).toISOString()}`);
5
+ this.retryAt = retryAt;
6
+ this.name = 'GitHubRequestCooldownError';
7
+ }
8
+ }
9
+ export function createGitHubRequestCoordinator(options) {
10
+ return new CoordinatedGitHubRequests(options);
11
+ }
12
+ class CoordinatedGitHubRequests {
13
+ options;
14
+ queue = [];
15
+ now;
16
+ active = 0;
17
+ draining = false;
18
+ cooldownUntil = 0;
19
+ transientFailureCount = 0;
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.now = options.now ?? Date.now;
23
+ }
24
+ run(request) {
25
+ return new Promise((resolve, reject) => {
26
+ this.queue.push({
27
+ request: request,
28
+ resolve: resolve,
29
+ reject,
30
+ });
31
+ void this.drain();
32
+ });
33
+ }
34
+ async drain() {
35
+ if (this.draining)
36
+ return;
37
+ this.draining = true;
38
+ try {
39
+ while (this.active < this.options.maxConcurrent && this.queue.length > 0) {
40
+ if (this.cooldownUntil > this.now()) {
41
+ const error = new GitHubRequestCooldownError(this.cooldownUntil);
42
+ this.queue.splice(0).forEach((pending) => pending.reject(error));
43
+ return;
44
+ }
45
+ const pending = this.queue.shift();
46
+ this.active += 1;
47
+ void Promise.resolve()
48
+ .then(pending.request)
49
+ .then((value) => {
50
+ this.transientFailureCount = 0;
51
+ pending.resolve(value);
52
+ }, (error) => {
53
+ this.recordFailure(error);
54
+ pending.reject(error);
55
+ })
56
+ .finally(() => {
57
+ this.active -= 1;
58
+ void this.drain();
59
+ });
60
+ }
61
+ }
62
+ finally {
63
+ this.draining = false;
64
+ }
65
+ }
66
+ recordFailure(error) {
67
+ const retryAfterMs = retryAfterMilliseconds(error, this.now());
68
+ if (statusOf(error) === 429) {
69
+ this.cooldownUntil = this.now() + (retryAfterMs ?? 60_000);
70
+ this.transientFailureCount = 0;
71
+ return;
72
+ }
73
+ if (isTransient(error)) {
74
+ const delay = Math.min(5_000 * 2 ** this.transientFailureCount, 60_000);
75
+ this.transientFailureCount += 1;
76
+ this.cooldownUntil = this.now() + delay;
77
+ }
78
+ }
79
+ }
80
+ function statusOf(error) {
81
+ if (typeof error !== 'object' || error === null || !('status' in error))
82
+ return undefined;
83
+ return typeof error.status === 'number' ? error.status : undefined;
84
+ }
85
+ function isTransient(error) {
86
+ const status = statusOf(error);
87
+ if (status !== undefined)
88
+ return status >= 500;
89
+ return (error instanceof TypeError ||
90
+ (typeof error === 'object' &&
91
+ error !== null &&
92
+ 'code' in error &&
93
+ typeof error.code === 'string'));
94
+ }
95
+ function retryAfterMilliseconds(error, now) {
96
+ const value = retryAfterValue(error);
97
+ if (value === undefined || value === null)
98
+ return undefined;
99
+ const seconds = Number(value);
100
+ if (Number.isFinite(seconds) && seconds >= 0)
101
+ return seconds * 1_000;
102
+ const timestamp = Date.parse(value);
103
+ return Number.isFinite(timestamp) ? Math.max(0, timestamp - now) : undefined;
104
+ }
105
+ function retryAfterValue(error) {
106
+ if (typeof error !== 'object' || error === null || !('response' in error))
107
+ return undefined;
108
+ const response = error.response;
109
+ if (typeof response !== 'object' || response === null || !('headers' in response))
110
+ return undefined;
111
+ return headerValue(response.headers);
112
+ }
113
+ function headerValue(headers) {
114
+ if (typeof headers !== 'object' || headers === null)
115
+ return undefined;
116
+ if ('get' in headers && typeof headers.get === 'function') {
117
+ const value = headers.get('retry-after');
118
+ return typeof value === 'string' ? value : undefined;
119
+ }
120
+ if ('retry-after' in headers && typeof headers['retry-after'] === 'string')
121
+ return headers['retry-after'];
122
+ return undefined;
123
+ }
@@ -2,8 +2,11 @@ import { ReviewerAuthorizationSource, } from '../../../activities/index.js';
2
2
  import { GitHubEventType } from '../contracts/events.js';
3
3
  import { issueCommentObservation, issueObservation } from './issue-source.js';
4
4
  import { createGitHubPullRequestSource } from './pr-source.js';
5
+ import { createGitHubRequestCoordinator, } from './request-coordinator.js';
5
6
  import { githubReviewObservation } from './review-source.js';
6
- export function createGitHubSource(config, client, adapter) {
7
+ export function createGitHubSource(config, client, adapter, requests = createGitHubRequestCoordinator({
8
+ maxConcurrent: config.polling.maxConcurrent,
9
+ })) {
7
10
  let nextPollAt = 0;
8
11
  // Draft eventIds are already content fingerprints (see issue-source.ts/pr-source.ts),
9
12
  // so the journal itself is idempotent per item. This cache only avoids re-appending
@@ -16,7 +19,14 @@ export function createGitHubSource(config, client, adapter) {
16
19
  if (Date.now() < nextPollAt)
17
20
  return [];
18
21
  nextPollAt = Date.now() + config.polling.lookbackMs;
19
- const perRepository = await Promise.all(config.repositories.map(({ owner, repo }) => pollRepository({ client, config, adapter, signal, owner, repo })));
22
+ const perRepository = await Promise.all(config.repositories.map(({ owner, repo }) => pollRepository({
23
+ client: limitGitHubSourceClient(client, requests),
24
+ config,
25
+ adapter,
26
+ signal,
27
+ owner,
28
+ repo,
29
+ })));
20
30
  return perRepository.flat().filter((draft) => {
21
31
  if (draft.eventType !== GitHubEventType.WorkObserved)
22
32
  return true;
@@ -27,6 +37,28 @@ export function createGitHubSource(config, client, adapter) {
27
37
  },
28
38
  };
29
39
  }
40
+ function limitGitHubSourceClient(client, requests) {
41
+ return {
42
+ ...client,
43
+ listIssues: (owner, repo, maxResults) => requests.run(() => client.listIssues(owner, repo, maxResults)),
44
+ listPullRequests: (owner, repo, maxResults) => requests.run(() => client.listPullRequests(owner, repo, maxResults)),
45
+ listCheckRunsForRef: (owner, repo, ref) => requests.run(() => client.listCheckRunsForRef(owner, repo, ref)),
46
+ getCombinedStatusForRef: (owner, repo, ref) => requests.run(() => client.getCombinedStatusForRef(owner, repo, ref)),
47
+ listPullRequestFiles: (owner, repo, pullNumber) => requests.run(() => client.listPullRequestFiles(owner, repo, pullNumber)),
48
+ listIssueComments: (owner, repo, issueNumber, pageSize) => requests.run(() => client.listIssueComments(owner, repo, issueNumber, pageSize)),
49
+ listReviews: (owner, repo, pullNumber, pageSize) => requests.run(() => client.listReviews(owner, repo, pullNumber, pageSize)),
50
+ ...(client.listReviewComments === undefined
51
+ ? {}
52
+ : {
53
+ listReviewComments: (owner, repo, pullNumber, pageSize) => requests.run(() => client.listReviewComments(owner, repo, pullNumber, pageSize)),
54
+ }),
55
+ ...(client.collaboratorPermission === undefined
56
+ ? {}
57
+ : {
58
+ collaboratorPermission: (owner, repo, login) => requests.run(() => client.collaboratorPermission(owner, repo, login)),
59
+ }),
60
+ };
61
+ }
30
62
  async function pollRepository(input) {
31
63
  const { client, config, adapter, signal, owner, repo } = input;
32
64
  const context = {
@@ -9,6 +9,7 @@ import { GitHubEventType } from './contracts/events.js';
9
9
  import { createGitHubClient } from './infrastructure/client.js';
10
10
  import { createGitHubDelivery } from './infrastructure/delivery.js';
11
11
  import { resolveGitHubCliToken } from './infrastructure/gh-auth.js';
12
+ import { createGitHubRequestCoordinator } from './infrastructure/request-coordinator.js';
12
13
  import { createGitHubSource } from './infrastructure/source.js';
13
14
  export const gitHubProviderDefinition = {
14
15
  provider: 'github',
@@ -20,16 +21,20 @@ export const gitHubProviderDefinition = {
20
21
  if (services === undefined)
21
22
  throw new Error('GitHub provider requires composed services');
22
23
  const client = createGitHubClient(config.token ?? resolveGitHubCliToken());
24
+ const requests = createGitHubRequestCoordinator({
25
+ maxConcurrent: config.polling.maxConcurrent,
26
+ });
23
27
  return {
24
28
  adapter,
25
29
  eventTypes: Object.values(GitHubEventType),
26
- source: createGitHubSource(config, client, adapter),
30
+ source: createGitHubSource(config, client, adapter, requests),
27
31
  maintenance: createGitHubWakeLabelReconciler({
28
32
  orchestration: services.orchestration,
29
33
  resources: services.resources,
30
34
  work: services.work,
31
35
  getLabels: client.getIssueLabels,
32
36
  setLabels: client.setIssueLabels,
37
+ requests,
33
38
  }),
34
39
  delivery: createGitHubDelivery(async (intent, idempotencyKey) => {
35
40
  const resource = await services.resources.get(resourceId(intent.resourceId));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.3.34",
3
+ "version": "0.3.36",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {