@leitwerk-dev/woodpecker 0.0.0-bootstrap.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,83 @@
1
- Registration placeholder only. Not a usable Leitwerk release.
1
+ # Woodpecker integration
2
+
3
+ Server-owned Woodpecker profiles, pipeline external sources, bounded log access, and workflow-focused LLM tools. Tokens never enter workers.
4
+
5
+ ```yaml
6
+ extensions:
7
+ woodpecker:
8
+ profiles:
9
+ primary:
10
+ base_url: https://ci.example.test
11
+ token: "..."
12
+ ```
13
+
14
+ The extension targets the Woodpecker 3 API. Tools resolve the current process
15
+ repository, list or inspect pipelines, decode and bound step logs, and explicitly
16
+ restart a diagnosed pipeline. The external source waits indefinitely until the
17
+ newest repository/SHA/event match is terminal. Push pipelines must also match
18
+ the configured source branch. Woodpecker reports the target branch for pull
19
+ request pipelines, so pull request events match by source-head SHA instead.
20
+
21
+ ## Explicit integration composition
22
+
23
+ `WoodpeckerClientLike` and `setupWoodpeckerIntegration` support alternate clients
24
+ with the same tool registration, durable writes and correlated pipeline polling.
25
+ An optional clock permits deterministic local polling.
26
+
27
+ ## Project binding
28
+
29
+ Server launch code writes a non-secret `metadata.woodpecker` object containing
30
+ `{ owner, repo, profile }` on each process project. Tools use only the project
31
+ selected and authorized by the server, never repository/profile tool arguments.
32
+ `WoodpeckerProjectBinding` and `resolveWoodpeckerProjectBinding` expose this contract.
33
+ Different projects in one process may use different profiles. Credentials remain
34
+ in the server integration; bindings contain only a profile identifier.
35
+
36
+ When `metadata.woodpecker` is absent, the compatibility reader uses the old
37
+ `metadata.forgejo` repository and `woodpeckerProfile` process parameter.
38
+ An explicit Woodpecker binding must contain all three fields.
39
+ Malformed explicit values fail instead of selecting another profile.
40
+ Capability, watcher, external-source and write identifiers retain their original
41
+ strings, including historical `@leitwerk-private/` prefixes. Package names do not
42
+ rename durable protocol identities.
43
+
44
+ ## Local adapter
45
+
46
+ Import `LocalWoodpeckerAdapter` from `@leitwerk-dev/woodpecker/testing` and supply its
47
+ `client()` through `setupWoodpeckerIntegration`. Construct the adapter with an owned
48
+ `root` directory, a local `baseUrl`, and an optional `now` clock. Provider state
49
+ persists in `woodpecker.json`; unknown resources fail locally. Production registration
50
+ does not import this entrypoint. The adapter never falls back to HTTP.
51
+
52
+ `seed(fullName)` registers a CI repository without a Git-host dependency.
53
+ `publish(repository, { branch, commit, event, status, logs })` supplies correlated
54
+ pipeline results. Local Git compositions resolve the actual commit before calling it.
55
+
56
+ ## Pipeline lookup window
57
+
58
+ `listPipelines(repoId, signal?, { page, perPage })` defaults to page 1 with 100
59
+ pipelines. Correlated polling searches up to 10 pages (1,000 newest pipelines),
60
+ stopping at the newest match, exhausted history, or `afterPipelineNumber`.
61
+ A newest pending match continues waiting even if an older match is terminal.
62
+ An inconclusive scan reports a lookup-window error; inspect repository history
63
+ and adjust the watched pipeline floor before retrying. No match within exhausted
64
+ history is an ordinary wait for a future pipeline.
65
+
66
+ ## API support
67
+
68
+ The following exported declarations are `@public`:
69
+
70
+ - `@leitwerk-dev/woodpecker`: `WoodpeckerClient`, `WoodpeckerClientLike`, `WoodpeckerIntegration`, `WoodpeckerPipeline`, `WoodpeckerProjectBinding`, `WoodpeckerRepository`, `default`, `setupWoodpeckerIntegration`.
71
+ - `@leitwerk-dev/woodpecker/testing`: `LocalWoodpeckerAdapter`, `LocalWoodpeckerOptions`, `LocalWoodpeckerRepository`, `LocalWoodpeckerState`.
72
+
73
+ Members have individual classifications; these exports do not make every member
74
+ public. Both `@public` and `@internal` APIs remain usable and fully typed. Source
75
+ annotations are authoritative; see the [SDK compatibility
76
+ policy](../../docs/process-sdk.md#api-compatibility).
77
+
78
+ ### External-write replay
79
+
80
+ Pipeline restart uses `ctx.externalWrites.logOnly()` and returns `{ ok: true }`.
81
+ The durable record includes diagnosis metadata and prevents a recorded restart
82
+ from repeating. Lost responses and remote success followed by recording failure
83
+ cannot be recovered. Pipeline status is not evidence that a restart occurred.
package/dist/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2026 Leitwerk contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
2
+ /** @internal */
3
+ export declare const resolveWoodpeckerProjectBinding: (ctx: Parameters<typeof resolveRepositoryProjectBinding>[0]) => import("@leitwerk-dev/process-sdk").RepositoryProjectBinding;
4
+ //# sourceMappingURL=binding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.d.ts","sourceRoot":"","sources":["../src/binding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AAE5E,gBAAgB;AAChB,eAAO,MAAM,+BAA+B,GAC3C,KAAK,UAAU,CAAC,OAAO,+BAA+B,CAAC,CAAC,CAAC,CAAC,iEACO,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { WoodpeckerClient } from "./client.js";
2
+ /** Public contract shared by HTTP and local adapters. @public */
3
+ export type WoodpeckerClientLike = Pick<WoodpeckerClient, keyof WoodpeckerClient>;
4
+ /** @public */
5
+ export interface WoodpeckerIntegration {
6
+ /** @public */
7
+ client(profile: string): WoodpeckerClientLike;
8
+ }
9
+ /** @internal */
10
+ export declare const woodpeckerIntegration: import("@leitwerk-dev/process-sdk").CapabilityToken<WoodpeckerIntegration>;
11
+ //# sourceMappingURL=capability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,iEAAiE;AACjE,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,EAAE,MAAM,gBAAgB,CAAC,CAAC;AAElF,cAAc;AACd,MAAM,WAAW,qBAAqB;IACrC,cAAc;IACd,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,CAAC;CAC9C;AACD,gBAAgB;AAChB,eAAO,MAAM,qBAAqB,4EAEjC,CAAC"}
@@ -0,0 +1,13 @@
1
+ // src/logs.ts
2
+ function boundedLogTail(lines, tailLines, maxBytes) {
3
+ const encoded = Buffer.from(lines.slice(-Math.min(Math.max(tailLines, 1), 2e3)).join("\n"));
4
+ const cap = Math.min(Math.max(maxBytes, 1), 1048576);
5
+ let start = Math.max(0, encoded.length - cap);
6
+ while (start < encoded.length && (encoded[start] & 192) === 128) start++;
7
+ return encoded.subarray(start).toString("utf8");
8
+ }
9
+
10
+ export {
11
+ boundedLogTail
12
+ };
13
+ //# sourceMappingURL=chunk-L6GKOYHO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/logs.ts"],"sourcesContent":["/** Keep a bounded tail without splitting a UTF-8 character. */\nexport function boundedLogTail(lines: string[], tailLines: number, maxBytes: number): string {\n\tconst encoded = Buffer.from(lines.slice(-Math.min(Math.max(tailLines, 1), 2_000)).join(\"\\n\"));\n\tconst cap = Math.min(Math.max(maxBytes, 1), 1_048_576);\n\tlet start = Math.max(0, encoded.length - cap);\n\twhile (start < encoded.length && (encoded[start] & 0xc0) === 0x80) start++;\n\treturn encoded.subarray(start).toString(\"utf8\");\n}\n"],"mappings":";AACO,SAAS,eAAe,OAAiB,WAAmB,UAA0B;AAC5F,QAAM,UAAU,OAAO,KAAK,MAAM,MAAM,CAAC,KAAK,IAAI,KAAK,IAAI,WAAW,CAAC,GAAG,GAAK,CAAC,EAAE,KAAK,IAAI,CAAC;AAC5F,QAAM,MAAM,KAAK,IAAI,KAAK,IAAI,UAAU,CAAC,GAAG,OAAS;AACrD,MAAI,QAAQ,KAAK,IAAI,GAAG,QAAQ,SAAS,GAAG;AAC5C,SAAO,QAAQ,QAAQ,WAAW,QAAQ,KAAK,IAAI,SAAU,IAAM;AACnE,SAAO,QAAQ,SAAS,KAAK,EAAE,SAAS,MAAM;AAC/C;","names":[]}
@@ -0,0 +1,66 @@
1
+ import { IntegrationHttpClient } from "@leitwerk-dev/process-sdk";
2
+ /** @internal */
3
+ export interface WoodpeckerProfile {
4
+ /** @internal */
5
+ baseUrl: string;
6
+ /** @internal */
7
+ token: string;
8
+ }
9
+ /** @public */
10
+ export interface WoodpeckerRepository {
11
+ /** @public */
12
+ id: number;
13
+ /** @public */
14
+ full_name: string;
15
+ }
16
+ /** @public */
17
+ export interface WoodpeckerPipeline {
18
+ /** @internal */
19
+ id: number;
20
+ /** @internal */
21
+ number: number;
22
+ /** @internal */
23
+ status: string;
24
+ /** @internal */
25
+ event: string;
26
+ /** @internal */
27
+ branch: string;
28
+ /** @internal */
29
+ commit: string;
30
+ /** @internal */
31
+ created_at?: number;
32
+ /** @internal */
33
+ workflows?: unknown[];
34
+ }
35
+ /** @internal */
36
+ export declare function parseWoodpeckerProfiles(value: unknown): Map<string, WoodpeckerProfile>;
37
+ /** @public */
38
+ export declare class WoodpeckerClient extends IntegrationHttpClient {
39
+ /** @internal */
40
+ readonly profile: WoodpeckerProfile;
41
+ /** @internal */
42
+ constructor(
43
+ /** @internal */
44
+ profile: WoodpeckerProfile);
45
+ /** @internal */
46
+ lookupRepository(fullName: string, signal?: AbortSignal): Promise<WoodpeckerRepository>;
47
+ /** @internal */
48
+ listPipelines(repoId: number, signal?: AbortSignal, pagination?: {
49
+ /** @internal */
50
+ page: number;
51
+ /** @internal */
52
+ perPage?: number;
53
+ }): Promise<WoodpeckerPipeline[]>;
54
+ /** @internal */
55
+ getPipeline(repoId: number, number: number, signal?: AbortSignal): Promise<WoodpeckerPipeline>;
56
+ /** @public */
57
+ getStepLogs(repoId: number, number: number, stepId: number, tailLines?: number, maxBytes?: number, signal?: AbortSignal): Promise<{
58
+ /** @public */
59
+ logs: string;
60
+ /** @internal */
61
+ truncated: boolean;
62
+ }>;
63
+ /** @internal */
64
+ restartPipeline(repoId: number, number: number, signal?: AbortSignal): Promise<WoodpeckerPipeline>;
65
+ }
66
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAGlE,gBAAgB;AAChB,MAAM,WAAW,iBAAiB;IACjC,gBAAgB;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB;IAChB,KAAK,EAAE,MAAM,CAAC;CACd;AACD,cAAc;AACd,MAAM,WAAW,oBAAoB;IACpC,cAAc;IACd,EAAE,EAAE,MAAM,CAAC;IACX,cAAc;IACd,SAAS,EAAE,MAAM,CAAC;CAClB;AACD,cAAc;AACd,MAAM,WAAW,kBAAkB;IAClC,gBAAgB;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gBAAgB;IAChB,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC;CACtB;AAwBD,gBAAgB;AAChB,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CActF;AAED,cAAc;AACd,qBAAa,gBAAiB,SAAQ,qBAAqB;IAGzD,gBAAgB;IAChB,QAAQ,CAAC,OAAO,EAAE,iBAAiB;IAHpC,gBAAgB;;IAEf,gBAAgB;IACP,OAAO,EAAE,iBAAiB;IAQpC,gBAAgB;IAChB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAMvF,gBAAgB;IAChB,aAAa,CACZ,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,EACpB,UAAU,GAAE;QACX,gBAAgB;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,gBAAgB;QAChB,OAAO,CAAC,EAAE,MAAM,CAAC;KACH,GACb,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAehC,gBAAgB;IAChB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAI9F,cAAc;IACR,WAAW,CAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,SAAS,SAAM,EACf,QAAQ,SAAU,EAClB,MAAM,CAAC,EAAE,WAAW;QAyBnB,cAAc;;QAEd,gBAAgB;;;IAKlB,gBAAgB;IAChB,eAAe,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,kBAAkB,CAAC;CAM9B"}
@@ -0,0 +1,35 @@
1
+ import type { ExternalActionSource } from "@leitwerk-dev/process-sdk";
2
+ /** @internal */
3
+ export declare const WOODPECKER_PIPELINE_KIND = "@leitwerk-private/woodpecker.pipeline";
4
+ /** @internal */
5
+ export interface WoodpeckerPipelineSourceConfig {
6
+ /** @internal */
7
+ profile: string;
8
+ /** @internal */
9
+ owner: string;
10
+ /** @internal */
11
+ repo: string;
12
+ /** @internal */
13
+ branch: string;
14
+ /** @internal */
15
+ headSha: string;
16
+ /** @internal */
17
+ afterPipelineNumber?: number;
18
+ /** @internal */
19
+ disabled?: boolean;
20
+ /** @internal */
21
+ pollInterval?: string;
22
+ /** @internal */
23
+ statuses?: string[];
24
+ }
25
+ /** @internal */
26
+ export declare const woodpeckerExternal: {
27
+ /** @internal */
28
+ pipeline<TParams, TState>(resolve: (ctx: {
29
+ /** @internal */
30
+ params: TParams;
31
+ /** @internal */
32
+ state: TState;
33
+ }) => WoodpeckerPipelineSourceConfig): ExternalActionSource<TParams, TState>;
34
+ };
35
+ //# sourceMappingURL=external.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"external.d.ts","sourceRoot":"","sources":["../src/external.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,gBAAgB;AAChB,eAAO,MAAM,wBAAwB,0CAA0C,CAAC;AAChF,gBAAgB;AAChB,MAAM,WAAW,8BAA8B;IAC9C,gBAAgB;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,gBAAgB;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,gBAAgB;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gBAAgB;IAChB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB;AACD,gBAAgB;AAChB,eAAO,MAAM,kBAAkB;IAC9B,gBAAgB;aACP,OAAO,EAAE,MAAM,WACd,CAAC,GAAG,EAAE;QACd,gBAAgB;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,gBAAgB;QAChB,KAAK,EAAE,MAAM,CAAC;KACd,KAAK,8BAA8B,GAClC,oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC;CAUxC,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
+ import { type WoodpeckerIntegration } from "./capability.js";
3
+ /** @public */
4
+ declare const extension: LeitwerkExtensionModule;
5
+ export type { WoodpeckerIntegration } from "./capability.js";
6
+ export { woodpeckerIntegration } from "./capability.js";
7
+ export type { WoodpeckerPipeline } from "./client.js";
8
+ export { WOODPECKER_PIPELINE_KIND, woodpeckerExternal } from "./external.js";
9
+ export default extension;
10
+ /** Register shared tools and polling with an explicit integration. @public */
11
+ export declare function setupWoodpeckerIntegration(api: Parameters<NonNullable<LeitwerkExtensionModule["setupServer"]>>[0], integration: WoodpeckerIntegration, options?: {
12
+ /** @public */
13
+ now?: () => number;
14
+ }): {
15
+ /** @public */
16
+ poll(): Promise<import("@leitwerk-dev/watcher-utils").PollResult>;
17
+ } | undefined;
18
+ export * from "./binding.js";
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,KAAK,qBAAqB,EAAyB,MAAM,iBAAiB,CAAC;AAYpF,cAAc;AACd,QAAA,MAAM,SAAS,EAAE,uBAahB,CAAC;AAEF,YAAY,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAC7E,eAAe,SAAS,CAAC;AAEzB,8EAA8E;AAC9E,wBAAgB,0BAA0B,CACzC,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,uBAAuB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EACvE,WAAW,EAAE,qBAAqB,EAClC,OAAO,GAAE;IACR,cAAc;IACd,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACd;;;cAON;AAED,cAAc,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,359 @@
1
+ import {
2
+ boundedLogTail
3
+ } from "./chunk-L6GKOYHO.js";
4
+
5
+ // src/index.ts
6
+ import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
7
+
8
+ // src/capability.ts
9
+ import { createCapabilityToken } from "@leitwerk-dev/process-sdk";
10
+ var woodpeckerIntegration = createCapabilityToken(
11
+ "@leitwerk-private/woodpecker.integration"
12
+ );
13
+
14
+ // src/client.ts
15
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
16
+ import { IntegrationHttpClient } from "@leitwerk-dev/process-sdk";
17
+ function decodeLogData(data) {
18
+ if (Array.isArray(data)) {
19
+ return new TextDecoder("utf-8", { fatal: false }).decode(Uint8Array.from(data));
20
+ }
21
+ if (typeof data !== "string") return "";
22
+ if (/^[A-Za-z0-9+/]*={0,2}$/.test(data) && data.length % 4 === 0) {
23
+ try {
24
+ const binary = atob(data);
25
+ return new TextDecoder("utf-8", { fatal: false }).decode(
26
+ Uint8Array.from(binary, (character) => character.charCodeAt(0))
27
+ );
28
+ } catch {
29
+ }
30
+ }
31
+ return data;
32
+ }
33
+ function parseWoodpeckerProfiles(value) {
34
+ const profiles = /* @__PURE__ */ new Map();
35
+ for (const [name, raw] of Object.entries(
36
+ asUnknownRecord(asUnknownRecord(value)?.profiles) ?? {}
37
+ )) {
38
+ const config = asUnknownRecord(raw) ?? {};
39
+ const baseUrl = typeof config.base_url === "string" ? config.base_url.replace(/\/+$/, "") : "";
40
+ const token = typeof config.token === "string" ? config.token.trim() : "";
41
+ if (!/^https:\/\//.test(baseUrl))
42
+ throw new Error(`Woodpecker profile '${name}' requires an HTTPS base_url`);
43
+ if (!token) throw new Error(`Woodpecker profile '${name}' requires a token`);
44
+ profiles.set(name, { baseUrl, token });
45
+ }
46
+ return profiles;
47
+ }
48
+ var WoodpeckerClient = class extends IntegrationHttpClient {
49
+ /** @internal */
50
+ constructor(profile) {
51
+ super("Woodpecker", `${profile.baseUrl}/api`, {
52
+ Authorization: `Bearer ${profile.token}`,
53
+ Accept: "application/json"
54
+ });
55
+ this.profile = profile;
56
+ }
57
+ profile;
58
+ /** @internal */
59
+ lookupRepository(fullName, signal) {
60
+ return this.request(`/repos/lookup/${encodeURIComponent(fullName)}`, {
61
+ signal
62
+ });
63
+ }
64
+ /** @internal */
65
+ listPipelines(repoId, signal, pagination = { page: 1 }) {
66
+ const { page, perPage = 100 } = pagination;
67
+ if (!Number.isSafeInteger(page) || page < 1 || !Number.isSafeInteger(perPage) || perPage < 1 || perPage > 100)
68
+ throw new Error("Invalid Woodpecker pipeline pagination");
69
+ return this.request(`/repos/${repoId}/pipelines?page=${page}&perPage=${perPage}`, {
70
+ signal
71
+ });
72
+ }
73
+ /** @internal */
74
+ getPipeline(repoId, number, signal) {
75
+ return this.request(`/repos/${repoId}/pipelines/${number}`, { signal });
76
+ }
77
+ /** @public */
78
+ async getStepLogs(repoId, number, stepId, tailLines = 400, maxBytes = 262144, signal) {
79
+ const body = await (await this.response(`/repos/${repoId}/logs/${number}/${stepId}`, {
80
+ signal
81
+ })).text();
82
+ let text = body;
83
+ try {
84
+ const entries = JSON.parse(body);
85
+ if (Array.isArray(entries)) {
86
+ text = entries.map(
87
+ (entry) => decodeLogData(asUnknownRecord(entry)?.data).replace(
88
+ /\r?\n$/,
89
+ ""
90
+ )
91
+ ).join("\n");
92
+ }
93
+ } catch {
94
+ }
95
+ const output = boundedLogTail(text.split(/\r?\n/), tailLines, maxBytes);
96
+ return {
97
+ /** @public */
98
+ logs: output,
99
+ /** @internal */
100
+ truncated: output.length < text.length
101
+ };
102
+ }
103
+ /** @internal */
104
+ restartPipeline(repoId, number, signal) {
105
+ return this.request(`/repos/${repoId}/pipelines/${number}`, {
106
+ method: "POST",
107
+ signal
108
+ });
109
+ }
110
+ };
111
+
112
+ // src/provider.ts
113
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
114
+ import {
115
+ createExternalSourcePollReporter
116
+ } from "@leitwerk-dev/process-sdk";
117
+ import { createPollSchedule, emptyPollResult } from "@leitwerk-dev/watcher-utils";
118
+
119
+ // src/external.ts
120
+ var WOODPECKER_PIPELINE_KIND = "@leitwerk-private/woodpecker.pipeline";
121
+ var woodpeckerExternal = {
122
+ /** @internal */
123
+ pipeline(resolve) {
124
+ return {
125
+ kind: WOODPECKER_PIPELINE_KIND,
126
+ label: "Woodpecker pipeline completion",
127
+ description: "Fires when a pipeline matching the current source head completes",
128
+ config: {},
129
+ inputMode: "none",
130
+ resolve
131
+ };
132
+ }
133
+ };
134
+
135
+ // src/provider.ts
136
+ function parse(value) {
137
+ const config = asUnknownRecord2(value) ?? {};
138
+ if (["profile", "owner", "repo", "branch", "headSha"].some(
139
+ (key) => typeof config[key] !== "string" || !config[key].trim()
140
+ ))
141
+ return null;
142
+ return {
143
+ profile: config.profile,
144
+ owner: config.owner,
145
+ repo: config.repo,
146
+ branch: config.branch,
147
+ headSha: config.headSha,
148
+ afterPipelineNumber: typeof config.afterPipelineNumber === "number" ? config.afterPipelineNumber : 0,
149
+ disabled: config.disabled === true,
150
+ pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
151
+ statuses: Array.isArray(config.statuses) ? config.statuses.filter((value2) => typeof value2 === "string") : void 0
152
+ };
153
+ }
154
+ var terminal = /* @__PURE__ */ new Set([
155
+ "success",
156
+ "failure",
157
+ "error",
158
+ "killed",
159
+ "canceled",
160
+ "cancelled",
161
+ "declined",
162
+ "blocked"
163
+ ]);
164
+ var supportedEvents = /* @__PURE__ */ new Set(["push", "pull_request", "pull_request_closed"]);
165
+ function matchesBranch(event, pipelineBranch, sourceBranch) {
166
+ return event !== "push" || pipelineBranch === sourceBranch;
167
+ }
168
+ function createWoodpeckerProvider(deps, integration, options = {}) {
169
+ const due = createPollSchedule(options.now);
170
+ return deps.polling.create({
171
+ id: "woodpecker",
172
+ pollInterval: () => "5s",
173
+ isEnabled: () => true,
174
+ defaultIntervalMs: 5e3,
175
+ async pollOnce() {
176
+ const result = emptyPollResult();
177
+ const report = createExternalSourcePollReporter(deps.externalSources, result);
178
+ await report.poll(WOODPECKER_PIPELINE_KIND, async (armed) => {
179
+ const config = parse(armed.resolved);
180
+ if (!config) {
181
+ result.errors.push(`${armed.id}:invalid_config`);
182
+ return;
183
+ }
184
+ if (config.disabled) return;
185
+ const key = `${armed.instanceId}:${armed.id}`;
186
+ if (!due(key, config.pollInterval)) return;
187
+ const client = integration.client(config.profile);
188
+ const repo = await client.lookupRepository(`${config.owner}/${config.repo}`);
189
+ const pipeline = await findLatestPipeline(client, repo.id, config);
190
+ if (!pipeline || !terminal.has(pipeline.status) || config.statuses && !config.statuses.includes(pipeline.status))
191
+ return;
192
+ await report.fire(
193
+ armed,
194
+ { repositoryId: repo.id, pipeline },
195
+ `${pipeline.number}:${pipeline.status}`
196
+ );
197
+ });
198
+ return result;
199
+ }
200
+ });
201
+ }
202
+ async function findLatestPipeline(client, repoId, config) {
203
+ for (let page = 1; page <= 10; page++) {
204
+ const pipelines = (await client.listPipelines(repoId, void 0, { page, perPage: 100 })).sort(
205
+ (a, b) => b.number - a.number
206
+ );
207
+ const match = pipelines.find(
208
+ (candidate) => candidate.number > (config.afterPipelineNumber ?? 0) && candidate.commit === config.headSha && supportedEvents.has(candidate.event) && matchesBranch(candidate.event, candidate.branch, config.branch)
209
+ );
210
+ if (match) return match;
211
+ if (pipelines.length < 100 || pipelines.some((candidate) => candidate.number <= (config.afterPipelineNumber ?? 0)))
212
+ return null;
213
+ }
214
+ throw new Error(
215
+ "Woodpecker pipeline lookup window exhausted (1000 pipelines); inspect the repository and update the watched pipeline floor before retrying"
216
+ );
217
+ }
218
+
219
+ // src/tools.ts
220
+ import {
221
+ numberArg,
222
+ projectParameters,
223
+ stringArg
224
+ } from "@leitwerk-dev/process-sdk";
225
+
226
+ // src/binding.ts
227
+ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
228
+ var resolveWoodpeckerProjectBinding = (ctx) => resolveRepositoryProjectBinding(ctx, "woodpecker", "forgejo");
229
+
230
+ // src/tools.ts
231
+ function target(ctx) {
232
+ const binding = resolveWoodpeckerProjectBinding(ctx);
233
+ return { fullName: `${binding.owner}/${binding.repo}`, profile: binding.profile };
234
+ }
235
+ function registerWoodpeckerTools(api, integration) {
236
+ const schema = projectParameters();
237
+ api.tool({
238
+ name: "woodpecker_lookup_repository",
239
+ description: "Resolve the current process repository in Woodpecker",
240
+ parameters: schema,
241
+ async execute(ctx) {
242
+ const t = target(ctx);
243
+ return integration.client(t.profile).lookupRepository(t.fullName, ctx.signal);
244
+ }
245
+ });
246
+ api.tool({
247
+ name: "woodpecker_list_pipelines",
248
+ description: "List recent Woodpecker pipelines for the current process repository",
249
+ parameters: schema,
250
+ async execute(ctx) {
251
+ const t = target(ctx);
252
+ const client = integration.client(t.profile);
253
+ const repo = await client.lookupRepository(t.fullName, ctx.signal);
254
+ return client.listPipelines(repo.id, ctx.signal);
255
+ }
256
+ });
257
+ for (const name of ["woodpecker_get_pipeline", "woodpecker_restart_pipeline"]) {
258
+ api.tool({
259
+ name,
260
+ description: name.endsWith("restart_pipeline") ? "Restart a diagnosed Woodpecker pipeline" : "Read a Woodpecker pipeline",
261
+ parameters: projectParameters({
262
+ pipelineNumber: { type: "integer" },
263
+ ...name === "woodpecker_restart_pipeline" ? {
264
+ diagnosis: {
265
+ type: "string",
266
+ description: "Why this is an infrastructure or flaky failure rather than a repository defect"
267
+ },
268
+ logEvidence: {
269
+ type: "string",
270
+ description: "Concrete bounded-log evidence supporting a restart"
271
+ }
272
+ } : {}
273
+ }),
274
+ async execute(ctx, args) {
275
+ const t = target(ctx);
276
+ const client = integration.client(t.profile);
277
+ const repo = await client.lookupRepository(t.fullName, ctx.signal);
278
+ const number = numberArg(args, "pipelineNumber");
279
+ if (name === "woodpecker_get_pipeline")
280
+ return client.getPipeline(repo.id, number, ctx.signal);
281
+ const diagnosis = stringArg(args, "diagnosis");
282
+ const logEvidence = stringArg(args, "logEvidence");
283
+ await ctx.externalWrites.logOnly(
284
+ { writeType: "woodpecker.restart", dedupKey: ctx.idempotencyKey },
285
+ async () => {
286
+ await client.restartPipeline(repo.id, number, ctx.signal);
287
+ return { repoId: repo.id, number, diagnosis, logEvidence };
288
+ }
289
+ );
290
+ return { ok: true };
291
+ }
292
+ });
293
+ }
294
+ api.tool({
295
+ name: "woodpecker_get_step_logs",
296
+ description: "Read bounded logs for a Woodpecker pipeline step",
297
+ parameters: projectParameters(
298
+ {
299
+ pipelineNumber: { type: "integer" },
300
+ stepId: { type: "integer" },
301
+ tailLines: { type: "integer" },
302
+ maxBytes: { type: "integer" }
303
+ },
304
+ ["pipelineNumber", "stepId"]
305
+ ),
306
+ async execute(ctx, args) {
307
+ const t = target(ctx);
308
+ const client = integration.client(t.profile);
309
+ const repo = await client.lookupRepository(t.fullName, ctx.signal);
310
+ return client.getStepLogs(
311
+ repo.id,
312
+ numberArg(args, "pipelineNumber"),
313
+ numberArg(args, "stepId"),
314
+ typeof args.tailLines === "number" ? args.tailLines : 400,
315
+ typeof args.maxBytes === "number" ? args.maxBytes : 262144,
316
+ ctx.signal
317
+ );
318
+ }
319
+ });
320
+ }
321
+
322
+ // src/index.ts
323
+ var manifest = {
324
+ /** @internal */
325
+ id: "woodpecker",
326
+ /** @internal */
327
+ version: "0.1.9"
328
+ };
329
+ var extension = {
330
+ manifest,
331
+ setupServer(api, config) {
332
+ const profiles = parseWoodpeckerProfiles(config);
333
+ const integration = {
334
+ client(profile) {
335
+ const value = profiles.get(profile);
336
+ if (!value) throw new Error(`Unknown Woodpecker profile '${profile}'`);
337
+ return new WoodpeckerClient(value);
338
+ }
339
+ };
340
+ setupWoodpeckerIntegration(api, integration);
341
+ }
342
+ };
343
+ var index_default = extension;
344
+ function setupWoodpeckerIntegration(api, integration, options = {}) {
345
+ api.provide(woodpeckerIntegration, integration);
346
+ const deps = api.get(coreHostCapabilities.serverSetup);
347
+ if (!deps || Array.isArray(deps)) return;
348
+ registerWoodpeckerTools(api, integration);
349
+ return createWoodpeckerProvider(deps, integration, options);
350
+ }
351
+ export {
352
+ WOODPECKER_PIPELINE_KIND,
353
+ index_default as default,
354
+ resolveWoodpeckerProjectBinding,
355
+ setupWoodpeckerIntegration,
356
+ woodpeckerExternal,
357
+ woodpeckerIntegration
358
+ };
359
+ //# sourceMappingURL=index.js.map