robisie 0.2.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +2 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +50 -3
- package/dist/commands.js +34 -7
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/device-login.d.ts +48 -0
- package/dist/device-login.js +523 -0
- package/dist/engine/bundle-report.json +5 -5
- package/dist/engine/tick.cjs +124 -40
- package/dist/engine-inputs.js +16 -26
- package/dist/login.d.ts +29 -0
- package/dist/login.js +153 -0
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js +9 -0
- package/dist/planer-client.d.ts +7 -1
- package/dist/planer-client.js +9 -3
- package/dist/roles.d.ts +1 -1
- package/docs/README.en.md +20 -3
- package/docs/README.md +65 -3
- package/docs/RELEASE-0.1.0.md +2 -0
- package/package.json +1 -1
package/dist/engine/tick.cjs
CHANGED
|
@@ -13832,6 +13832,9 @@ var init_types = __esm({
|
|
|
13832
13832
|
// src/lib/db/schema.ts
|
|
13833
13833
|
var schema_exports = {};
|
|
13834
13834
|
__export2(schema_exports, {
|
|
13835
|
+
cliInstallations: () => cliInstallations,
|
|
13836
|
+
cliKeyPairs: () => cliKeyPairs,
|
|
13837
|
+
deviceAuthorizations: () => deviceAuthorizations,
|
|
13835
13838
|
emailFailures: () => emailFailures,
|
|
13836
13839
|
gdprAuditLog: () => gdprAuditLog,
|
|
13837
13840
|
jobs: () => jobs,
|
|
@@ -13858,7 +13861,7 @@ __export2(schema_exports, {
|
|
|
13858
13861
|
userProfiles: () => userProfiles,
|
|
13859
13862
|
users: () => users
|
|
13860
13863
|
});
|
|
13861
|
-
var users, jobs, plugins, userPlugins, monitoredChannels, subscriptions, products, userProfiles, emailFailures, gdprAuditLog, storageCleanupQueue, bytea, tsvector, memoryDocuments, memoryChunks, plannerProjects, plannerReviewPolicies, plannerTracks, plannerTasks, stripeEvents, userMcpKeys, plannerWebhookSubscriptions, plannerTaskStatusEvents, plannerLimitEvents, mcpRateLimitWindows, licenseUsageReadings, licenseUsageAlerts;
|
|
13864
|
+
var users, jobs, plugins, userPlugins, monitoredChannels, subscriptions, products, userProfiles, emailFailures, gdprAuditLog, storageCleanupQueue, bytea, tsvector, memoryDocuments, memoryChunks, plannerProjects, plannerReviewPolicies, plannerTracks, plannerTasks, stripeEvents, userMcpKeys, cliInstallations, deviceAuthorizations, cliKeyPairs, plannerWebhookSubscriptions, plannerTaskStatusEvents, plannerLimitEvents, mcpRateLimitWindows, licenseUsageReadings, licenseUsageAlerts;
|
|
13862
13865
|
var init_schema2 = __esm({
|
|
13863
13866
|
"src/lib/db/schema.ts"() {
|
|
13864
13867
|
"use strict";
|
|
@@ -14332,6 +14335,51 @@ var init_schema2 = __esm({
|
|
|
14332
14335
|
index("idx_user_mcp_keys_user").on(table.userId)
|
|
14333
14336
|
]
|
|
14334
14337
|
);
|
|
14338
|
+
cliInstallations = pgTable("cli_installations", {
|
|
14339
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
14340
|
+
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
14341
|
+
displayName: text("display_name"),
|
|
14342
|
+
createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
|
|
14343
|
+
revokedAt: timestamp("revoked_at", { withTimezone: true, mode: "date" })
|
|
14344
|
+
}, (table) => [index("idx_cli_installations_user").on(table.userId)]);
|
|
14345
|
+
deviceAuthorizations = pgTable("device_authorizations", {
|
|
14346
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
14347
|
+
deviceCodeHash: text("device_code_hash").notNull().unique(),
|
|
14348
|
+
userCodeHash: text("user_code_hash").notNull().unique(),
|
|
14349
|
+
clientId: text("client_id").notNull(),
|
|
14350
|
+
scope: text("scope").notNull(),
|
|
14351
|
+
installationHint: uuid("installation_hint"),
|
|
14352
|
+
displayName: text("display_name"),
|
|
14353
|
+
state: text("state", { enum: ["pending", "approved", "denied", "consumed", "expired"] }).notNull().default("pending"),
|
|
14354
|
+
ownerUserId: text("owner_user_id").references(() => users.id, { onDelete: "cascade" }),
|
|
14355
|
+
installationId: uuid("installation_id").references(() => cliInstallations.id, { onDelete: "cascade" }),
|
|
14356
|
+
approvedSessionId: text("approved_session_id"),
|
|
14357
|
+
reauthAt: timestamp("reauth_at", { withTimezone: true, mode: "date" }),
|
|
14358
|
+
intervalS: integer("interval_s").notNull().default(5),
|
|
14359
|
+
lastPolledAt: timestamp("last_polled_at", { withTimezone: true, mode: "date" }),
|
|
14360
|
+
pollCount: integer("poll_count").notNull().default(0),
|
|
14361
|
+
createdIpHash: text("created_ip_hash").notNull(),
|
|
14362
|
+
createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
|
|
14363
|
+
expiresAt: timestamp("expires_at", { withTimezone: true, mode: "date" }).notNull().default(sql`now() + interval '600 seconds'`),
|
|
14364
|
+
decidedAt: timestamp("decided_at", { withTimezone: true, mode: "date" }),
|
|
14365
|
+
consumedAt: timestamp("consumed_at", { withTimezone: true, mode: "date" })
|
|
14366
|
+
}, (table) => [
|
|
14367
|
+
index("idx_device_authorizations_active_ip").on(table.createdIpHash, table.expiresAt).where(sql`${table.state} = 'pending'`),
|
|
14368
|
+
index("idx_device_authorizations_owner").on(table.ownerUserId)
|
|
14369
|
+
]);
|
|
14370
|
+
cliKeyPairs = pgTable("cli_key_pairs", {
|
|
14371
|
+
pairId: uuid("pair_id").primaryKey(),
|
|
14372
|
+
installationId: uuid("installation_id").notNull().references(() => cliInstallations.id, { onDelete: "cascade" }),
|
|
14373
|
+
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
14374
|
+
workerKeyId: uuid("worker_key_id").notNull().unique().references(() => userMcpKeys.id, { onDelete: "cascade" }),
|
|
14375
|
+
reviewKeyId: uuid("review_key_id").notNull().unique().references(() => userMcpKeys.id, { onDelete: "cascade" }),
|
|
14376
|
+
issuedAt: timestamp("issued_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
|
|
14377
|
+
confirmedAt: timestamp("confirmed_at", { withTimezone: true, mode: "date" }),
|
|
14378
|
+
revokedAt: timestamp("revoked_at", { withTimezone: true, mode: "date" })
|
|
14379
|
+
}, (table) => [
|
|
14380
|
+
index("idx_cli_key_pairs_installation").on(table.installationId),
|
|
14381
|
+
index("idx_cli_key_pairs_user").on(table.userId)
|
|
14382
|
+
]);
|
|
14335
14383
|
plannerWebhookSubscriptions = pgTable(
|
|
14336
14384
|
"planner_webhook_subscriptions",
|
|
14337
14385
|
{
|
|
@@ -36291,13 +36339,16 @@ async function withProjectTx(userId, fn) {
|
|
|
36291
36339
|
throw new Error("Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie.");
|
|
36292
36340
|
}
|
|
36293
36341
|
function listProjects(userId, options2 = {}) {
|
|
36294
|
-
return withAppUserTx(
|
|
36295
|
-
|
|
36296
|
-
(db) => db.select().from(plannerProjects).where(and(
|
|
36342
|
+
return withAppUserTx(userId, async (db) => {
|
|
36343
|
+
const projects = await db.select().from(plannerProjects).where(and(
|
|
36297
36344
|
eq(plannerProjects.userId, userId),
|
|
36298
36345
|
options2.includeArchived ? void 0 : isNull(plannerProjects.archivedAt)
|
|
36299
|
-
)).orderBy(asc(plannerProjects.createdAt))
|
|
36300
|
-
|
|
36346
|
+
)).orderBy(asc(plannerProjects.createdAt));
|
|
36347
|
+
if (projects.length === 0) return [];
|
|
36348
|
+
const policies = await db.select({ projectId: plannerReviewPolicies.projectId, mode: plannerReviewPolicies.mode }).from(plannerReviewPolicies).where(eq(plannerReviewPolicies.userId, userId));
|
|
36349
|
+
const byProject = new Map(policies.map((policy) => [policy.projectId, policy.mode]));
|
|
36350
|
+
return projects.map((project) => ({ ...project, reviewPolicy: byProject.get(project.id) ?? null }));
|
|
36351
|
+
});
|
|
36301
36352
|
}
|
|
36302
36353
|
async function createProject(userId, input) {
|
|
36303
36354
|
const name3 = validProjectName(input.name);
|
|
@@ -37577,7 +37628,7 @@ var init_constants = __esm({
|
|
|
37577
37628
|
"packages/client/src/constants.ts"() {
|
|
37578
37629
|
"use strict";
|
|
37579
37630
|
PACKAGE_NAME = "robisie";
|
|
37580
|
-
PACKAGE_VERSION = "0.
|
|
37631
|
+
PACKAGE_VERSION = "0.4.0";
|
|
37581
37632
|
SUPPORTED_CONTRACT_MAJOR = 1;
|
|
37582
37633
|
DEFAULT_ORIGIN = "https://robisie.app";
|
|
37583
37634
|
MCP_SERVER_NAME = "robisie";
|
|
@@ -53343,7 +53394,7 @@ function finishTickState(state, outcome, tick, at3, facts = {}) {
|
|
|
53343
53394
|
const reason = observed ? `runtime=failed outcome=${outcome} loaded=${facts.observedLoaded ?? "UNKNOWN"} tick=${tick}` : `outcome=failed tick=${tick}`;
|
|
53344
53395
|
return { ...state, confirmed: void 0, breaker: { ...state.confirmed, at: at3, reason } };
|
|
53345
53396
|
}
|
|
53346
|
-
function readLoadedSha(repo, git2 =
|
|
53397
|
+
function readLoadedSha(repo, git2 = quietGit) {
|
|
53347
53398
|
try {
|
|
53348
53399
|
const head = git2(["rev-parse", "HEAD"], repo);
|
|
53349
53400
|
const dirty = git2(["status", "--porcelain", "-z", "--", ":(glob)maszynista/*.ts", "services", "src/lib"], repo);
|
|
@@ -53355,9 +53406,15 @@ function readLoadedSha(repo, git2 = defaultGit) {
|
|
|
53355
53406
|
function mainRefLockRace(error48) {
|
|
53356
53407
|
return [record6(error48).stderr, error48 instanceof Error ? error48.message : String(error48)].some((diagnostic) => typeof diagnostic === "string" && diagnostic.includes("cannot lock ref 'refs/remotes/origin/main'"));
|
|
53357
53408
|
}
|
|
53358
|
-
function
|
|
53409
|
+
function runGit(args, cwd = process.cwd(), timeoutMs = 6e4, quiet = false) {
|
|
53359
53410
|
try {
|
|
53360
|
-
const output = (0, import_node_child_process4.execFileSync)("git", args, {
|
|
53411
|
+
const output = (0, import_node_child_process4.execFileSync)("git", args, {
|
|
53412
|
+
cwd,
|
|
53413
|
+
encoding: "utf8",
|
|
53414
|
+
timeout: timeoutMs,
|
|
53415
|
+
maxBuffer: 20 * 1024 * 1024,
|
|
53416
|
+
stdio: quiet ? ["ignore", "pipe", "ignore"] : void 0
|
|
53417
|
+
});
|
|
53361
53418
|
return args.includes("-z") ? output : output.trim();
|
|
53362
53419
|
} catch (error48) {
|
|
53363
53420
|
throw Object.assign(
|
|
@@ -54079,7 +54136,7 @@ async function runHostActivation(input, deps = {}) {
|
|
|
54079
54136
|
deps.log?.(`ff ${head.slice(0, 8)}\u2192${target.slice(0, 8)} ${label2} brud=${porcelainPaths(porcelain).length} zachowany`);
|
|
54080
54137
|
return endRefusal({ code: "activate", target });
|
|
54081
54138
|
}
|
|
54082
|
-
var import_node_child_process4, import_node_crypto6, import_node_fs11, import_node_path13, STATE_FILE, MODE_FILE, BREAKER_WINDOW_TICKS, SMOKE_TIMEOUT_MS, ACTIVATION_RESERVE_MS, loadableExtensions, dependencyKeys;
|
|
54139
|
+
var import_node_child_process4, import_node_crypto6, import_node_fs11, import_node_path13, STATE_FILE, MODE_FILE, BREAKER_WINDOW_TICKS, SMOKE_TIMEOUT_MS, ACTIVATION_RESERVE_MS, loadableExtensions, dependencyKeys, defaultGit, quietGit;
|
|
54083
54140
|
var init_host_activation = __esm({
|
|
54084
54141
|
"maszynista/host-activation.ts"() {
|
|
54085
54142
|
"use strict";
|
|
@@ -54096,6 +54153,8 @@ var init_host_activation = __esm({
|
|
|
54096
54153
|
ACTIVATION_RESERVE_MS = 15e4;
|
|
54097
54154
|
loadableExtensions = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".mjs", ".cjs", ".json"]);
|
|
54098
54155
|
dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "overrides", "resolutions"];
|
|
54156
|
+
defaultGit = (args, cwd, timeoutMs) => runGit(args, cwd, timeoutMs);
|
|
54157
|
+
quietGit = (args, cwd, timeoutMs) => runGit(args, cwd, timeoutMs, true);
|
|
54099
54158
|
}
|
|
54100
54159
|
});
|
|
54101
54160
|
|
|
@@ -74735,6 +74794,7 @@ var init_planer_client = __esm({
|
|
|
74735
74794
|
this.operation = operation;
|
|
74736
74795
|
this.uncertain = uncertain;
|
|
74737
74796
|
this.name = "PlanerClientError";
|
|
74797
|
+
if (diagnostic?.gateReason !== void 0) this.gateReason = diagnostic.gateReason;
|
|
74738
74798
|
if (diagnostic?.plannerCode !== void 0) this.plannerCode = diagnostic.plannerCode;
|
|
74739
74799
|
if (diagnostic?.requestId !== void 0) this.requestId = diagnostic.requestId;
|
|
74740
74800
|
if (diagnostic?.plannerMeta !== void 0) this.plannerMeta = diagnostic.plannerMeta;
|
|
@@ -74789,7 +74849,7 @@ var init_planer_client = __esm({
|
|
|
74789
74849
|
freeText = external_exports.string().max(2e3);
|
|
74790
74850
|
name2 = external_exports.string().min(1).max(500);
|
|
74791
74851
|
date9 = external_exports.iso.datetime({ offset: true });
|
|
74792
|
-
projectSchema = external_exports.object({ id: uuid8, name: external_exports.string(), slug: external_exports.string() });
|
|
74852
|
+
projectSchema = external_exports.object({ id: uuid8, name: external_exports.string(), slug: external_exports.string(), reviewPolicy: external_exports.enum(["legacy", "enforced"]).nullable().optional() });
|
|
74793
74853
|
trackSchema = external_exports.object({ id: uuid8, projectId: uuid8, name: external_exports.string(), position: external_exports.number().int() });
|
|
74794
74854
|
taskSchema = external_exports.object({
|
|
74795
74855
|
id: uuid8,
|
|
@@ -75016,7 +75076,14 @@ var init_planer_client = __esm({
|
|
|
75016
75076
|
if (result.content.length !== 1 || result.content[0]?.type !== "text") throw new Error("Invalid tool content");
|
|
75017
75077
|
value = JSON.parse(result.content[0].text);
|
|
75018
75078
|
} catch {
|
|
75019
|
-
|
|
75079
|
+
const text9 = result.content.length === 1 && result.content[0]?.type === "text" ? result.content[0].text : "";
|
|
75080
|
+
const gateReason = result.isError && text9.startsWith("Brama recenzji: ") && text9.trim().length <= 200 && !/[\p{C}\p{Zl}\p{Zp}]/u.test(text9) ? text9.trim() : void 0;
|
|
75081
|
+
throw new PlanerClientError(
|
|
75082
|
+
result.isError ? "TOOL_ERROR" : "INVALID_RESPONSE",
|
|
75083
|
+
operation,
|
|
75084
|
+
mutation,
|
|
75085
|
+
gateReason === void 0 ? void 0 : { gateReason }
|
|
75086
|
+
);
|
|
75020
75087
|
}
|
|
75021
75088
|
return { value, isError: result.isError === true };
|
|
75022
75089
|
}
|
|
@@ -76326,16 +76393,19 @@ function callLocalReceiver(input, dir) {
|
|
|
76326
76393
|
"--disable-web-search",
|
|
76327
76394
|
"--verbatim",
|
|
76328
76395
|
"--reasoning-effort",
|
|
76329
|
-
"
|
|
76396
|
+
"low"
|
|
76330
76397
|
];
|
|
76331
76398
|
const result = (0, import_node_child_process7.spawnSync)("grok", args, { cwd: dir, env: localReceiverEnv(), encoding: "utf8", timeout: 18e4, maxBuffer: 256 * 1024 });
|
|
76332
|
-
if (result.error || result.status !== 0)
|
|
76399
|
+
if (result.error || result.status !== 0) {
|
|
76400
|
+
const stderr = (result.stderr ?? "").replace(new RegExp("\\p{C}", "gu"), "").trim().slice(0, 200);
|
|
76401
|
+
throw result.error ?? new Error(`Grok exit=${result.status}${stderr ? `: ${stderr}` : ""}`);
|
|
76402
|
+
}
|
|
76333
76403
|
const envelope = record8(JSON.parse(result.stdout)), models = Object.keys(record8(envelope.modelUsage));
|
|
76334
76404
|
if (envelope.stopReason !== "end_turn" || models.length !== 1 || !/^grok-/.test(models[0])) throw new Error("Niepotwierdzony model/terminal Groka");
|
|
76335
76405
|
return { output: envelope.structuredOutput ?? null, invocation: {
|
|
76336
76406
|
provider: "xai",
|
|
76337
76407
|
actualModel: models[0],
|
|
76338
|
-
effort: "
|
|
76408
|
+
effort: "low",
|
|
76339
76409
|
exit: result.status,
|
|
76340
76410
|
startedAt,
|
|
76341
76411
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -77319,7 +77389,7 @@ function completion(dir, claim, response, timestamp3, stop = "") {
|
|
|
77319
77389
|
reason = `U\u017Cycia ${p.events.length}/${p.contract.min}; termin ${p.contract.deadline}; wyzwalacz: nowe zdarzenie lub deadline`;
|
|
77320
77390
|
} else {
|
|
77321
77391
|
const raw = record10(response), invocation = record10(raw.invocation), model = text6.parse(invocation.actualModel);
|
|
77322
|
-
if (invocation.provider !== "xai" || !/^grok-/.test(model) || invocation.exit !== 0 || invocation.effort !== "none" || !(0, import_node_util6.isDeepStrictEqual)(Object.keys(record10(invocation.modelUsage)), [model]) || !at2.safeParse(invocation.startedAt).success || !at2.safeParse(invocation.finishedAt).success || !Array.isArray(invocation.command)) throw new Error("Brak rzeczywistego wywo\u0142ania Groka");
|
|
77392
|
+
if (invocation.provider !== "xai" || !/^grok-/.test(model) || invocation.exit !== 0 || invocation.effort !== "none" && invocation.effort !== "low" || !(0, import_node_util6.isDeepStrictEqual)(Object.keys(record10(invocation.modelUsage)), [model]) || !at2.safeParse(invocation.startedAt).success || !at2.safeParse(invocation.finishedAt).success || !Array.isArray(invocation.command)) throw new Error("Brak rzeczywistego wywo\u0142ania Groka");
|
|
77323
77393
|
const results = validateLocalReceiver(raw.output, input);
|
|
77324
77394
|
if (results.some((r) => r.verdict !== "PASS")) throw new Error(results.map((r) => `${r.index}: ${r.verdict}: ${r.reason}`).join("; "));
|
|
77325
77395
|
const used = new Set(results.flatMap((r) => r.eventIds)), events = p.events.filter((e) => used.has(e.id));
|
|
@@ -77962,6 +78032,7 @@ async function acceptLocalDelivery(api, cardId, receiver) {
|
|
|
77962
78032
|
const intentFile = `${receiver.archive}.acceptance.json`;
|
|
77963
78033
|
const intentValue = readJson4(intentFile, true);
|
|
77964
78034
|
let intent = intentValue;
|
|
78035
|
+
let acceptError;
|
|
77965
78036
|
let current = await read();
|
|
77966
78037
|
const prepared = aligned(current);
|
|
77967
78038
|
if (intent && (intent.packetHash !== receiver.packetHash || !intent.prepared || !intent.request || intent.request.id !== cardId || intent.request.cardId !== cardId || intent.request.projectId !== current.projectId || intent.request.providerDeclared !== provider || !prepared)) return stop("obcy zapis \u017C\u0105dania odbioru");
|
|
@@ -78011,12 +78082,16 @@ async function acceptLocalDelivery(api, cardId, receiver) {
|
|
|
78011
78082
|
}
|
|
78012
78083
|
try {
|
|
78013
78084
|
await api.acceptReview(request2);
|
|
78014
|
-
} catch {
|
|
78085
|
+
} catch (error48) {
|
|
78086
|
+
acceptError = error48;
|
|
78015
78087
|
}
|
|
78016
78088
|
current = await read();
|
|
78017
78089
|
}
|
|
78018
78090
|
const confirmed = (card) => {
|
|
78019
|
-
if (!["delivered", "done"].includes(card.status))
|
|
78091
|
+
if (!["delivered", "done"].includes(card.status)) {
|
|
78092
|
+
const reason = acceptError instanceof PlanerClientError ? (acceptError.gateReason ?? acceptError.code).slice(0, 200) : void 0;
|
|
78093
|
+
return stop(`niepotwierdzony odbi\xF3r${reason ? `: ${reason}` : ""}; diagnoza bez ponowienia acceptReview`);
|
|
78094
|
+
}
|
|
78020
78095
|
const receipt = storedReview(card);
|
|
78021
78096
|
if (!receipt || !matchesSnapshot(receipt, intent.request) || receipt.providerDeclared !== provider) return stop("obcy receipt/submission/provider");
|
|
78022
78097
|
const comparable = (task) => {
|
|
@@ -78053,6 +78128,7 @@ var init_local_acceptance = __esm({
|
|
|
78053
78128
|
import_node_crypto16 = require("node:crypto");
|
|
78054
78129
|
import_node_util7 = require("node:util");
|
|
78055
78130
|
init_zod();
|
|
78131
|
+
init_planer_client();
|
|
78056
78132
|
init_done_evidence();
|
|
78057
78133
|
init_delivered_gate();
|
|
78058
78134
|
init_local_receiver();
|
|
@@ -78094,7 +78170,7 @@ var init_git_commit = __esm({
|
|
|
78094
78170
|
});
|
|
78095
78171
|
|
|
78096
78172
|
// packages/client/src/delivery-local.ts
|
|
78097
|
-
function
|
|
78173
|
+
function runGit2(repo, args, input) {
|
|
78098
78174
|
let options2;
|
|
78099
78175
|
try {
|
|
78100
78176
|
options2 = args[0] === "notes" && args.includes("add") ? gitCommitOptions(args, repo) : { args, env: process.env };
|
|
@@ -78116,12 +78192,12 @@ function gitText(run) {
|
|
|
78116
78192
|
return (run.error?.message ?? (run.stderr.trim() || run.stdout.trim())).slice(0, OUTPUT_LIMIT);
|
|
78117
78193
|
}
|
|
78118
78194
|
function resolveCommit(repo, spec) {
|
|
78119
|
-
const run =
|
|
78195
|
+
const run = runGit2(repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${spec}^{commit}`]);
|
|
78120
78196
|
const sha5 = run.stdout.trim();
|
|
78121
78197
|
return run.status === 0 && SHA_RE.test(sha5) ? sha5 : void 0;
|
|
78122
78198
|
}
|
|
78123
78199
|
function isAncestor2(repo, ancestor3, descendant) {
|
|
78124
|
-
const run =
|
|
78200
|
+
const run = runGit2(repo, ["merge-base", "--is-ancestor", ancestor3, descendant]);
|
|
78125
78201
|
if (run.status === 0) return true;
|
|
78126
78202
|
if (run.status === 1) return false;
|
|
78127
78203
|
return run;
|
|
@@ -78135,7 +78211,7 @@ function canonical2(value) {
|
|
|
78135
78211
|
}
|
|
78136
78212
|
function prepare(repo, input) {
|
|
78137
78213
|
const target = typeof input?.target === "string" ? input.target : "";
|
|
78138
|
-
const branch =
|
|
78214
|
+
const branch = runGit2(repo, ["check-ref-format", "--branch", target]);
|
|
78139
78215
|
if (!target || target.startsWith("-") || branch.status !== 0 || branch.stdout.trim() !== target) {
|
|
78140
78216
|
return { ok: false, reason: "invalid-target", message: `Nieprawid\u0142owa nazwa ga\u0142\u0119zi celu: ${JSON.stringify(target)}` };
|
|
78141
78217
|
}
|
|
@@ -78148,7 +78224,7 @@ function prepare(repo, input) {
|
|
|
78148
78224
|
}
|
|
78149
78225
|
const taskSha = resolveCommit(repo, requested);
|
|
78150
78226
|
if (taskSha !== requested) return { ok: false, reason: "invalid-task", message: `Commit zadania ${requested} nie istnieje w repozytorium.` };
|
|
78151
|
-
const merge3 =
|
|
78227
|
+
const merge3 = runGit2(repo, ["merge-tree", "--write-tree", "--name-only", "--no-messages", targetSha2, taskSha]);
|
|
78152
78228
|
const lines2 = merge3.stdout.split("\n").filter(Boolean);
|
|
78153
78229
|
const tree = lines2[0] ?? "";
|
|
78154
78230
|
if (merge3.status === 1 && SHA_RE.test(tree)) {
|
|
@@ -78181,7 +78257,7 @@ function check4(repo, prepared, commands, options2 = {}) {
|
|
|
78181
78257
|
return { ok: false, reason: "error", message: `Nie uda\u0142o si\u0119 utworzy\u0107 katalogu tymczasowego: ${error48 instanceof Error ? error48.message : String(error48)}`, results };
|
|
78182
78258
|
}
|
|
78183
78259
|
const worktree = (0, import_node_path28.join)(tmp, "wt");
|
|
78184
|
-
const add2 =
|
|
78260
|
+
const add2 = runGit2(repo, ["worktree", "add", "--detach", "--quiet", worktree, prepared.taskSha]);
|
|
78185
78261
|
if (add2.status !== 0 || add2.error) {
|
|
78186
78262
|
const outcome2 = { ok: false, reason: "error", message: `git worktree add nie powiod\u0142o si\u0119: ${gitText(add2)}`, results };
|
|
78187
78263
|
return withCleanup(outcome2, removeWorktree(repo, tmp, worktree, false), tmp, worktree);
|
|
@@ -78197,14 +78273,14 @@ function check4(repo, prepared, commands, options2 = {}) {
|
|
|
78197
78273
|
}
|
|
78198
78274
|
function removeWorktree(repo, tmp, worktree, added) {
|
|
78199
78275
|
const failed2 = [];
|
|
78200
|
-
const remove =
|
|
78276
|
+
const remove = runGit2(repo, ["worktree", "remove", "--force", worktree]);
|
|
78201
78277
|
if (added && (remove.status !== 0 || remove.error)) failed2.push({ step: "worktree-remove", message: gitText(remove) || `status=${remove.status}` });
|
|
78202
78278
|
try {
|
|
78203
78279
|
(0, import_node_fs25.rmSync)(tmp, { recursive: true, force: true });
|
|
78204
78280
|
} catch (error48) {
|
|
78205
78281
|
failed2.push({ step: "rm-tmp", message: error48 instanceof Error ? error48.message : String(error48) });
|
|
78206
78282
|
}
|
|
78207
|
-
const prune =
|
|
78283
|
+
const prune = runGit2(repo, ["worktree", "prune"]);
|
|
78208
78284
|
if (prune.status !== 0 || prune.error) failed2.push({ step: "worktree-prune", message: gitText(prune) || `status=${prune.status}` });
|
|
78209
78285
|
return failed2;
|
|
78210
78286
|
}
|
|
@@ -78237,7 +78313,7 @@ function runChecks(cwd, commands, timeoutMs, results) {
|
|
|
78237
78313
|
return { ok: true, results };
|
|
78238
78314
|
}
|
|
78239
78315
|
function checkedOutIn(repo, ref) {
|
|
78240
|
-
const list2 =
|
|
78316
|
+
const list2 = runGit2(repo, ["worktree", "list", "--porcelain", "-z"]);
|
|
78241
78317
|
if (list2.status !== 0) return list2;
|
|
78242
78318
|
let path34;
|
|
78243
78319
|
for (const field of list2.stdout.split("\0")) {
|
|
@@ -78261,7 +78337,7 @@ function deliver(repo, prepared) {
|
|
|
78261
78337
|
if (!forward || prepared.mode !== "fast-forward") {
|
|
78262
78338
|
return { ok: false, reason: "not-fast-forward", message: `Odmowa: ${taskSha} nie jest fast-forwardem ${prepared.target} (${targetSha2}). Zaktualizuj ga\u0142\u0105\u017A zadania o cel i powt\xF3rz.` };
|
|
78263
78339
|
}
|
|
78264
|
-
const symbolic =
|
|
78340
|
+
const symbolic = runGit2(repo, ["symbolic-ref", "-q", ref]);
|
|
78265
78341
|
if (symbolic.status === 0 && !symbolic.error) {
|
|
78266
78342
|
return { ok: false, reason: "target-is-symbolic-ref", message: `Odmowa: ${prepared.target} jest aliasem (symbolic ref) do ${symbolic.stdout.trim()}; dostarcz do ga\u0142\u0119zi docelowej wprost.` };
|
|
78267
78343
|
}
|
|
@@ -78273,7 +78349,7 @@ function deliver(repo, prepared) {
|
|
|
78273
78349
|
if (before !== targetSha2) {
|
|
78274
78350
|
return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} przesun\u0105\u0142 si\u0119 z ${targetSha2} na ${before ?? "(brak)"} po prepare; nic nie zmieniono.` };
|
|
78275
78351
|
}
|
|
78276
|
-
const merge3 =
|
|
78352
|
+
const merge3 = runGit2(worktree, ["-c", `core.hooksPath=${import_node_os6.devNull}`, "merge", "--ff-only", "--no-autostash", "--no-overwrite-ignore", taskSha]);
|
|
78277
78353
|
const after2 = resolveCommit(repo, ref);
|
|
78278
78354
|
if (after2 === taskSha) return { ok: true, moved: true, ref, from: targetSha2, to: taskSha };
|
|
78279
78355
|
if (after2 === targetSha2) {
|
|
@@ -78283,7 +78359,7 @@ Od\u0142\xF3\u017C zmiany (git stash) albo cofnij je i pon\xF3w dostaw\u0119.` }
|
|
|
78283
78359
|
}
|
|
78284
78360
|
return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} po pr\xF3bie FF wskazuje ${after2 ?? "(brak)"} zamiast ${taskSha}; sprawd\u017A stan repozytorium.` };
|
|
78285
78361
|
}
|
|
78286
|
-
const update =
|
|
78362
|
+
const update = runGit2(repo, ["update-ref", "--no-deref", "-m", `robisie: dostawa local-ff ${taskSha}`, ref, taskSha, targetSha2]);
|
|
78287
78363
|
if (update.status !== 0) {
|
|
78288
78364
|
const now = resolveCommit(repo, ref);
|
|
78289
78365
|
if (now !== targetSha2) {
|
|
@@ -78305,24 +78381,24 @@ function attachEvidence(repo, sha5, kind, evidence2) {
|
|
|
78305
78381
|
}
|
|
78306
78382
|
if (line2 === void 0) return { ok: false, reason: "error", message: "Dow\xF3d nie jest serializowalny do JSON." };
|
|
78307
78383
|
const ref = `refs/notes/robisie/${kind}`;
|
|
78308
|
-
const strategy =
|
|
78384
|
+
const strategy = runGit2(repo, ["config", `notes.robisie/${kind}.mergeStrategy`, "cat_sort_uniq"]);
|
|
78309
78385
|
if (strategy.status !== 0) return { ok: false, reason: "error", message: `Ustawienie notes mergeStrategy nie powiod\u0142o si\u0119: ${gitText(strategy)}` };
|
|
78310
78386
|
const existing = readEvidenceLines(repo, kind, sha5);
|
|
78311
78387
|
if (!Array.isArray(existing)) return existing;
|
|
78312
78388
|
if (existing.includes(line2)) return { ok: true, ref, sha: sha5, written: false };
|
|
78313
78389
|
const body = [.../* @__PURE__ */ new Set([...existing, line2])].sort().join("\n") + "\n";
|
|
78314
|
-
const write =
|
|
78390
|
+
const write = runGit2(repo, ["notes", `--ref=${ref}`, "add", "-f", "-F", "-", sha5], body);
|
|
78315
78391
|
if (write.status !== 0) return { ok: false, reason: "error", message: `git notes add nie powiod\u0142o si\u0119: ${gitText(write)}` };
|
|
78316
78392
|
return { ok: true, ref, sha: sha5, written: true };
|
|
78317
78393
|
}
|
|
78318
78394
|
function readEvidenceLines(repo, kind, sha5) {
|
|
78319
78395
|
const ref = `refs/notes/robisie/${kind}`;
|
|
78320
|
-
const exists2 =
|
|
78396
|
+
const exists2 = runGit2(repo, ["rev-parse", "--verify", "--quiet", ref]);
|
|
78321
78397
|
if (exists2.status === 1 && !exists2.error && !exists2.stderr.trim()) return [];
|
|
78322
78398
|
if (exists2.status !== 0 || exists2.error) {
|
|
78323
78399
|
return { ok: false, reason: "evidence-read-failed", message: `Odczyt ${ref} nie powi\xF3d\u0142 si\u0119: ${gitText(exists2) || `status=${exists2.status}`}` };
|
|
78324
78400
|
}
|
|
78325
|
-
const show =
|
|
78401
|
+
const show = runGit2(repo, ["notes", `--ref=${ref}`, "show", sha5]);
|
|
78326
78402
|
if (show.status === 0 && !show.error) return show.stdout.split("\n").filter(Boolean);
|
|
78327
78403
|
if (show.status === 1 && !show.error && /^error: no note found for object [0-9a-f]+\.?$/.test(show.stderr.trim())) return [];
|
|
78328
78404
|
return { ok: false, reason: "evidence-read-failed", message: `git notes show nie powiod\u0142o si\u0119: ${gitText(show) || `status=${show.status}`}` };
|
|
@@ -320388,11 +320464,19 @@ async function localAcceptancePhase(s, uid, dry, snapshot2, installation) {
|
|
|
320388
320464
|
throw new Error("Nie mo\u017Cna odczyta\u0107 archiwum odbioru lokalnego", { cause });
|
|
320389
320465
|
}
|
|
320390
320466
|
if (!installation?.localAcceptance) throw new Error("Brak kontekstu localAcceptance");
|
|
320391
|
-
|
|
320392
|
-
|
|
320393
|
-
|
|
320394
|
-
|
|
320395
|
-
|
|
320467
|
+
if ((0, import_node_fs47.existsSync)(`${ref}.acceptance.json`) && (0, import_node_fs47.existsSync)(`${ref}.acceptance-stop.json`) && card.status === "in_review") continue;
|
|
320468
|
+
try {
|
|
320469
|
+
const confirmed = await acceptLocalDelivery2(await installation.localAcceptance(), card.id, completion2);
|
|
320470
|
+
snapshot2?.set(card.id, confirmed);
|
|
320471
|
+
rememberProcessCards(s, [confirmed]);
|
|
320472
|
+
s.done_auto++;
|
|
320473
|
+
lastTick(s, "acceptance-local", "Chroniony odbi\xF3r lokalny \u2192 done", true, card.id);
|
|
320474
|
+
} catch (error48) {
|
|
320475
|
+
if (!(error48 instanceof Error) || !error48.message.startsWith("STOP odbioru lokalnego:")) throw error48;
|
|
320476
|
+
const reason = error48.message;
|
|
320477
|
+
(0, import_node_fs47.appendFileSync)(import_node_path52.default.join(DIR, "installation-events.jsonl"), JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), cardId: card.id, reason }) + "\n", { mode: 384, flush: true });
|
|
320478
|
+
log2(`HOLD odbioru lokalnego ${card.id}: ${reason}`);
|
|
320479
|
+
}
|
|
320396
320480
|
}
|
|
320397
320481
|
}
|
|
320398
320482
|
async function testerPhase(s, uid, projectId2, dry = DRY2, runtime = loadedSha, snapshot2, installation = tickInstallation) {
|
package/dist/engine-inputs.js
CHANGED
|
@@ -99,36 +99,26 @@ export function inputDirectory(config) {
|
|
|
99
99
|
/** Reject links along the write path; do not change modes on user-owned directories. */
|
|
100
100
|
function checkDirectory(directory, writing, configPath) {
|
|
101
101
|
try {
|
|
102
|
-
|
|
103
|
-
if (parent !== directory)
|
|
104
|
-
checkDirectory(parent, false, configPath);
|
|
102
|
+
let existing = directory;
|
|
105
103
|
let stat;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
while (true) {
|
|
116
|
-
try {
|
|
117
|
-
lstatSync(existing);
|
|
118
|
-
break;
|
|
119
|
-
}
|
|
120
|
-
catch (cause) {
|
|
121
|
-
if (!missing(cause))
|
|
122
|
-
throw cause;
|
|
123
|
-
existing = dirname(existing);
|
|
124
|
-
}
|
|
104
|
+
while (true) {
|
|
105
|
+
try {
|
|
106
|
+
stat = lstatSync(existing);
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!missing(error) || dirname(existing) === existing)
|
|
111
|
+
throw error;
|
|
112
|
+
existing = dirname(existing);
|
|
125
113
|
}
|
|
126
|
-
accessSync(existing, constants.W_OK | constants.X_OK);
|
|
127
|
-
return;
|
|
128
114
|
}
|
|
129
|
-
|
|
115
|
+
// inputDirectory canonicalizes stateDir; a changed realpath here means a link in the write path.
|
|
116
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(existing) !== existing)
|
|
130
117
|
throw problem(directory, configPath);
|
|
131
|
-
|
|
118
|
+
if (existing === directory)
|
|
119
|
+
accessSync(directory, constants.R_OK | constants.X_OK | (writing ? constants.W_OK : 0));
|
|
120
|
+
else if (writing)
|
|
121
|
+
accessSync(existing, constants.W_OK | constants.X_OK);
|
|
132
122
|
}
|
|
133
123
|
catch (error) {
|
|
134
124
|
if (error instanceof RobisieError)
|
package/dist/login.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Ctx } from "./context.js";
|
|
2
|
+
import { type LoginIo, type PairCopies } from "./device-login.js";
|
|
3
|
+
/** Replaceable like commands.ts `loginIo`: tests swap the clock and sleep, never the protocol. */
|
|
4
|
+
export declare const loginRuntime: {
|
|
5
|
+
io: Partial<LoginIo>;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* J5 copies of A: the header in `~/.claude.json` (only where init installed it and it is still there) and the
|
|
9
|
+
* manifest login fields. `restore` writes back exactly the captured state and throws when the read-back differs.
|
|
10
|
+
*/
|
|
11
|
+
export declare function pairCopies(ctx: Ctx): PairCopies;
|
|
12
|
+
/** `npx robisie login`; the manifest's installation_id is only a claim the server checks (§5.2). */
|
|
13
|
+
export declare function login(ctx: Ctx, options: {
|
|
14
|
+
wait: boolean;
|
|
15
|
+
timeoutSeconds?: number;
|
|
16
|
+
}): Promise<0 | 1 | 2>;
|
|
17
|
+
/** init without any key and without a terminal pairs instead of stopping at „Brak klucza” (§7.6). */
|
|
18
|
+
export declare function initNeedsLogin(ctx: Ctx, keyStdin: boolean): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Takes the installation lock, finishes an interrupted pair journal, and for a login installation hands the
|
|
21
|
+
* command A and B from the files instead of the environment (§7.3, §7.6). Installations never paired by
|
|
22
|
+
* login have no mutex file: creating one here would turn doctor into a writer of manual installations.
|
|
23
|
+
*/
|
|
24
|
+
export declare function openInstallation(ctx: Ctx, command: "init" | "doctor" | "factory run"): Promise<{
|
|
25
|
+
ctx: Ctx;
|
|
26
|
+
release: (() => void) | null;
|
|
27
|
+
}>;
|
|
28
|
+
/** Releases the lock after the command; a failure is reported, the command's own result stands. */
|
|
29
|
+
export declare function closeInstallation(ctx: Ctx, release: () => void): void;
|
package/dist/login.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { existsSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { agentPaths, planAgent } from "./agents.js";
|
|
5
|
+
import { KEY_ENV, KEY_PATTERN } from "./constants.js";
|
|
6
|
+
import { RobisieError } from "./context.js";
|
|
7
|
+
import { acquireInstallationLock, deviceLogin, resumePairJournal } from "./device-login.js";
|
|
8
|
+
import { applyOp, capture } from "./fsops.js";
|
|
9
|
+
import { clientPaths, readKey, readManifest, refuseSymlink, writeManifest, writePrivate } from "./manifest.js";
|
|
10
|
+
/**
|
|
11
|
+
* CLI side of `npx robisie login` (CONTRACT.md §7.3 J5, §7.6): the copies of A outside the key files, the
|
|
12
|
+
* installation lock with journal recovery for init/doctor/factory run, and which keys those commands use.
|
|
13
|
+
*/
|
|
14
|
+
const REVIEW_KEY_ENV = "ROBISIE_REVIEW_KEY";
|
|
15
|
+
/** Replaceable like commands.ts `loginIo`: tests swap the clock and sleep, never the protocol. */
|
|
16
|
+
export const loginRuntime = { io: {} };
|
|
17
|
+
function isRecord(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
/** The `~/.claude.json` entry init writes; Codex and OpenCode read A from ENV and keep no copy. */
|
|
21
|
+
function claudeOp(ctx, key) {
|
|
22
|
+
const [op] = planAgent(ctx, "claude", [], key);
|
|
23
|
+
if (!op || op.kind !== "json")
|
|
24
|
+
throw new Error("Plan instalacji Claude Code nie ma wpisu MCP.");
|
|
25
|
+
return op;
|
|
26
|
+
}
|
|
27
|
+
function recorded(manifest, op) {
|
|
28
|
+
return manifest?.entries.find((entry) => entry.kind === "json" && entry.path === op.path && isDeepStrictEqual(entry.keyPath, [...op.keyPath]));
|
|
29
|
+
}
|
|
30
|
+
function jsonValue(op) {
|
|
31
|
+
const bytes = capture(op.path).bytes;
|
|
32
|
+
if (bytes === null)
|
|
33
|
+
return null;
|
|
34
|
+
let cursor = JSON.parse(bytes.toString("utf8"));
|
|
35
|
+
for (const key of op.keyPath)
|
|
36
|
+
cursor = isRecord(cursor) && Object.hasOwn(cursor, key) ? cursor[key] : null;
|
|
37
|
+
return cursor ?? null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* J5 copies of A: the header in `~/.claude.json` (only where init installed it and it is still there) and the
|
|
41
|
+
* manifest login fields. `restore` writes back exactly the captured state and throws when the read-back differs.
|
|
42
|
+
*/
|
|
43
|
+
export function pairCopies(ctx) {
|
|
44
|
+
const paths = clientPaths(agentPaths(ctx).clientDir);
|
|
45
|
+
const manifestText = () => {
|
|
46
|
+
refuseSymlink(paths.manifest);
|
|
47
|
+
return capture(paths.manifest).bytes?.toString("utf8") ?? null;
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
capture: () => {
|
|
51
|
+
const op = claudeOp(ctx, "");
|
|
52
|
+
const state = { manifest: manifestText(), claude: null };
|
|
53
|
+
if (recorded(readManifest(paths.manifest), op))
|
|
54
|
+
state.claude = jsonValue(op);
|
|
55
|
+
return state;
|
|
56
|
+
},
|
|
57
|
+
apply: ({ key, installationId, pairId }) => {
|
|
58
|
+
const manifest = readManifest(paths.manifest);
|
|
59
|
+
const op = claudeOp(ctx, key);
|
|
60
|
+
const entries = [...(manifest?.entries ?? [])];
|
|
61
|
+
const prior = recorded(manifest, op);
|
|
62
|
+
if (prior && jsonValue(op) !== null)
|
|
63
|
+
entries[entries.indexOf(prior)] = Object.assign({}, prior, applyOp(op, prior, { backupDir: paths.backups }).entry);
|
|
64
|
+
writeManifest(paths.dir, {
|
|
65
|
+
agents: manifest?.agents ?? [], roleProviders: manifest?.roleProviders ?? null, entries,
|
|
66
|
+
installation_id: installationId, pair_id: pairId, credentialSource: "login",
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
restore: (captured) => {
|
|
70
|
+
// A journal written without copies never had them applied.
|
|
71
|
+
if (captured === null)
|
|
72
|
+
return;
|
|
73
|
+
const unknownState = new Error("Dziennik ma nieznany zapis kopii klucza A.");
|
|
74
|
+
if (!isRecord(captured) || !("claude" in captured))
|
|
75
|
+
throw unknownState;
|
|
76
|
+
const { manifest, claude } = captured;
|
|
77
|
+
if (manifest !== null && typeof manifest !== "string")
|
|
78
|
+
throw unknownState;
|
|
79
|
+
const op = claudeOp(ctx, "");
|
|
80
|
+
if (claude !== null)
|
|
81
|
+
applyOp({ ...op, value: claude }, recorded(readManifest(paths.manifest), op), { backupDir: paths.backups });
|
|
82
|
+
if (manifest === null) {
|
|
83
|
+
refuseSymlink(paths.manifest);
|
|
84
|
+
rmSync(paths.manifest, { force: true });
|
|
85
|
+
}
|
|
86
|
+
else
|
|
87
|
+
writePrivate(paths.dir, paths.manifest, manifest);
|
|
88
|
+
if (manifestText() !== manifest || (claude !== null && !isDeepStrictEqual(jsonValue(op), claude))) {
|
|
89
|
+
throw new Error("Odczyt kontrolny kopii klucza A nie zgadza się z dziennikiem.");
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** `npx robisie login`; the manifest's installation_id is only a claim the server checks (§5.2). */
|
|
95
|
+
export async function login(ctx, options) {
|
|
96
|
+
const installationHint = readManifest(clientPaths(agentPaths(ctx).clientDir).manifest)?.installation_id ?? null;
|
|
97
|
+
return deviceLogin(ctx, { ...options, installationHint, copies: pairCopies(ctx), io: loginRuntime.io });
|
|
98
|
+
}
|
|
99
|
+
/** init without any key and without a terminal pairs instead of stopping at „Brak klucza” (§7.6). */
|
|
100
|
+
export function initNeedsLogin(ctx, keyStdin) {
|
|
101
|
+
if (keyStdin || ctx.askSecret !== null || ctx.env[KEY_ENV]?.trim())
|
|
102
|
+
return false;
|
|
103
|
+
const dir = agentPaths(ctx).clientDir;
|
|
104
|
+
return !(readManifest(clientPaths(dir).manifest) && readKey(dir));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Takes the installation lock, finishes an interrupted pair journal, and for a login installation hands the
|
|
108
|
+
* command A and B from the files instead of the environment (§7.3, §7.6). Installations never paired by
|
|
109
|
+
* login have no mutex file: creating one here would turn doctor into a writer of manual installations.
|
|
110
|
+
*/
|
|
111
|
+
export async function openInstallation(ctx, command) {
|
|
112
|
+
const dir = agentPaths(ctx).clientDir;
|
|
113
|
+
if (!existsSync(join(dir, "robisie.lock.sqlite")) && !existsSync(join(dir, "pair-journal.json")))
|
|
114
|
+
return { ctx, release: null };
|
|
115
|
+
const release = acquireInstallationLock(dir, command);
|
|
116
|
+
try {
|
|
117
|
+
await resumePairJournal(ctx, dir, pairCopies(ctx));
|
|
118
|
+
if (readManifest(clientPaths(dir).manifest)?.credentialSource !== "login")
|
|
119
|
+
return { ctx, release };
|
|
120
|
+
const key = readKey(dir);
|
|
121
|
+
const reviewKey = readKey(dir, "review-key");
|
|
122
|
+
if (!key || !reviewKey || !KEY_PATTERN.test(key) || !KEY_PATTERN.test(reviewKey)) {
|
|
123
|
+
throw new RobisieError("Klucze A i B tej instalacji są niekompletne albo uszkodzone.", "Uruchom `npx robisie login`.");
|
|
124
|
+
}
|
|
125
|
+
for (const [name, value] of [[KEY_ENV, key], [REVIEW_KEY_ENV, reviewKey]]) {
|
|
126
|
+
const stale = ctx.env[name]?.trim();
|
|
127
|
+
if (stale && stale !== value)
|
|
128
|
+
ctx.err(`Stara wartość ${name} w środowisku jest ignorowana — otwórz nowy terminal.`);
|
|
129
|
+
}
|
|
130
|
+
return { ctx: { ...ctx, env: { ...ctx.env, [KEY_ENV]: key, [REVIEW_KEY_ENV]: reviewKey } }, release };
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
try {
|
|
134
|
+
release();
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// The SQLite handle closes with the process; the first error is the one to act on.
|
|
138
|
+
}
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** Releases the lock after the command; a failure is reported, the command's own result stands. */
|
|
143
|
+
export function closeInstallation(ctx, release) {
|
|
144
|
+
try {
|
|
145
|
+
release();
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!(error instanceof RobisieError))
|
|
149
|
+
throw error;
|
|
150
|
+
ctx.err(`✗ ${error.message}`);
|
|
151
|
+
ctx.err(`Następny krok: ${error.nextStep}`);
|
|
152
|
+
}
|
|
153
|
+
}
|