@chatpanel/bridge 0.11.24 → 0.11.25
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 +7 -7
- package/package.json +1 -13
- package/scripts/sync-channels.mjs +8 -90
- package/scripts/sync-events.mjs +7 -78
- package/scripts/sync-pii.mjs +7 -68
- package/src/api-compat.js +5 -294
- package/src/channels/adapters/telegram.js +3 -298
- package/src/channels/bridge.js +1 -59
- package/src/channels/eventlog.js +3 -57
- package/src/channels/gateway.js +1 -114
- package/src/channels/invoke.js +1 -172
- package/src/channels/normalize.js +1 -58
- package/src/channels/pairing.js +1 -95
- package/src/channels/service.js +1 -329
- package/src/channels/stream.js +5 -104
- package/src/cli-errors.js +3 -136
- package/src/connections.js +1 -160
- package/src/connectors.js +1 -100
- package/src/engines/antigravity.js +5 -235
- package/src/engines/args.js +1 -47
- package/src/engines/claude.js +6 -586
- package/src/engines/cli-agents.js +7 -312
- package/src/engines/codex.js +6 -481
- package/src/engines/custom.js +17 -577
- package/src/engines/prompt.js +6 -32
- package/src/engines/stream-formats.js +2 -222
- package/src/entitlement.js +1 -77
- package/src/env.js +3 -628
- package/src/events/capability.js +1 -134
- package/src/events/event.js +1 -183
- package/src/events/reach.js +1 -31
- package/src/events/ref.js +1 -63
- package/src/events/scm-connection.js +1 -188
- package/src/events/scopes.js +1 -20
- package/src/events/skill-manifest.js +1 -338
- package/src/events/skill-scan.js +3 -217
- package/src/events/view.js +1 -96
- package/src/mcp-capabilities.js +2 -139
- package/src/mcp-local.js +0 -0
- package/src/mcp-quarantine.js +1 -110
- package/src/net.js +1 -107
- package/src/pii/index.js +1 -29
- package/src/pii/net.js +1 -111
- package/src/pii/pii-detect.js +2 -296
- package/src/pii/pii-redact.js +1 -470
- package/src/pii/pipeline.js +1 -137
- package/src/pii/sanitize.js +2 -179
- package/src/pii/tool-harness.js +1 -184
- package/src/pii/tool-rank.js +1 -110
- package/src/proc.js +2 -91
- package/src/relay-timeout.js +1 -21
- package/src/runs.js +1 -49
- package/src/sanitize.js +1 -7
- package/src/scm.js +1 -76
- package/src/server.js +10 -1492
- package/src/service.js +11 -176
- package/src/sign-in.js +1 -91
- package/src/skills.js +1 -399
- package/src/ssrf.js +1 -70
- package/src/update.js +1 -216
- package/src/workdir.js +1 -108
- package/src/worktree.js +3 -125
package/src/events/capability.js
CHANGED
|
@@ -1,134 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/capability.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// The capability signature — one call shape a rule, a schedule, the user or a model all
|
|
10
|
-
// invoke identically, through one policy path.
|
|
11
|
-
//
|
|
12
|
-
// `actor` is the field that makes capabilities turn-independent; it is the whole of the
|
|
13
|
-
// "capabilities are not turn-shaped" principle expressed as data rather than as a
|
|
14
|
-
// subsystem.
|
|
15
|
-
//
|
|
16
|
-
// `requirements` is what the router dispatches on: not "which model" but "what must be
|
|
17
|
-
// true". {maxLatencyMs:100, deterministic:true, egress:'none'} selects class R or M on a
|
|
18
|
-
// host that can realize it — or REFUSES. Silently exceeding a declared budget is the
|
|
19
|
-
// failure mode this exists to prevent.
|
|
20
|
-
|
|
21
|
-
import { CLASSES, EFFECTS, EGRESS, ACTOR_KINDS, SCOPE_KINDS, EventError } from './event.js';
|
|
22
|
-
import { DATA_SCOPES } from './scopes.js';
|
|
23
|
-
import { validateView } from './view.js';
|
|
24
|
-
|
|
25
|
-
export { DATA_SCOPES } from './scopes.js';
|
|
26
|
-
|
|
27
|
-
const str = (v) => typeof v === 'string' && v.length > 0;
|
|
28
|
-
const strs = (v, allowed = null) => Array.isArray(v) && v.every((x) => str(x) && (!allowed || allowed.includes(x)));
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Validate a capability DECLARATION — the static surface a reviewer, a user or an admin
|
|
32
|
-
* approves BEFORE the capability runs. Everything here is readable without executing
|
|
33
|
-
* anything, which is what makes load-time approval possible.
|
|
34
|
-
*/
|
|
35
|
-
export function validateCapability(c) {
|
|
36
|
-
if (!c || typeof c !== 'object') throw new EventError('SHAPE', 'capability must be an object');
|
|
37
|
-
if (!str(c.id)) throw new EventError('SHAPE', 'capability.id required');
|
|
38
|
-
if (!str(c.version)) throw new EventError('SHAPE', 'capability.version required');
|
|
39
|
-
if (!CLASSES.includes(c.class)) throw new EventError('SHAPE', `capability.class must be one of ${CLASSES}`);
|
|
40
|
-
if (!strs(c.requires)) throw new EventError('SHAPE', 'capability.requires must be string[]');
|
|
41
|
-
if (!strs(c.provides)) throw new EventError('SHAPE', 'capability.provides must be string[]');
|
|
42
|
-
if (!strs(c.reads, DATA_SCOPES)) throw new EventError('SHAPE', `capability.reads must be within ${DATA_SCOPES}`);
|
|
43
|
-
if (!strs(c.writes, DATA_SCOPES)) throw new EventError('SHAPE', `capability.writes must be within ${DATA_SCOPES}`);
|
|
44
|
-
if (!EGRESS.includes(c.egress)) throw new EventError('SHAPE', `capability.egress must be one of ${EGRESS}`);
|
|
45
|
-
if (!EFFECTS.includes(c.effects)) throw new EventError('SHAPE', `capability.effects must be one of ${EFFECTS}`);
|
|
46
|
-
if (typeof c.invoke !== 'function') throw new EventError('SHAPE', 'capability.invoke required');
|
|
47
|
-
if (typeof c.disclose !== 'function') throw new EventError('SHAPE', 'capability.disclose required');
|
|
48
|
-
if (!c.output || typeof c.output.render !== 'function') {
|
|
49
|
-
throw new EventError('SHAPE', 'capability.output.render required — canonical value and rendering are separate');
|
|
50
|
-
}
|
|
51
|
-
// A capability MAY ship its own UI. Optional, and validated against this capability so a
|
|
52
|
-
// view can never name a capability its owner isn't already allowed to call.
|
|
53
|
-
if (c.view != null) validateView(c.view, c);
|
|
54
|
-
// A class-R capability that declares egress is a contradiction: R is a determinism
|
|
55
|
-
// guarantee, and a network round-trip is not deterministic.
|
|
56
|
-
if (c.class === 'R' && c.egress !== 'none') {
|
|
57
|
-
throw new EventError('CONTRADICTION', 'class R must declare egress:none');
|
|
58
|
-
}
|
|
59
|
-
return c;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Validate an INVOCATION. Enforces the one rule that is easiest to forget and worst to
|
|
64
|
-
* miss: a capability that is not `pure` cannot be invoked without an idempotency key,
|
|
65
|
-
* because a retried delegated call would otherwise perform the side effect twice.
|
|
66
|
-
*/
|
|
67
|
-
export function validateInvocation(inv, capability) {
|
|
68
|
-
if (!inv || typeof inv !== 'object') throw new EventError('SHAPE', 'invocation must be an object');
|
|
69
|
-
if (!str(inv.capability)) throw new EventError('SHAPE', 'invocation.capability required');
|
|
70
|
-
if (!inv.actor || !ACTOR_KINDS.includes(inv.actor.kind) || !str(inv.actor.id)) {
|
|
71
|
-
throw new EventError('SHAPE', `invocation.actor.kind must be one of ${ACTOR_KINDS}`);
|
|
72
|
-
}
|
|
73
|
-
if (!inv.scope || !SCOPE_KINDS.includes(inv.scope.kind) || !str(inv.scope.id)) {
|
|
74
|
-
throw new EventError('SHAPE', `invocation.scope.kind must be one of ${SCOPE_KINDS}`);
|
|
75
|
-
}
|
|
76
|
-
if (!Array.isArray(inv.causes)) throw new EventError('SHAPE', 'invocation.causes must be string[]');
|
|
77
|
-
const effects = capability ? capability.effects : inv.effects;
|
|
78
|
-
if (effects && effects !== 'pure' && !str(inv.idempotencyKey)) {
|
|
79
|
-
throw new EventError('IDEMPOTENCY', `invocation of a '${effects}' capability requires an idempotencyKey`);
|
|
80
|
-
}
|
|
81
|
-
return inv;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Can this capability satisfy these requirements on this host?
|
|
86
|
-
* Returns { ok, reasons[] } — REFUSING is a valid, expected outcome.
|
|
87
|
-
*
|
|
88
|
-
* `host` supplies what it can actually realize: { realizes: {R:{maxMs},M:{maxMs},...} }.
|
|
89
|
-
* Class is intrinsic (a guarantee); latency is host-bound. Never fuse the two.
|
|
90
|
-
*/
|
|
91
|
-
export function canSatisfy(capability, requirements = {}, host = null) {
|
|
92
|
-
const reasons = [];
|
|
93
|
-
const { maxLatencyMs, deterministic, egress, maxCostUsd } = requirements;
|
|
94
|
-
|
|
95
|
-
if (deterministic === true && !['R', 'M'].includes(capability.class)) {
|
|
96
|
-
reasons.push(`class ${capability.class} is not deterministic`);
|
|
97
|
-
}
|
|
98
|
-
if (egress === 'none' && capability.egress !== 'none') {
|
|
99
|
-
reasons.push(`capability egresses '${capability.egress}', requirement is 'none'`);
|
|
100
|
-
}
|
|
101
|
-
if (egress === 'redacted' && capability.egress === 'delegated') {
|
|
102
|
-
reasons.push('delegated egress is not controlled, requirement is redacted');
|
|
103
|
-
}
|
|
104
|
-
if (maxLatencyMs != null && host) {
|
|
105
|
-
const realized = host.realizes && host.realizes[capability.class];
|
|
106
|
-
if (!realized) reasons.push(`host cannot realize class ${capability.class}`);
|
|
107
|
-
else if (realized.maxMs > maxLatencyMs) {
|
|
108
|
-
reasons.push(`host realizes class ${capability.class} at ~${realized.maxMs}ms, requirement is ${maxLatencyMs}ms`);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
if (maxCostUsd != null && capability.class === 'C' && maxCostUsd <= 0) {
|
|
112
|
-
reasons.push('cloud class requires a positive cost ceiling');
|
|
113
|
-
}
|
|
114
|
-
return { ok: reasons.length === 0, reasons };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* The model-facing projection — an ALLOWLIST built from exactly three fields.
|
|
119
|
-
*
|
|
120
|
-
* Never an omit-list. An omit-list leaks the next field someone adds; this cannot,
|
|
121
|
-
* because `invoke`, `effects`, `cost`, `writes` and `egress` are never copied.
|
|
122
|
-
*/
|
|
123
|
-
export function toModelSchema(capability) {
|
|
124
|
-
return {
|
|
125
|
-
name: capability.id,
|
|
126
|
-
description: capability.disclose().gist,
|
|
127
|
-
parameters: capability.input || { type: 'object', properties: {} },
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** The same allowlist over a toolset — the only supported way to build a model request. */
|
|
132
|
-
export function toModelSchemas(capabilities) {
|
|
133
|
-
return capabilities.map(toModelSchema);
|
|
134
|
-
}
|
|
1
|
+
import{CLASSES as d,EFFECTS as p,EGRESS as w,ACTOR_KINDS as m,SCOPE_KINDS as S,EventError as s}from"./event.js";import{DATA_SCOPES as n}from"./scopes.js";import{validateView as E}from"./view.js";import{DATA_SCOPES as v}from"./scopes.js";const o=e=>typeof e=="string"&&e.length>0,a=(e,r=null)=>Array.isArray(e)&&e.every(t=>o(t)&&(!r||r.includes(t)));function g(e){if(!e||typeof e!="object")throw new s("SHAPE","capability must be an object");if(!o(e.id))throw new s("SHAPE","capability.id required");if(!o(e.version))throw new s("SHAPE","capability.version required");if(!d.includes(e.class))throw new s("SHAPE",`capability.class must be one of ${d}`);if(!a(e.requires))throw new s("SHAPE","capability.requires must be string[]");if(!a(e.provides))throw new s("SHAPE","capability.provides must be string[]");if(!a(e.reads,n))throw new s("SHAPE",`capability.reads must be within ${n}`);if(!a(e.writes,n))throw new s("SHAPE",`capability.writes must be within ${n}`);if(!w.includes(e.egress))throw new s("SHAPE",`capability.egress must be one of ${w}`);if(!p.includes(e.effects))throw new s("SHAPE",`capability.effects must be one of ${p}`);if(typeof e.invoke!="function")throw new s("SHAPE","capability.invoke required");if(typeof e.disclose!="function")throw new s("SHAPE","capability.disclose required");if(!e.output||typeof e.output.render!="function")throw new s("SHAPE","capability.output.render required — canonical value and rendering are separate");if(e.view!=null&&E(e.view,e),e.class==="R"&&e.egress!=="none")throw new s("CONTRADICTION","class R must declare egress:none");return e}function H(e,r){if(!e||typeof e!="object")throw new s("SHAPE","invocation must be an object");if(!o(e.capability))throw new s("SHAPE","invocation.capability required");if(!e.actor||!m.includes(e.actor.kind)||!o(e.actor.id))throw new s("SHAPE",`invocation.actor.kind must be one of ${m}`);if(!e.scope||!S.includes(e.scope.kind)||!o(e.scope.id))throw new s("SHAPE",`invocation.scope.kind must be one of ${S}`);if(!Array.isArray(e.causes))throw new s("SHAPE","invocation.causes must be string[]");const t=r?r.effects:e.effects;if(t&&t!=="pure"&&!o(e.idempotencyKey))throw new s("IDEMPOTENCY",`invocation of a '${t}' capability requires an idempotencyKey`);return e}function $(e,r={},t=null){const i=[],{maxLatencyMs:c,deterministic:h,egress:f,maxCostUsd:l}=r;if(h===!0&&!["R","M"].includes(e.class)&&i.push(`class ${e.class} is not deterministic`),f==="none"&&e.egress!=="none"&&i.push(`capability egresses '${e.egress}', requirement is 'none'`),f==="redacted"&&e.egress==="delegated"&&i.push("delegated egress is not controlled, requirement is redacted"),c!=null&&t){const u=t.realizes&&t.realizes[e.class];u?u.maxMs>c&&i.push(`host realizes class ${e.class} at ~${u.maxMs}ms, requirement is ${c}ms`):i.push(`host cannot realize class ${e.class}`)}return l!=null&&e.class==="C"&&l<=0&&i.push("cloud class requires a positive cost ceiling"),{ok:i.length===0,reasons:i}}function A(e){return{name:e.id,description:e.disclose().gist,parameters:e.input||{type:"object",properties:{}}}}function q(e){return e.map(A)}export{v as DATA_SCOPES,$ as canSatisfy,A as toModelSchema,q as toModelSchemas,g as validateCapability,H as validateInvocation};
|
package/src/events/event.js
CHANGED
|
@@ -1,183 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/event.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// The event envelope — durable facts only.
|
|
10
|
-
//
|
|
11
|
-
// ORDER WITHOUT CLOCKS. `at` is wall time and is ADVISORY: it is shown to humans and
|
|
12
|
-
// never consulted for ordering. `(host, seq)` plus `causes` are the authority, because
|
|
13
|
-
// once two hosts append concurrently a timestamp is not an order (see order.js).
|
|
14
|
-
//
|
|
15
|
-
// EPHEMERAL STREAMS ARE NOT THIS TYPE. Market ticks, live captions and DOM mutations
|
|
16
|
-
// live in an in-memory ring buffer with no id, no seq and no persistence; only the
|
|
17
|
-
// windowed aggregate that entered a model request or crossed the device boundary is
|
|
18
|
-
// promoted to an Event. That is structural rather than a rule to remember: durably
|
|
19
|
-
// logging a caption stream is ~3 MB per meeting, ~5.5 GB/year, and there is no Event
|
|
20
|
-
// type that would accept one.
|
|
21
|
-
//
|
|
22
|
-
// METADATA ONLY. Payloads carry Refs and counts, never content. `privacy.redacted`
|
|
23
|
-
// carries how many of each entity type were redacted and never the values — a log of
|
|
24
|
-
// what was redacted must not itself contain the redacted data.
|
|
25
|
-
|
|
26
|
-
import { isRef } from './ref.js';
|
|
27
|
-
|
|
28
|
-
export const CURRENT_VERSION = 1;
|
|
29
|
-
|
|
30
|
-
/** The seven families of v1. Adding is cheap; removing is not. */
|
|
31
|
-
export const EVENT_TYPES = Object.freeze({
|
|
32
|
-
turn: ['started', 'ended'],
|
|
33
|
-
// What the model was SHOWN and what it SAID. Deliberately arriving as refs, not text —
|
|
34
|
-
// see the note on the validators below.
|
|
35
|
-
assistant: ['prompted', 'message', 'reasoning'],
|
|
36
|
-
context: ['assembled', 'attached', 'expanded'],
|
|
37
|
-
capability: ['offered', 'granted', 'denied', 'activated', 'revoked', 'invoked', 'resulted'],
|
|
38
|
-
privacy: ['redacted', 'egress'],
|
|
39
|
-
policy: ['changed', 'guard_denied'],
|
|
40
|
-
data: ['created', 'updated', 'deleted'],
|
|
41
|
-
automation: ['fired', 'suppressed'],
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
export const ALL_TYPES = Object.freeze(
|
|
45
|
-
Object.entries(EVENT_TYPES).flatMap(([fam, kinds]) => kinds.map((k) => `${fam}.${k}`)),
|
|
46
|
-
);
|
|
47
|
-
|
|
48
|
-
// 'channel' is a message arriving from a paired external surface — Telegram, WhatsApp — that
|
|
49
|
-
// drives a turn the same way a person pressing send does. It is turn-independent for the same
|
|
50
|
-
// reason 'schedule' and 'agent' are: nobody is sitting in the panel when it fires, so consent
|
|
51
|
-
// and reach have to be settled at pairing time, not at the keystroke. The actor.id carries the
|
|
52
|
-
// surface and the sender, e.g. 'telegram:8412…'. See chatpanel-channels for the invoker.
|
|
53
|
-
export const ACTOR_KINDS = Object.freeze(['user', 'rule', 'schedule', 'model', 'agent', 'channel']);
|
|
54
|
-
export const SCOPE_KINDS = Object.freeze(['global', 'site', 'tab', 'session', 'agent']);
|
|
55
|
-
export const CLASSES = Object.freeze(['R', 'M', 'L', 'C', 'A', 'X', 'H']);
|
|
56
|
-
export const EFFECTS = Object.freeze(['pure', 'idempotent', 'replay-safe', 'non-replayable']);
|
|
57
|
-
export const EGRESS = Object.freeze(['none', 'redacted', 'delegated']);
|
|
58
|
-
|
|
59
|
-
export class EventError extends Error {
|
|
60
|
-
constructor(code, message, detail = null) {
|
|
61
|
-
super(message);
|
|
62
|
-
this.name = 'EventError';
|
|
63
|
-
this.code = code;
|
|
64
|
-
this.detail = detail;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const str = (v) => typeof v === 'string' && v.length > 0;
|
|
69
|
-
const num = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
70
|
-
const arr = (v) => Array.isArray(v);
|
|
71
|
-
|
|
72
|
-
function actorOk(a) { return !!a && ACTOR_KINDS.includes(a.kind) && str(a.id); }
|
|
73
|
-
function scopeOk(s) { return !!s && SCOPE_KINDS.includes(s.kind) && str(s.id); }
|
|
74
|
-
|
|
75
|
-
// Per-type payload requirements. Deliberately light — enough that a malformed event
|
|
76
|
-
// cannot enter an append-only log, not a full schema language.
|
|
77
|
-
const PAYLOAD = {
|
|
78
|
-
'turn.started': (p) => str(p.turnId),
|
|
79
|
-
'turn.ended': (p) => str(p.turnId),
|
|
80
|
-
|
|
81
|
-
// ── assistant ─────────────────────────────────────────────────────────────
|
|
82
|
-
// "Model-visible means logged" was true of the toolset and false of the conversation:
|
|
83
|
-
// the log could say a turn happened and what it cost, but never what was asked or
|
|
84
|
-
// answered. That is the half a trajectory view needs, and the half replay cannot be
|
|
85
|
-
// checked without.
|
|
86
|
-
//
|
|
87
|
-
// CONTENT IS NEVER IN THE EVENT. Each of these carries a Ref — a content hash — and the
|
|
88
|
-
// bytes live in the blob store. Three reasons, in order of how much they matter:
|
|
89
|
-
// 1. The log stays metadata, so exporting or replicating it does not export the user's
|
|
90
|
-
// conversations by accident. That property is the whole reason an event log is safe
|
|
91
|
-
// to keep at all.
|
|
92
|
-
// 2. Deletion stays honest: an append-only log cannot unsay a message, but a blob can
|
|
93
|
-
// be crypto-shredded and the ref then resolves to verified-but-unavailable. Inlined
|
|
94
|
-
// text would make "delete my data" a lie the schema enforces forever.
|
|
95
|
-
// 3. Repeated content (the same system prompt on every turn) is stored once.
|
|
96
|
-
'assistant.prompted': (p) => str(p.turnId) && isRef(p.ref),
|
|
97
|
-
'assistant.message': (p) => str(p.turnId) && isRef(p.ref),
|
|
98
|
-
'assistant.reasoning': (p) => str(p.turnId) && isRef(p.ref),
|
|
99
|
-
|
|
100
|
-
'context.assembled': (p) => num(p.budget) && num(p.used) && !!p.parts && typeof p.parts === 'object'
|
|
101
|
-
&& arr(p.resident) && p.resident.every(isRef) && num(p.reachableCount),
|
|
102
|
-
'context.attached': (p) => isRef(p.ref),
|
|
103
|
-
'context.expanded': (p) => isRef(p.ref) && num(p.tokens),
|
|
104
|
-
|
|
105
|
-
'capability.offered': (p) => str(p.capability) && str(p.reason),
|
|
106
|
-
'capability.granted': (p) => str(p.capability) && actorOk(p.actor),
|
|
107
|
-
'capability.denied': (p) => str(p.capability) && actorOk(p.actor),
|
|
108
|
-
'capability.activated': (p) => str(p.capability) && CLASSES.includes(p.classUsed),
|
|
109
|
-
'capability.revoked': (p) => str(p.capability) && str(p.cause),
|
|
110
|
-
// I3 is enforced here structurally: a non-pure invocation without a key is not a
|
|
111
|
-
// valid event, so it cannot reach the log at all.
|
|
112
|
-
'capability.invoked': (p) => str(p.capability) && actorOk(p.actor) && scopeOk(p.scope)
|
|
113
|
-
&& EFFECTS.includes(p.effects) && (p.effects === 'pure' || str(p.idempotencyKey)),
|
|
114
|
-
'capability.resulted': (p) => str(p.capability) && typeof p.ok === 'boolean'
|
|
115
|
-
&& CLASSES.includes(p.classUsed) && !!p.cost && num(p.cost.ms),
|
|
116
|
-
|
|
117
|
-
// counts only — never values
|
|
118
|
-
'privacy.redacted': (p) => !!p.counts && typeof p.counts === 'object'
|
|
119
|
-
&& Object.values(p.counts).every(num),
|
|
120
|
-
'privacy.egress': (p) => str(p.host) && typeof p.redacted === 'boolean'
|
|
121
|
-
&& typeof p.controlled === 'boolean',
|
|
122
|
-
|
|
123
|
-
'policy.changed': (p) => str(p.dial) && actorOk(p.actor) && 'from' in p && 'to' in p,
|
|
124
|
-
'policy.guard_denied': (p) => str(p.capability) && str(p.reason),
|
|
125
|
-
|
|
126
|
-
'data.created': (p) => isRef(p.ref),
|
|
127
|
-
'data.updated': (p) => isRef(p.ref),
|
|
128
|
-
'data.deleted': (p) => isRef(p.ref) && typeof p.shredded === 'boolean',
|
|
129
|
-
|
|
130
|
-
'automation.fired': (p) => str(p.ruleId) && CLASSES.includes(p.classUsed),
|
|
131
|
-
'automation.suppressed': (p) => str(p.ruleId) && str(p.reason),
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
/** Validate a durable event. Throws EventError; never mutates. */
|
|
135
|
-
export function validateEvent(e) {
|
|
136
|
-
if (!e || typeof e !== 'object') throw new EventError('SHAPE', 'event must be an object');
|
|
137
|
-
if (e.v !== CURRENT_VERSION) throw new EventError('VERSION', `expected v=${CURRENT_VERSION}, got ${e.v} — upcast first`, e.v);
|
|
138
|
-
if (!str(e.id)) throw new EventError('SHAPE', 'id required');
|
|
139
|
-
if (!str(e.host)) throw new EventError('SHAPE', 'host required');
|
|
140
|
-
if (!Number.isInteger(e.seq) || e.seq < 0) throw new EventError('SHAPE', 'seq must be a non-negative integer');
|
|
141
|
-
if (!arr(e.causes) || !e.causes.every(str)) throw new EventError('SHAPE', 'causes must be string[]');
|
|
142
|
-
if (!num(e.at)) throw new EventError('SHAPE', 'at required (advisory wall clock)');
|
|
143
|
-
if (!ALL_TYPES.includes(e.type)) throw new EventError('TYPE', `unknown type ${e.type}`, e.type);
|
|
144
|
-
if (!e.payload || typeof e.payload !== 'object') throw new EventError('SHAPE', 'payload required');
|
|
145
|
-
const check = PAYLOAD[e.type];
|
|
146
|
-
if (check && !check(e.payload)) throw new EventError('PAYLOAD', `payload invalid for ${e.type}`, e.type);
|
|
147
|
-
return e;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
export function isValidEvent(e) {
|
|
151
|
-
try { validateEvent(e); return true; } catch { return false; }
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* A per-host append cursor. Owns `seq` — the only monotonic thing in the system — so
|
|
156
|
-
* callers cannot skip or reuse one.
|
|
157
|
-
*
|
|
158
|
-
* `now` and `newId` are injected so tests are deterministic and so the package holds no
|
|
159
|
-
* ambient dependency on a clock or a crypto implementation.
|
|
160
|
-
*/
|
|
161
|
-
export function createAppender({ host, seq = 0, now = () => Date.now(), newId }) {
|
|
162
|
-
if (!str(host)) throw new EventError('SHAPE', 'host required');
|
|
163
|
-
const genId = newId || (() => globalThis.crypto.randomUUID());
|
|
164
|
-
let n = seq;
|
|
165
|
-
return {
|
|
166
|
-
get host() { return host; },
|
|
167
|
-
get seq() { return n; },
|
|
168
|
-
/** Build + validate the next event for this host. Does not persist — the caller stores it. */
|
|
169
|
-
append(type, payload, causes = []) {
|
|
170
|
-
const e = Object.freeze({
|
|
171
|
-
v: CURRENT_VERSION,
|
|
172
|
-
id: genId(),
|
|
173
|
-
host,
|
|
174
|
-
seq: n++,
|
|
175
|
-
causes: Object.freeze([...causes]),
|
|
176
|
-
at: now(),
|
|
177
|
-
type,
|
|
178
|
-
payload,
|
|
179
|
-
});
|
|
180
|
-
return validateEvent(e);
|
|
181
|
-
},
|
|
182
|
-
};
|
|
183
|
-
}
|
|
1
|
+
import{isRef as a}from"./ref.js";const c=1,m=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"]}),v=Object.freeze(Object.entries(m).flatMap(([e,n])=>n.map(s=>`${e}.${s}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),S=Object.freeze(["global","site","tab","session","agent"]),l=Object.freeze(["R","M","L","C","A","X","H"]),x=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),I=Object.freeze(["none","redacted","delegated"]);class r extends Error{constructor(n,s,i=null){super(s),this.name="EventError",this.code=n,this.detail=i}}const t=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),f=e=>Array.isArray(e);function d(e){return!!e&&w.includes(e.kind)&&t(e.id)}function A(e){return!!e&&S.includes(e.kind)&&t(e.id)}const O={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&a(e.ref),"assistant.message":e=>t(e.turnId)&&a(e.ref),"assistant.reasoning":e=>t(e.turnId)&&a(e.ref),"context.assembled":e=>o(e.budget)&&o(e.used)&&!!e.parts&&typeof e.parts=="object"&&f(e.resident)&&e.resident.every(a)&&o(e.reachableCount),"context.attached":e=>a(e.ref),"context.expanded":e=>a(e.ref)&&o(e.tokens),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&d(e.actor),"capability.denied":e=>t(e.capability)&&d(e.actor),"capability.activated":e=>t(e.capability)&&l.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&d(e.actor)&&A(e.scope)&&x.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&l.includes(e.classUsed)&&!!e.cost&&o(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(o),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&d(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>a(e.ref),"data.updated":e=>a(e.ref),"data.deleted":e=>a(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&l.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason)};function y(e){if(!e||typeof e!="object")throw new r("SHAPE","event must be an object");if(e.v!==c)throw new r("VERSION",`expected v=${c}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new r("SHAPE","id required");if(!t(e.host))throw new r("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new r("SHAPE","seq must be a non-negative integer");if(!f(e.causes)||!e.causes.every(t))throw new r("SHAPE","causes must be string[]");if(!o(e.at))throw new r("SHAPE","at required (advisory wall clock)");if(!v.includes(e.type))throw new r("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new r("SHAPE","payload required");const n=O[e.type];if(n&&!n(e.payload))throw new r("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function P(e){try{return y(e),!0}catch{return!1}}function k({host:e,seq:n=0,now:s=()=>Date.now(),newId:i}){if(!t(e))throw new r("SHAPE","host required");const p=i||(()=>globalThis.crypto.randomUUID());let u=n;return{get host(){return e},get seq(){return u},append(b,h,E=[]){const g=Object.freeze({v:c,id:p(),host:e,seq:u++,causes:Object.freeze([...E]),at:s(),type:b,payload:h});return y(g)}}}export{w as ACTOR_KINDS,v as ALL_TYPES,l as CLASSES,c as CURRENT_VERSION,x as EFFECTS,I as EGRESS,m as EVENT_TYPES,r as EventError,S as SCOPE_KINDS,k as createAppender,P as isValidEvent,y as validateEvent};
|
package/src/events/reach.js
CHANGED
|
@@ -1,31 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/reach.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// reach.js — how far a request may travel, on its own so it can travel alone.
|
|
10
|
-
//
|
|
11
|
-
// One ordered vocabulary answers "how far may this go" for three very different callers: the
|
|
12
|
-
// model router ranks a model's reach against a turn's requirement, pairing gives a phone a
|
|
13
|
-
// ceiling, and the bridge maps that ceiling to a toolset. Three declarations, one vocabulary,
|
|
14
|
-
// or "how far may this reach" gets three answers that drift.
|
|
15
|
-
//
|
|
16
|
-
// A separate module rather than a constant inside router.js for the reason scopes.js exists:
|
|
17
|
-
// the consumers have wildly different weights. The bridge has zero runtime dependencies by
|
|
18
|
-
// design and vendors what it needs — pulling the 50 KB model router in to reach a
|
|
19
|
-
// three-element array is exactly the transitive-graph mistake that split DATA_SCOPES out of
|
|
20
|
-
// capability.js.
|
|
21
|
-
//
|
|
22
|
-
// ORDERED, least to most: a ceiling comparison is an index comparison.
|
|
23
|
-
export const REACH = Object.freeze(['device', 'trusted', 'any']);
|
|
24
|
-
|
|
25
|
-
/** Position in the ladder; an unknown tier ranks LOWEST, so a typo never widens reach. */
|
|
26
|
-
export const reachRank = (r) => Math.max(0, REACH.indexOf(r));
|
|
27
|
-
|
|
28
|
-
/** Does `have` satisfy `need`? Fails closed — an unknown `have` is treated as 'device'. */
|
|
29
|
-
export function reachSatisfies(have, need) {
|
|
30
|
-
return reachRank(have) >= reachRank(need);
|
|
31
|
-
}
|
|
1
|
+
const n=Object.freeze(["device","trusted","any"]),t=e=>Math.max(0,n.indexOf(e));function a(e,r){return t(e)>=t(r)}export{n as REACH,t as reachRank,a as reachSatisfies};
|
package/src/events/ref.js
CHANGED
|
@@ -1,63 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/ref.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// References — how the log addresses content WITHOUT copying it.
|
|
10
|
-
//
|
|
11
|
-
// An event records "note n_88, lines 10-40, hash H" and never the text. Content that
|
|
12
|
-
// actually entered a model request is written once into a content-addressed blob store
|
|
13
|
-
// keyed by hash, so the same excerpt across a hundred turns costs one copy.
|
|
14
|
-
//
|
|
15
|
-
// Replay resolves a Ref by hash: match => exact reconstruction; blob absent or
|
|
16
|
-
// crypto-shredded => VERIFIED_BUT_UNAVAILABLE. It never silently substitutes today's
|
|
17
|
-
// version of the note, because that would make replay quietly wrong instead of loudly
|
|
18
|
-
// incomplete.
|
|
19
|
-
|
|
20
|
-
// `memory` and `brief` joined when the derived layer landed: a brief's claim cites the
|
|
21
|
-
// record it came from, and a claim the USER stated cites the memory they stated it in.
|
|
22
|
-
// Additive — no existing ref changes meaning.
|
|
23
|
-
export const REF_KINDS = Object.freeze(['note', 'meeting', 'chat', 'page', 'result', 'blob', 'memory', 'brief']);
|
|
24
|
-
|
|
25
|
-
export const RESOLUTION = Object.freeze({
|
|
26
|
-
EXACT: 'exact', // blob present, hash matches
|
|
27
|
-
UNAVAILABLE: 'verified-but-unavailable', // we know what it was; we no longer hold it
|
|
28
|
-
DRIFTED: 'drifted', // source still exists but its hash changed
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
/** Build a Ref. `hash` is the content hash AT CAPTURE TIME — that is the whole point. */
|
|
32
|
-
export function makeRef({ kind, id, hash, range = null, stored = false }) {
|
|
33
|
-
if (!REF_KINDS.includes(kind)) throw new TypeError(`ref: unknown kind ${kind}`);
|
|
34
|
-
if (typeof id !== 'string' || !id) throw new TypeError('ref: id required');
|
|
35
|
-
if (typeof hash !== 'string' || !hash) throw new TypeError('ref: hash required');
|
|
36
|
-
const ref = { kind, id, hash };
|
|
37
|
-
if (range) {
|
|
38
|
-
if (!Number.isInteger(range.from) || !Number.isInteger(range.to) || range.to < range.from) {
|
|
39
|
-
throw new TypeError('ref: range must be {from,to} integers with to >= from');
|
|
40
|
-
}
|
|
41
|
-
ref.range = { from: range.from, to: range.to };
|
|
42
|
-
}
|
|
43
|
-
if (stored) ref.stored = true;
|
|
44
|
-
return Object.freeze(ref);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function isRef(v) {
|
|
48
|
-
return !!v && typeof v === 'object'
|
|
49
|
-
&& REF_KINDS.includes(v.kind)
|
|
50
|
-
&& typeof v.id === 'string' && v.id.length > 0
|
|
51
|
-
&& typeof v.hash === 'string' && v.hash.length > 0;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Classify what a replay can say about a Ref, given what the blob store holds now.
|
|
56
|
-
* `lookup(ref) -> { hash } | null`. Pure: the caller owns the store.
|
|
57
|
-
*/
|
|
58
|
-
export function resolveRef(ref, lookup) {
|
|
59
|
-
const got = lookup(ref);
|
|
60
|
-
if (!got) return { resolution: RESOLUTION.UNAVAILABLE, ref };
|
|
61
|
-
if (got.hash !== ref.hash) return { resolution: RESOLUTION.DRIFTED, ref, actualHash: got.hash };
|
|
62
|
-
return { resolution: RESOLUTION.EXACT, ref, value: got.value };
|
|
63
|
-
}
|
|
1
|
+
const f=Object.freeze(["note","meeting","chat","page","result","blob","memory","brief"]),i=Object.freeze({EXACT:"exact",UNAVAILABLE:"verified-but-unavailable",DRIFTED:"drifted"});function u({kind:e,id:o,hash:r,range:t=null,stored:s=!1}){if(!f.includes(e))throw new TypeError(`ref: unknown kind ${e}`);if(typeof o!="string"||!o)throw new TypeError("ref: id required");if(typeof r!="string"||!r)throw new TypeError("ref: hash required");const n={kind:e,id:o,hash:r};if(t){if(!Number.isInteger(t.from)||!Number.isInteger(t.to)||t.to<t.from)throw new TypeError("ref: range must be {from,to} integers with to >= from");n.range={from:t.from,to:t.to}}return s&&(n.stored=!0),Object.freeze(n)}function l(e){return!!e&&typeof e=="object"&&f.includes(e.kind)&&typeof e.id=="string"&&e.id.length>0&&typeof e.hash=="string"&&e.hash.length>0}function h(e,o){const r=o(e);return r?r.hash!==e.hash?{resolution:i.DRIFTED,ref:e,actualHash:r.hash}:{resolution:i.EXACT,ref:e,value:r.value}:{resolution:i.UNAVAILABLE,ref:e}}export{f as REF_KINDS,i as RESOLUTION,l as isRef,u as makeRef,h as resolveRef};
|
|
@@ -1,188 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/scm-connection.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// An SCM CONNECTION — how a harness engine reaches the organisation's source-control hub —
|
|
10
|
-
// and the two names a job gets in it: its branch and its worktree directory.
|
|
11
|
-
// (architecture-pillars.md §14: the repository is the source of truth.)
|
|
12
|
-
//
|
|
13
|
-
// ChatPanel is not a git host and not a git client. The harness runs `git`, `gh`, `glab`;
|
|
14
|
-
// ChatPanel brings the CREDENTIAL, the WORKTREE, the BRANCH NAME and the RECORD. This module
|
|
15
|
-
// is the pure part: what a connection record holds, how a remote URL maps to one, what a
|
|
16
|
-
// job's branch is called, and the environment that hands a token to git for ONE process
|
|
17
|
-
// without writing it anywhere.
|
|
18
|
-
//
|
|
19
|
-
// THE TOKEN IS NEVER IN THE RECORD. A connection stores a `secretRef` — the name under which
|
|
20
|
-
// the machine's keychain (or the bridge's secret store) holds the token. The record travels
|
|
21
|
-
// with the client-prefs document (`connections` section) so both clients show the same
|
|
22
|
-
// connections; the secret does not travel, and `normalizeConnection` REFUSES a record that
|
|
23
|
-
// carries one, so a settings export, a sync, or a prompt can never carry it either.
|
|
24
|
-
|
|
25
|
-
export const SCM_KINDS = Object.freeze(['github', 'github-enterprise', 'gitlab', 'bitbucket', 'gitea', 'azure-devops', 'git']);
|
|
26
|
-
export const CONNECTION_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
|
|
27
|
-
export const SECRET_REF_RE = /^[a-zA-Z0-9_.:@/-]{1,200}$/;
|
|
28
|
-
const SECRET_FIELDS = ['token', 'password', 'secret', 'pat', 'apiKey', 'key'];
|
|
29
|
-
const DEFAULT_HOST = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org', 'azure-devops': 'dev.azure.com' };
|
|
30
|
-
|
|
31
|
-
export class ScmError extends Error {
|
|
32
|
-
constructor(code, message) { super(message); this.name = 'ScmError'; this.code = code; }
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
36
|
-
|
|
37
|
-
/** The host a connection serves: its baseUrl's, or the kind's public host. */
|
|
38
|
-
export function hostOf(conn) {
|
|
39
|
-
const url = String(conn?.baseUrl || '').trim();
|
|
40
|
-
if (url) { try { return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.toLowerCase(); } catch { return url.toLowerCase().replace(/^https?:\/\//, '').split('/')[0]; } }
|
|
41
|
-
return DEFAULT_HOST[conn?.kind] || '';
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function validateConnection(conn) {
|
|
45
|
-
const errors = [];
|
|
46
|
-
if (!isRecord(conn)) return { ok: false, errors: ['connection must be an object'] };
|
|
47
|
-
if (!CONNECTION_ID_RE.test(String(conn.id || ''))) errors.push('id: a short identifier (letters, digits, _ -)');
|
|
48
|
-
if (!SCM_KINDS.includes(conn.kind)) errors.push(`kind: one of ${SCM_KINDS.join(', ')}`);
|
|
49
|
-
const needsHost = ['github-enterprise', 'gitea', 'git'].includes(conn.kind);
|
|
50
|
-
if (needsHost && !String(conn.baseUrl || '').trim()) errors.push('baseUrl: the hub\'s URL');
|
|
51
|
-
if (conn.baseUrl && !/^(https?:\/\/)?[a-z0-9.-]+(:\d+)?(\/[^\s]*)?$/i.test(String(conn.baseUrl).trim())) errors.push('baseUrl: a host or URL');
|
|
52
|
-
const leaked = SECRET_FIELDS.filter((k) => conn[k] !== undefined && conn[k] !== null && conn[k] !== '');
|
|
53
|
-
if (leaked.length) errors.push(`${leaked.join(', ')}: a connection never stores a secret — store it in the keychain and reference it by secretRef`);
|
|
54
|
-
if (conn.secretRef !== undefined && conn.secretRef !== null && conn.secretRef !== '' && !SECRET_REF_RE.test(String(conn.secretRef))) errors.push('secretRef: a keychain / secret-store name');
|
|
55
|
-
if (conn.reach !== undefined && !Array.isArray(conn.reach)) errors.push('reach: a list of remotes or owners this connection may be used for');
|
|
56
|
-
return { ok: errors.length === 0, errors };
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** The stored form. Throws on a record that carries a secret. */
|
|
60
|
-
export function normalizeConnection(conn) {
|
|
61
|
-
const v = validateConnection(conn);
|
|
62
|
-
if (!v.ok) throw new ScmError('INVALID', v.errors.join('; '));
|
|
63
|
-
const id = String(conn.id);
|
|
64
|
-
return {
|
|
65
|
-
id,
|
|
66
|
-
kind: conn.kind,
|
|
67
|
-
label: String(conn.label || conn.name || '').trim().slice(0, 80) || `${conn.kind} · ${hostOf(conn) || id}`,
|
|
68
|
-
...(conn.baseUrl ? { baseUrl: String(conn.baseUrl).trim().replace(/\/+$/, '') } : {}),
|
|
69
|
-
// The secret's NAME — `chatpanel:scm:<id>` by default — under which the keychain holds it.
|
|
70
|
-
secretRef: String(conn.secretRef || '').trim() || `chatpanel:scm:${id}`,
|
|
71
|
-
...(conn.username ? { username: String(conn.username).trim().slice(0, 80) } : {}),
|
|
72
|
-
// Which remotes it may be used for: `owner/*`, `owner/name`, or a host. Empty = any on its host.
|
|
73
|
-
reach: (Array.isArray(conn.reach) ? conn.reach : []).map((r) => String(r).trim().toLowerCase()).filter(Boolean).slice(0, 64),
|
|
74
|
-
enabled: conn.enabled !== false,
|
|
75
|
-
...(conn.createdAt ? { createdAt: conn.createdAt } : {}),
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* A remote URL, read: `{ host, owner, name, protocol }` for https, ssh (`git@host:o/n.git`,
|
|
81
|
-
* `ssh://git@host/o/n`) and plain `host/o/n`. Credentials in the URL are dropped, never
|
|
82
|
-
* returned. Null for what cannot be read.
|
|
83
|
-
*/
|
|
84
|
-
export function parseRemote(url) {
|
|
85
|
-
const s = String(url || '').trim();
|
|
86
|
-
if (!s) return null;
|
|
87
|
-
let m = /^(?:ssh:\/\/)?(?:[\w.-]+@)?([a-z0-9.-]+)(?::\d+)?[:/]+([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(s.replace(/^https?:\/\/(?:[^@/]+@)?/i, ''));
|
|
88
|
-
if (m && !/^https?:/i.test(s)) return { host: m[1].toLowerCase(), owner: m[2], name: m[3], protocol: /^ssh:|^[\w.-]+@/.test(s) ? 'ssh' : 'plain' };
|
|
89
|
-
try {
|
|
90
|
-
const u = new URL(s);
|
|
91
|
-
const parts = u.pathname.replace(/\.git$/, '').split('/').filter(Boolean);
|
|
92
|
-
if (parts.length < 2) return null;
|
|
93
|
-
// Azure DevOps: /org/project/_git/repo; GitLab subgroups: /a/b/c/repo — owner is all but the last.
|
|
94
|
-
const name = parts.at(-1);
|
|
95
|
-
const owner = parts.slice(0, -1).filter((p) => p !== '_git').join('/');
|
|
96
|
-
return { host: u.host.toLowerCase(), owner, name, protocol: u.protocol.replace(':', '') };
|
|
97
|
-
} catch { return null; }
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* The connection to use for a remote: enabled, same host, and — when the connection lists
|
|
102
|
-
* a reach — the remote's `owner/name` or `owner/*` in it. The most specific reach wins.
|
|
103
|
-
*/
|
|
104
|
-
export function connectionFor(remote, connections = []) {
|
|
105
|
-
const r = typeof remote === 'string' ? parseRemote(remote) : remote;
|
|
106
|
-
if (!r) return null;
|
|
107
|
-
const slug = `${r.owner}/${r.name}`.toLowerCase();
|
|
108
|
-
let best = null; let bestScore = -1;
|
|
109
|
-
for (const c of connections || []) {
|
|
110
|
-
if (!c || c.enabled === false) continue;
|
|
111
|
-
if (hostOf(c) !== r.host) continue;
|
|
112
|
-
const reach = Array.isArray(c.reach) ? c.reach : [];
|
|
113
|
-
let score = reach.length ? -1 : 0;
|
|
114
|
-
for (const x of reach) {
|
|
115
|
-
if (x === slug) score = Math.max(score, 3);
|
|
116
|
-
else if (x.endsWith('/*') && slug.startsWith(x.slice(0, -1))) score = Math.max(score, 2);
|
|
117
|
-
else if (x === r.host) score = Math.max(score, 1);
|
|
118
|
-
}
|
|
119
|
-
if (score > bestScore) { best = c; bestScore = score; }
|
|
120
|
-
}
|
|
121
|
-
return best;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const slug = (s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 48) || 'x';
|
|
125
|
-
|
|
126
|
-
/** A job's branch: `cp/<project>/<job>` — one branch per job, always under `cp/`, never a protected name. */
|
|
127
|
-
export function branchFor(projectId, jobId) { return `cp/${slug(projectId)}/${slug(jobId)}`; }
|
|
128
|
-
|
|
129
|
-
/** A job's worktree directory under the bridge's worktree root: `<project>/<job>`. */
|
|
130
|
-
export function worktreeDirFor(projectId, jobId) { return `${slug(projectId)}/${slug(jobId)}`; }
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* The environment that hands ONE process the token, scoped to the connection's host:
|
|
134
|
-
* git's `credential.<url>.helper` set through `GIT_CONFIG_*` (never a file, never the
|
|
135
|
-
* command line), a helper that reads the token from the environment, terminal prompts
|
|
136
|
-
* off, and the hub CLIs' own variables (`GH_TOKEN` / `GH_HOST`, `GITLAB_TOKEN`) so `gh` and
|
|
137
|
-
* `glab` work in the same process. The caller spawns with `{ ...process.env, ...env }` and
|
|
138
|
-
* the token dies with the process.
|
|
139
|
-
*/
|
|
140
|
-
export function credentialEnv(conn, token, { username = null } = {}) {
|
|
141
|
-
const c = conn || {};
|
|
142
|
-
const host = hostOf(c);
|
|
143
|
-
if (!host || !token) return {};
|
|
144
|
-
const user = username || c.username || ({ github: 'x-access-token', 'github-enterprise': 'x-access-token', gitlab: 'oauth2', bitbucket: 'x-token-auth', gitea: 'oauth2', 'azure-devops': 'pat' }[c.kind] || 'token');
|
|
145
|
-
const env = {
|
|
146
|
-
GIT_TERMINAL_PROMPT: '0',
|
|
147
|
-
GIT_CONFIG_COUNT: '2',
|
|
148
|
-
GIT_CONFIG_KEY_0: `credential.https://${host}.helper`,
|
|
149
|
-
// A shell helper: on `get`, answer from the environment. Nothing is written anywhere.
|
|
150
|
-
GIT_CONFIG_VALUE_0: '!f() { if [ "$1" = get ]; then printf "username=%s\\npassword=%s\\n" "$CHATPANEL_SCM_USER" "$CHATPANEL_SCM_TOKEN"; fi; }; f',
|
|
151
|
-
GIT_CONFIG_KEY_1: `credential.https://${host}.useHttpPath`,
|
|
152
|
-
GIT_CONFIG_VALUE_1: 'false',
|
|
153
|
-
CHATPANEL_SCM_USER: user,
|
|
154
|
-
CHATPANEL_SCM_TOKEN: String(token),
|
|
155
|
-
};
|
|
156
|
-
if (c.kind === 'github' || c.kind === 'github-enterprise') {
|
|
157
|
-
env.GH_TOKEN = String(token);
|
|
158
|
-
if (c.kind === 'github-enterprise') { env.GH_ENTERPRISE_TOKEN = String(token); env.GH_HOST = host; }
|
|
159
|
-
}
|
|
160
|
-
if (c.kind === 'gitlab') { env.GITLAB_TOKEN = String(token); env.GITLAB_HOST = host; }
|
|
161
|
-
return env;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/** One line a person reads: "GitHub · github.com · acme/*". */
|
|
165
|
-
export function describeConnection(conn) {
|
|
166
|
-
const c = conn || {};
|
|
167
|
-
const kindLabel = { github: 'GitHub', 'github-enterprise': 'GitHub Enterprise', gitlab: 'GitLab', bitbucket: 'Bitbucket', gitea: 'Gitea', 'azure-devops': 'Azure DevOps', git: 'Git' }[c.kind] || c.kind;
|
|
168
|
-
return `${kindLabel} · ${hostOf(c)}${c.reach?.length ? ` · ${c.reach.join(', ')}` : ''}${c.enabled === false ? ' (off)' : ''}`;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export function blankConnection() { return { id: '', kind: 'github', label: '', baseUrl: '', reach: [], username: '' }; }
|
|
172
|
-
|
|
173
|
-
/** The editor's form → a connection, or the errors. The token is NOT part of the form's record: the host stores it separately. */
|
|
174
|
-
export function connectionFromForm(form) {
|
|
175
|
-
const f = form || {};
|
|
176
|
-
const id = String(f.id || '').trim() || slug(f.label || `${f.kind}-${hostOf(f)}`);
|
|
177
|
-
const conn = {
|
|
178
|
-
id, kind: f.kind || 'github', label: String(f.label || '').trim(),
|
|
179
|
-
...(f.baseUrl ? { baseUrl: String(f.baseUrl).trim() } : {}),
|
|
180
|
-
...(f.username ? { username: String(f.username).trim() } : {}),
|
|
181
|
-
...(f.secretRef ? { secretRef: String(f.secretRef).trim() } : {}),
|
|
182
|
-
reach: String(Array.isArray(f.reach) ? f.reach.join(',') : f.reach || '').split(/[,\s]+/).map((x) => x.trim()).filter(Boolean),
|
|
183
|
-
enabled: f.enabled !== false,
|
|
184
|
-
...(f.createdAt ? { createdAt: f.createdAt } : {}),
|
|
185
|
-
};
|
|
186
|
-
const v = validateConnection(conn);
|
|
187
|
-
return v.ok ? { ok: true, connection: normalizeConnection(conn) } : { ok: false, errors: v.errors };
|
|
188
|
-
}
|
|
1
|
+
const f=Object.freeze(["github","github-enterprise","gitlab","bitbucket","gitea","azure-devops","git"]),b=/^[a-z][a-z0-9_-]{0,63}$/i,d=/^[a-zA-Z0-9_.:@/-]{1,200}$/,g=["token","password","secret","pat","apiKey","key"],m={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org","azure-devops":"dev.azure.com"};class _ extends Error{constructor(e,i){super(i),this.name="ScmError",this.code=e}}const S=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function c(t){const e=String(t?.baseUrl||"").trim();if(e)try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).host.toLowerCase()}catch{return e.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]}return m[t?.kind]||""}function p(t){const e=[];if(!S(t))return{ok:!1,errors:["connection must be an object"]};b.test(String(t.id||""))||e.push("id: a short identifier (letters, digits, _ -)"),f.includes(t.kind)||e.push(`kind: one of ${f.join(", ")}`),["github-enterprise","gitea","git"].includes(t.kind)&&!String(t.baseUrl||"").trim()&&e.push("baseUrl: the hub's URL"),t.baseUrl&&!/^(https?:\/\/)?[a-z0-9.-]+(:\d+)?(\/[^\s]*)?$/i.test(String(t.baseUrl).trim())&&e.push("baseUrl: a host or URL");const r=g.filter(s=>t[s]!==void 0&&t[s]!==null&&t[s]!=="");return r.length&&e.push(`${r.join(", ")}: a connection never stores a secret — store it in the keychain and reference it by secretRef`),t.secretRef!==void 0&&t.secretRef!==null&&t.secretRef!==""&&!d.test(String(t.secretRef))&&e.push("secretRef: a keychain / secret-store name"),t.reach!==void 0&&!Array.isArray(t.reach)&&e.push("reach: a list of remotes or owners this connection may be used for"),{ok:e.length===0,errors:e}}function k(t){const e=p(t);if(!e.ok)throw new _("INVALID",e.errors.join("; "));const i=String(t.id);return{id:i,kind:t.kind,label:String(t.label||t.name||"").trim().slice(0,80)||`${t.kind} · ${c(t)||i}`,...t.baseUrl?{baseUrl:String(t.baseUrl).trim().replace(/\/+$/,"")}:{},secretRef:String(t.secretRef||"").trim()||`chatpanel:scm:${i}`,...t.username?{username:String(t.username).trim().slice(0,80)}:{},reach:(Array.isArray(t.reach)?t.reach:[]).map(r=>String(r).trim().toLowerCase()).filter(Boolean).slice(0,64),enabled:t.enabled!==!1,...t.createdAt?{createdAt:t.createdAt}:{}}}function E(t){const e=String(t||"").trim();if(!e)return null;let i=/^(?:ssh:\/\/)?(?:[\w.-]+@)?([a-z0-9.-]+)(?::\d+)?[:/]+([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(e.replace(/^https?:\/\/(?:[^@/]+@)?/i,""));if(i&&!/^https?:/i.test(e))return{host:i[1].toLowerCase(),owner:i[2],name:i[3],protocol:/^ssh:|^[\w.-]+@/.test(e)?"ssh":"plain"};try{const r=new URL(e),s=r.pathname.replace(/\.git$/,"").split("/").filter(Boolean);if(s.length<2)return null;const a=s.at(-1),n=s.slice(0,-1).filter(u=>u!=="_git").join("/");return{host:r.host.toLowerCase(),owner:n,name:a,protocol:r.protocol.replace(":","")}}catch{return null}}function A(t,e=[]){const i=typeof t=="string"?E(t):t;if(!i)return null;const r=`${i.owner}/${i.name}`.toLowerCase();let s=null,a=-1;for(const n of e||[]){if(!n||n.enabled===!1||c(n)!==i.host)continue;const u=Array.isArray(n.reach)?n.reach:[];let o=u.length?-1:0;for(const h of u)h===r?o=Math.max(o,3):h.endsWith("/*")&&r.startsWith(h.slice(0,-1))?o=Math.max(o,2):h===i.host&&(o=Math.max(o,1));o>a&&(s=n,a=o)}return s}const l=t=>String(t||"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,48)||"x";function $(t,e){return`cp/${l(t)}/${l(e)}`}function C(t,e){return`${l(t)}/${l(e)}`}function R(t,e,{username:i=null}={}){const r=t||{},s=c(r);if(!s||!e)return{};const a=i||r.username||{github:"x-access-token","github-enterprise":"x-access-token",gitlab:"oauth2",bitbucket:"x-token-auth",gitea:"oauth2","azure-devops":"pat"}[r.kind]||"token",n={GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_COUNT:"2",GIT_CONFIG_KEY_0:`credential.https://${s}.helper`,GIT_CONFIG_VALUE_0:'!f() { if [ "$1" = get ]; then printf "username=%s\\npassword=%s\\n" "$CHATPANEL_SCM_USER" "$CHATPANEL_SCM_TOKEN"; fi; }; f',GIT_CONFIG_KEY_1:`credential.https://${s}.useHttpPath`,GIT_CONFIG_VALUE_1:"false",CHATPANEL_SCM_USER:a,CHATPANEL_SCM_TOKEN:String(e)};return(r.kind==="github"||r.kind==="github-enterprise")&&(n.GH_TOKEN=String(e),r.kind==="github-enterprise"&&(n.GH_ENTERPRISE_TOKEN=String(e),n.GH_HOST=s)),r.kind==="gitlab"&&(n.GITLAB_TOKEN=String(e),n.GITLAB_HOST=s),n}function T(t){const e=t||{};return`${{github:"GitHub","github-enterprise":"GitHub Enterprise",gitlab:"GitLab",bitbucket:"Bitbucket",gitea:"Gitea","azure-devops":"Azure DevOps",git:"Git"}[e.kind]||e.kind} · ${c(e)}${e.reach?.length?` · ${e.reach.join(", ")}`:""}${e.enabled===!1?" (off)":""}`}function L(){return{id:"",kind:"github",label:"",baseUrl:"",reach:[],username:""}}function x(t){const e=t||{},r={id:String(e.id||"").trim()||l(e.label||`${e.kind}-${c(e)}`),kind:e.kind||"github",label:String(e.label||"").trim(),...e.baseUrl?{baseUrl:String(e.baseUrl).trim()}:{},...e.username?{username:String(e.username).trim()}:{},...e.secretRef?{secretRef:String(e.secretRef).trim()}:{},reach:String(Array.isArray(e.reach)?e.reach.join(","):e.reach||"").split(/[,\s]+/).map(a=>a.trim()).filter(Boolean),enabled:e.enabled!==!1,...e.createdAt?{createdAt:e.createdAt}:{}},s=p(r);return s.ok?{ok:!0,connection:k(r)}:{ok:!1,errors:s.errors}}export{b as CONNECTION_ID_RE,f as SCM_KINDS,d as SECRET_REF_RE,_ as ScmError,L as blankConnection,$ as branchFor,A as connectionFor,x as connectionFromForm,R as credentialEnv,T as describeConnection,c as hostOf,k as normalizeConnection,E as parseRemote,p as validateConnection,C as worktreeDirFor};
|