@agentic-kit/pi 0.17.0 → 0.18.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.
Files changed (136) hide show
  1. package/README.md +5 -7
  2. package/confirm-gate.d.ts +1 -2
  3. package/esm/confirm-gate.d.ts +1 -2
  4. package/esm/host.d.ts +5 -110
  5. package/esm/host.js +5 -18
  6. package/esm/index.d.ts +17 -9
  7. package/esm/index.js +20 -38
  8. package/esm/pi-tool.d.ts +16 -0
  9. package/esm/pi-tool.js +32 -0
  10. package/host.d.ts +5 -110
  11. package/host.js +10 -22
  12. package/index.d.ts +17 -9
  13. package/index.js +47 -62
  14. package/package.json +6 -10
  15. package/pi-tool.d.ts +16 -0
  16. package/pi-tool.js +36 -0
  17. package/app-workspace.d.ts +0 -16
  18. package/app-workspace.js +0 -145
  19. package/context.d.ts +0 -62
  20. package/context.js +0 -282
  21. package/db-probe.d.ts +0 -30
  22. package/db-probe.js +0 -50
  23. package/esm/app-workspace.d.ts +0 -16
  24. package/esm/app-workspace.js +0 -134
  25. package/esm/context.d.ts +0 -62
  26. package/esm/context.js +0 -270
  27. package/esm/db-probe.d.ts +0 -30
  28. package/esm/db-probe.js +0 -47
  29. package/esm/policy/add-policies-to-table.d.ts +0 -26
  30. package/esm/policy/add-policies-to-table.js +0 -66
  31. package/esm/policy/provision-helpers.d.ts +0 -38
  32. package/esm/policy/provision-helpers.js +0 -50
  33. package/esm/provision-database/credential.d.ts +0 -14
  34. package/esm/provision-database/credential.js +0 -19
  35. package/esm/provision-database/env-file.d.ts +0 -37
  36. package/esm/provision-database/env-file.js +0 -85
  37. package/esm/provision-database/manifest.d.ts +0 -10
  38. package/esm/provision-database/manifest.js +0 -48
  39. package/esm/provision-database/pg-fixups.d.ts +0 -16
  40. package/esm/provision-database/pg-fixups.js +0 -132
  41. package/esm/provision-database/preset-match.d.ts +0 -13
  42. package/esm/provision-database/preset-match.js +0 -66
  43. package/esm/provision-database/presets.d.ts +0 -4
  44. package/esm/provision-database/presets.js +0 -13
  45. package/esm/provision-database/request-database.d.ts +0 -61
  46. package/esm/provision-database/request-database.js +0 -130
  47. package/esm/provision-database/resolve.d.ts +0 -27
  48. package/esm/provision-database/resolve.js +0 -49
  49. package/esm/records/meta.d.ts +0 -41
  50. package/esm/records/meta.js +0 -167
  51. package/esm/run-codegen/barrels.d.ts +0 -3
  52. package/esm/run-codegen/barrels.js +0 -48
  53. package/esm/run-codegen/endpoints.d.ts +0 -8
  54. package/esm/run-codegen/endpoints.js +0 -46
  55. package/esm/schema-resolve.d.ts +0 -23
  56. package/esm/schema-resolve.js +0 -69
  57. package/esm/tool-schema.d.ts +0 -3
  58. package/esm/tool-schema.js +0 -10
  59. package/esm/tools/add-policies.d.ts +0 -8
  60. package/esm/tools/add-policies.js +0 -96
  61. package/esm/tools/add-records.d.ts +0 -14
  62. package/esm/tools/add-records.js +0 -124
  63. package/esm/tools/add-relation-schema.d.ts +0 -30
  64. package/esm/tools/add-relation-schema.js +0 -58
  65. package/esm/tools/add-relation.d.ts +0 -10
  66. package/esm/tools/add-relation.js +0 -91
  67. package/esm/tools/create-api-key.d.ts +0 -18
  68. package/esm/tools/create-api-key.js +0 -216
  69. package/esm/tools/describe-schema.d.ts +0 -18
  70. package/esm/tools/describe-schema.js +0 -132
  71. package/esm/tools/manage-entity-types.d.ts +0 -41
  72. package/esm/tools/manage-entity-types.js +0 -203
  73. package/esm/tools/mutations.d.ts +0 -14
  74. package/esm/tools/mutations.js +0 -235
  75. package/esm/tools/provision-blueprint.d.ts +0 -22
  76. package/esm/tools/provision-blueprint.js +0 -111
  77. package/esm/tools/provision-database.d.ts +0 -14
  78. package/esm/tools/provision-database.js +0 -262
  79. package/esm/tools/run-codegen.d.ts +0 -11
  80. package/esm/tools/run-codegen.js +0 -139
  81. package/esm/tools/templates.d.ts +0 -49
  82. package/esm/tools/templates.js +0 -337
  83. package/policy/add-policies-to-table.d.ts +0 -26
  84. package/policy/add-policies-to-table.js +0 -71
  85. package/policy/provision-helpers.d.ts +0 -38
  86. package/policy/provision-helpers.js +0 -58
  87. package/provision-database/credential.d.ts +0 -14
  88. package/provision-database/credential.js +0 -22
  89. package/provision-database/env-file.d.ts +0 -37
  90. package/provision-database/env-file.js +0 -91
  91. package/provision-database/manifest.d.ts +0 -10
  92. package/provision-database/manifest.js +0 -56
  93. package/provision-database/pg-fixups.d.ts +0 -16
  94. package/provision-database/pg-fixups.js +0 -170
  95. package/provision-database/preset-match.d.ts +0 -13
  96. package/provision-database/preset-match.js +0 -70
  97. package/provision-database/presets.d.ts +0 -4
  98. package/provision-database/presets.js +0 -17
  99. package/provision-database/request-database.d.ts +0 -61
  100. package/provision-database/request-database.js +0 -134
  101. package/provision-database/resolve.d.ts +0 -27
  102. package/provision-database/resolve.js +0 -53
  103. package/records/meta.d.ts +0 -41
  104. package/records/meta.js +0 -172
  105. package/run-codegen/barrels.d.ts +0 -3
  106. package/run-codegen/barrels.js +0 -54
  107. package/run-codegen/endpoints.d.ts +0 -8
  108. package/run-codegen/endpoints.js +0 -51
  109. package/schema-resolve.d.ts +0 -23
  110. package/schema-resolve.js +0 -75
  111. package/tool-schema.d.ts +0 -3
  112. package/tool-schema.js +0 -13
  113. package/tools/add-policies.d.ts +0 -8
  114. package/tools/add-policies.js +0 -99
  115. package/tools/add-records.d.ts +0 -14
  116. package/tools/add-records.js +0 -127
  117. package/tools/add-relation-schema.d.ts +0 -30
  118. package/tools/add-relation-schema.js +0 -62
  119. package/tools/add-relation.d.ts +0 -10
  120. package/tools/add-relation.js +0 -94
  121. package/tools/create-api-key.d.ts +0 -18
  122. package/tools/create-api-key.js +0 -222
  123. package/tools/describe-schema.d.ts +0 -18
  124. package/tools/describe-schema.js +0 -135
  125. package/tools/manage-entity-types.d.ts +0 -41
  126. package/tools/manage-entity-types.js +0 -208
  127. package/tools/mutations.d.ts +0 -14
  128. package/tools/mutations.js +0 -238
  129. package/tools/provision-blueprint.d.ts +0 -22
  130. package/tools/provision-blueprint.js +0 -114
  131. package/tools/provision-database.d.ts +0 -14
  132. package/tools/provision-database.js +0 -268
  133. package/tools/run-codegen.d.ts +0 -11
  134. package/tools/run-codegen.js +0 -143
  135. package/tools/templates.d.ts +0 -49
  136. package/tools/templates.js +0 -341
@@ -1,27 +0,0 @@
1
- import { type ProvisionModule } from './presets';
2
- export interface ProvisionOverlay {
3
- /**
4
- * Base preset name to resolve from (e.g. 'b2b:storage', 'full'). The last
5
- * layer that sets `preset` wins; if none set it, `DEFAULT_PROVISION_PRESET`
6
- * is used.
7
- */
8
- preset?: string;
9
- /**
10
- * Modules to add. An entry whose key matches an existing module OVERRIDES it
11
- * (e.g. re-declaring `storage_module` with app-specific options); a new key
12
- * is appended.
13
- */
14
- add?: ProvisionModule[];
15
- /**
16
- * Module names or `name:scope` keys to drop from the base. A bare name
17
- * removes every scope of that module; `name:scope` removes just that one.
18
- */
19
- remove?: string[];
20
- }
21
- /** Stable identity for a module entry: `name` or `name:scope` when scoped. */
22
- export declare function moduleKey(m: ProvisionModule): string;
23
- /**
24
- * Resolve the effective module list from a pinned preset plus ordered overlays.
25
- * Pure: no I/O, no host access. Later overlays win (last-write-wins by key).
26
- */
27
- export declare function resolveProvisionModules(layers?: ProvisionOverlay[]): ProvisionModule[];
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.moduleKey = moduleKey;
4
- exports.resolveProvisionModules = resolveProvisionModules;
5
- // Ordered-overlay resolution for provision modules.
6
- //
7
- // Mirrors the skills overlay model (`@agentic-kit/harness` skills manifest): a
8
- // pinned base (a named preset from `node-type-registry`) is layered under zero
9
- // or more overlays, later layers winning by module key. An empty overlay list
10
- // resolves to the base preset unchanged.
11
- const presets_1 = require("./presets");
12
- function moduleName(m) {
13
- return Array.isArray(m) ? m[0] : m;
14
- }
15
- function moduleScope(m) {
16
- if (!Array.isArray(m))
17
- return undefined;
18
- const scope = m[1]?.scope;
19
- return typeof scope === 'string' ? scope : undefined;
20
- }
21
- /** Stable identity for a module entry: `name` or `name:scope` when scoped. */
22
- function moduleKey(m) {
23
- const scope = moduleScope(m);
24
- return scope ? `${moduleName(m)}:${scope}` : moduleName(m);
25
- }
26
- /**
27
- * Resolve the effective module list from a pinned preset plus ordered overlays.
28
- * Pure: no I/O, no host access. Later overlays win (last-write-wins by key).
29
- */
30
- function resolveProvisionModules(layers = []) {
31
- const presetName = [...layers].reverse().find((l) => l.preset)?.preset ?? presets_1.DEFAULT_PROVISION_PRESET;
32
- const preset = (0, presets_1.getModulePreset)(presetName);
33
- if (!preset) {
34
- const known = presets_1.allModulePresets.map((p) => p.name).join(', ');
35
- throw new Error(`Unknown provision preset "${presetName}". Known presets: ${known}.`);
36
- }
37
- // Ordered map keyed by module identity preserves position while allowing
38
- // overrides (same key) and appends (new key).
39
- const resolved = new Map();
40
- for (const m of preset.modules)
41
- resolved.set(moduleKey(m), m);
42
- for (const layer of layers) {
43
- for (const target of layer.remove ?? []) {
44
- for (const key of [...resolved.keys()]) {
45
- if (key === target || key.split(':')[0] === target)
46
- resolved.delete(key);
47
- }
48
- }
49
- for (const m of layer.add ?? [])
50
- resolved.set(moduleKey(m), m);
51
- }
52
- return [...resolved.values()];
53
- }
package/records/meta.d.ts DELETED
@@ -1,41 +0,0 @@
1
- import type { Table, TableInflection } from '@constructive-io/graphql-query/types/schema';
2
- export declare const META_QUERY = "\n query DbToolsMeta {\n _meta {\n tables {\n name\n query { all one create update delete }\n inflection {\n allRows\n conditionType\n connection\n createInputType\n createPayloadType\n deletePayloadType\n edge\n filterType\n orderByType\n patchType\n tableType\n updatePayloadType\n }\n fields {\n name\n isNotNull\n hasDefault\n type {\n gqlType\n isArray\n pgType\n subtype\n isNotNull\n hasDefault\n }\n }\n }\n }\n }\n";
3
- type RawType = {
4
- gqlType: string;
5
- isArray: boolean;
6
- modifier?: string | number | null;
7
- pgAlias?: string | null;
8
- pgType?: string | null;
9
- subtype?: string | null;
10
- typmod?: number | null;
11
- isNotNull?: boolean | null;
12
- hasDefault?: boolean | null;
13
- };
14
- type RawField = {
15
- name: string;
16
- isNotNull?: boolean | null;
17
- hasDefault?: boolean | null;
18
- type: RawType;
19
- };
20
- type RawInflection = Partial<Record<keyof TableInflection, string | null>>;
21
- type RawQuery = {
22
- all: string | null;
23
- one?: string | null;
24
- create?: string | null;
25
- update?: string | null;
26
- delete?: string | null;
27
- };
28
- export type RawMetaTable = {
29
- name: string;
30
- query?: RawQuery | null;
31
- inflection?: RawInflection | null;
32
- fields?: (RawField | null)[] | null;
33
- };
34
- export type MetaResponse = {
35
- _meta?: {
36
- tables?: (RawMetaTable | null)[] | null;
37
- } | null;
38
- };
39
- export declare function cleanTable(meta: RawMetaTable): Table;
40
- export declare function findMetaTable(tables: RawMetaTable[], requested: string): RawMetaTable | undefined;
41
- export {};
package/records/meta.js DELETED
@@ -1,172 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.META_QUERY = void 0;
4
- exports.cleanTable = cleanTable;
5
- exports.findMetaTable = findMetaTable;
6
- // Vendored from constructive-client's `@constructive-io/data` (not published to
7
- // the registry). We query the per-DB data endpoint's `_meta` introspection and
8
- // reshape each table into the `Table` shape `buildPostGraphileCreate` expects.
9
- // Relations are intentionally left empty: the create-mutation builder only reads
10
- // them to skip relational fields in the return selection, and every `_meta` field
11
- // is a real scalar column, so selecting them all is valid.
12
- //
13
- // Only fields the live backend's `_meta` actually exposes are selected here —
14
- // over-selecting (e.g. MetaType.modifier or MetaInflection.createField) fails
15
- // GraphQL validation. The reshapers below tolerate the omitted fields.
16
- exports.META_QUERY = `
17
- query DbToolsMeta {
18
- _meta {
19
- tables {
20
- name
21
- query { all one create update delete }
22
- inflection {
23
- allRows
24
- conditionType
25
- connection
26
- createInputType
27
- createPayloadType
28
- deletePayloadType
29
- edge
30
- filterType
31
- orderByType
32
- patchType
33
- tableType
34
- updatePayloadType
35
- }
36
- fields {
37
- name
38
- isNotNull
39
- hasDefault
40
- type {
41
- gqlType
42
- isArray
43
- pgType
44
- subtype
45
- isNotNull
46
- hasDefault
47
- }
48
- }
49
- }
50
- }
51
- }
52
- `;
53
- function convertInflection(inflection) {
54
- if (!inflection)
55
- return undefined;
56
- const s = (key) => inflection[key] ?? '';
57
- const n = (key) => inflection[key] ?? null;
58
- return {
59
- allRows: s('allRows'),
60
- allRowsSimple: s('allRowsSimple'),
61
- conditionType: s('conditionType'),
62
- connection: s('connection'),
63
- createField: s('createField'),
64
- createInputType: s('createInputType'),
65
- createPayloadType: s('createPayloadType'),
66
- deleteByPrimaryKey: n('deleteByPrimaryKey'),
67
- deletePayloadType: s('deletePayloadType'),
68
- edge: s('edge'),
69
- edgeField: s('edgeField'),
70
- enumType: s('enumType'),
71
- filterType: n('filterType'),
72
- inputType: s('inputType'),
73
- orderByType: s('orderByType'),
74
- patchField: s('patchField'),
75
- patchType: n('patchType'),
76
- tableFieldName: s('tableFieldName'),
77
- tableType: s('tableType'),
78
- typeName: s('typeName'),
79
- updateByPrimaryKey: n('updateByPrimaryKey'),
80
- updatePayloadType: n('updatePayloadType'),
81
- };
82
- }
83
- function convertQuery(query) {
84
- if (!query)
85
- return undefined;
86
- return {
87
- all: query.all ?? '',
88
- one: query.one ?? null,
89
- create: query.create ?? '',
90
- update: query.update ?? null,
91
- delete: query.delete ?? null,
92
- };
93
- }
94
- function cleanTable(meta) {
95
- return {
96
- name: meta.name,
97
- inflection: convertInflection(meta.inflection),
98
- query: convertQuery(meta.query),
99
- fields: (meta.fields ?? [])
100
- .filter((f) => Boolean(f))
101
- .map((field) => ({
102
- name: field.name,
103
- type: {
104
- gqlType: field.type.gqlType,
105
- isArray: field.type.isArray,
106
- modifier: field.type.modifier,
107
- pgAlias: field.type.pgAlias,
108
- pgType: field.type.pgType,
109
- subtype: field.type.subtype,
110
- typmod: field.type.typmod,
111
- },
112
- isNotNull: field.isNotNull ?? field.type.isNotNull ?? null,
113
- hasDefault: field.hasDefault ?? field.type.hasDefault ?? null,
114
- })),
115
- relations: { belongsTo: [], hasOne: [], hasMany: [], manyToMany: [] },
116
- };
117
- }
118
- function normalizeTableLookupKey(value) {
119
- return (value ?? '')
120
- .trim()
121
- .toLowerCase()
122
- .replace(/[^a-z0-9]/g, '');
123
- }
124
- function getTableLookupVariants(value) {
125
- const normalized = normalizeTableLookupKey(value);
126
- if (!normalized)
127
- return [];
128
- const variants = new Set([normalized]);
129
- if (normalized.endsWith('y')) {
130
- variants.add(`${normalized}s`);
131
- variants.add(`${normalized.slice(0, -1)}ies`);
132
- }
133
- if (normalized.endsWith('ies')) {
134
- variants.add(`${normalized.slice(0, -3)}y`);
135
- }
136
- if (/(s|x|z|ch|sh)$/.test(normalized))
137
- variants.add(`${normalized}es`);
138
- if (normalized.endsWith('es'))
139
- variants.add(normalized.slice(0, -2));
140
- if (!normalized.endsWith('s'))
141
- variants.add(`${normalized}s`);
142
- if (normalized.endsWith('s'))
143
- variants.add(normalized.slice(0, -1));
144
- return [...variants].filter(Boolean);
145
- }
146
- // Resolve a user-supplied table name (snake_case singular or plural) against the
147
- // PascalCase-singular `_meta` table names, tolerating pluralization differences.
148
- function findMetaTable(tables, requested) {
149
- const index = new Map();
150
- for (const table of tables) {
151
- const keys = [
152
- table.name,
153
- table.query?.all,
154
- table.query?.one,
155
- table.inflection?.tableType,
156
- table.inflection?.tableFieldName,
157
- table.inflection?.allRows,
158
- ];
159
- for (const key of keys) {
160
- for (const variant of getTableLookupVariants(key)) {
161
- if (!index.has(variant))
162
- index.set(variant, table);
163
- }
164
- }
165
- }
166
- for (const variant of getTableLookupVariants(requested)) {
167
- const match = index.get(variant);
168
- if (match)
169
- return match;
170
- }
171
- return undefined;
172
- }
@@ -1,3 +0,0 @@
1
- /** Rewrite directory barrel specifiers under `root` in place. Returns the count
2
- * of files changed. No-op (returns 0) when `root` does not exist. */
3
- export declare function normalizeSdkBarrels(root: string): number;
@@ -1,54 +0,0 @@
1
- "use strict";
2
- // Turbopack barrel normalization (TURBOPACK-BARREL-001).
3
- //
4
- // Codegen emits directory barrel re-exports like `export * from './hooks'` where
5
- // `./hooks` is a directory with an index.ts. Next.js 16's Turbopack cannot
6
- // resolve directory specifiers — it needs an explicit `./hooks/index`. This pass
7
- // rewrites `./X` -> `./X/index` only when X resolves to a sibling DIRECTORY,
8
- // leaving file specifiers (and ones already ending in /index) untouched.
9
- //
10
- // Pure-ish: operates on a real directory tree (so it's exercised with a temp
11
- // fixture in tests) and is idempotent — safe to re-run.
12
- var __importDefault = (this && this.__importDefault) || function (mod) {
13
- return (mod && mod.__esModule) ? mod : { "default": mod };
14
- };
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.normalizeSdkBarrels = normalizeSdkBarrels;
17
- const node_fs_1 = __importDefault(require("node:fs"));
18
- const node_path_1 = __importDefault(require("node:path"));
19
- const SPEC_RE = /((?:export|import)[^\n]*?from\s*["'])(\.\.?\/[^"']+?)(["'])/g;
20
- const FILE_EXT_RE = /\.(tsx?|jsx?|json|css)$/;
21
- /** Rewrite directory barrel specifiers under `root` in place. Returns the count
22
- * of files changed. No-op (returns 0) when `root` does not exist. */
23
- function normalizeSdkBarrels(root) {
24
- if (!node_fs_1.default.existsSync(root))
25
- return 0;
26
- let changed = 0;
27
- const walk = (dir) => {
28
- for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
29
- const p = node_path_1.default.join(dir, entry.name);
30
- if (entry.isDirectory()) {
31
- walk(p);
32
- continue;
33
- }
34
- if (!/\.tsx?$/.test(entry.name))
35
- continue;
36
- const orig = node_fs_1.default.readFileSync(p, 'utf8');
37
- const next = orig.replace(SPEC_RE, (match, pre, spec, post) => {
38
- if (FILE_EXT_RE.test(spec))
39
- return match; // already a file
40
- const abs = node_path_1.default.resolve(node_path_1.default.dirname(p), spec);
41
- if (node_fs_1.default.existsSync(abs) && node_fs_1.default.statSync(abs).isDirectory()) {
42
- return pre + spec.replace(/\/$/, '') + '/index' + post;
43
- }
44
- return match;
45
- });
46
- if (next !== orig) {
47
- node_fs_1.default.writeFileSync(p, next);
48
- changed++;
49
- }
50
- }
51
- };
52
- walk(root);
53
- return changed;
54
- }
@@ -1,8 +0,0 @@
1
- export type PlaneEndpoints = {
2
- admin: string;
3
- auth: string;
4
- app: string;
5
- };
6
- export declare function derivePlaneEndpoints(apiEndpoint: string, databaseName: string): PlaneEndpoints | undefined;
7
- export declare function codegenEndpointEnv(planes: PlaneEndpoints): Record<string, string>;
8
- export declare function envLocalContent(databaseName: string, planes: PlaneEndpoints | undefined): string;
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.derivePlaneEndpoints = derivePlaneEndpoints;
4
- exports.codegenEndpointEnv = codegenEndpointEnv;
5
- exports.envLocalContent = envLocalContent;
6
- // Codegen and the Next.js dev server default every per-DB vhost to
7
- // *-<db>.localhost:3000, which only exists on a local backend. Derive the real
8
- // vhosts from the api endpoint the binding belongs to by swapping its first
9
- // host label (api.launchql.dev -> admin-<db>.launchql.dev) — the same scheme
10
- // context.ts uses for the data plane. The app DATA plane is `api-<db>`, not
11
- // `app-<db>` (SUBDOMAIN-001).
12
- function derivePlaneEndpoints(apiEndpoint, databaseName) {
13
- const derive = (label) => {
14
- try {
15
- const url = new URL(apiEndpoint);
16
- const labels = url.hostname.split('.');
17
- labels[0] = `${label}-${databaseName}`;
18
- url.hostname = labels.join('.');
19
- return url.toString();
20
- }
21
- catch {
22
- return undefined;
23
- }
24
- };
25
- const admin = derive('admin');
26
- const auth = derive('auth');
27
- const app = derive('api');
28
- return admin && auth && app ? { admin, auth, app } : undefined;
29
- }
30
- // The template's graphql-codegen.config.ts honors CODEGEN_*_ENDPOINT for the
31
- // URL and CODEGEN_*_HOST for the Host header; set both so scheme and routing
32
- // stay in sync on any backend.
33
- function codegenEndpointEnv(planes) {
34
- return {
35
- CODEGEN_ADMIN_ENDPOINT: planes.admin,
36
- CODEGEN_ADMIN_HOST: new URL(planes.admin).host,
37
- CODEGEN_AUTH_ENDPOINT: planes.auth,
38
- CODEGEN_AUTH_HOST: new URL(planes.auth).host,
39
- CODEGEN_APP_ENDPOINT: planes.app,
40
- CODEGEN_APP_HOST: new URL(planes.app).host,
41
- };
42
- }
43
- // .env.local for the dev server: the template's runtime config falls back to
44
- // localhost vhosts unless NEXT_PUBLIC_*_ENDPOINT overrides are present.
45
- function envLocalContent(databaseName, planes) {
46
- const lines = [`NEXT_PUBLIC_DB_NAME=${databaseName}`];
47
- if (planes) {
48
- lines.push(`NEXT_PUBLIC_ADMIN_ENDPOINT=${planes.admin}`, `NEXT_PUBLIC_AUTH_ENDPOINT=${planes.auth}`, `NEXT_PUBLIC_APP_ENDPOINT=${planes.app}`);
49
- }
50
- return `${lines.join('\n')}\n`;
51
- }
@@ -1,23 +0,0 @@
1
- import type { ProjectContext } from './context';
2
- export type ResolvedField = {
3
- id: string;
4
- name: string;
5
- tableId: string;
6
- };
7
- export type ResolvedUniqueConstraint = {
8
- id: string;
9
- fieldIds: string[];
10
- };
11
- export type ResolvedTable = {
12
- id: string;
13
- name: string;
14
- fields: ResolvedField[];
15
- uniqueConstraints: ResolvedUniqueConstraint[];
16
- };
17
- export type ResolvedSchema = {
18
- tables: ResolvedTable[];
19
- };
20
- export declare function resolveSchema(context: ProjectContext): Promise<ResolvedSchema>;
21
- export declare function resolveTable(schema: ResolvedSchema, tableName: string): ResolvedTable;
22
- export declare function resolveField(table: ResolvedTable, fieldName: string): ResolvedField;
23
- export declare function findUniqueConstraintId(table: ResolvedTable, fieldId: string): string | undefined;
package/schema-resolve.js DELETED
@@ -1,75 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveSchema = resolveSchema;
4
- exports.resolveTable = resolveTable;
5
- exports.resolveField = resolveField;
6
- exports.findUniqueConstraintId = findUniqueConstraintId;
7
- async function resolveSchema(context) {
8
- const { api, databaseId } = context;
9
- const tablesResult = await api.table
10
- .findMany({
11
- select: { id: true, name: true },
12
- where: { databaseId: { equalTo: databaseId } },
13
- })
14
- .execute();
15
- if (!tablesResult.ok) {
16
- const message = tablesResult.errors.map((e) => e.message).join('; ');
17
- throw new Error(`Failed to read tables: ${message}`);
18
- }
19
- const tableNodes = tablesResult.data.tables?.nodes ?? [];
20
- const tableIds = tableNodes.map((t) => t.id);
21
- const fieldsByTable = new Map();
22
- const constraintsByTable = new Map();
23
- if (tableIds.length > 0) {
24
- const fieldsResult = await api.field
25
- .findMany({
26
- select: { id: true, name: true, tableId: true },
27
- where: { tableId: { in: tableIds } },
28
- })
29
- .execute();
30
- if (!fieldsResult.ok) {
31
- const message = fieldsResult.errors.map((e) => e.message).join('; ');
32
- throw new Error(`Failed to read fields: ${message}`);
33
- }
34
- for (const field of fieldsResult.data.fields?.nodes ?? []) {
35
- const list = fieldsByTable.get(field.tableId) ?? [];
36
- list.push({ id: field.id, name: field.name, tableId: field.tableId });
37
- fieldsByTable.set(field.tableId, list);
38
- }
39
- const constraintsResult = await api.uniqueConstraint
40
- .findMany({
41
- select: { id: true, tableId: true, fieldIds: true },
42
- where: { tableId: { in: tableIds } },
43
- })
44
- .execute();
45
- if (constraintsResult.ok) {
46
- for (const c of constraintsResult.data.uniqueConstraints?.nodes ?? []) {
47
- const list = constraintsByTable.get(c.tableId) ?? [];
48
- list.push({ id: c.id, fieldIds: Array.isArray(c.fieldIds) ? c.fieldIds : [] });
49
- constraintsByTable.set(c.tableId, list);
50
- }
51
- }
52
- }
53
- const tables = tableNodes.map((table) => ({
54
- id: table.id,
55
- name: table.name,
56
- fields: fieldsByTable.get(table.id) ?? [],
57
- uniqueConstraints: constraintsByTable.get(table.id) ?? [],
58
- }));
59
- return { tables };
60
- }
61
- function resolveTable(schema, tableName) {
62
- const table = schema.tables.find((t) => t.name === tableName);
63
- if (!table)
64
- throw new Error(`Table "${tableName}" not found in current schema`);
65
- return table;
66
- }
67
- function resolveField(table, fieldName) {
68
- const field = table.fields.find((f) => f.name === fieldName);
69
- if (!field)
70
- throw new Error(`Field "${fieldName}" not found in table "${table.name}"`);
71
- return field;
72
- }
73
- function findUniqueConstraintId(table, fieldId) {
74
- return table.uniqueConstraints.find((c) => c.fieldIds.includes(fieldId))?.id;
75
- }
package/tool-schema.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import type { TSchema } from 'typebox';
2
- import { z } from 'zod';
3
- export declare function toolSchema(schema: z.ZodType): TSchema;
package/tool-schema.js DELETED
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toolSchema = toolSchema;
4
- const zod_1 = require("zod");
5
- // Tool parameter schemas are authored in zod; pi's ToolDefinition wants a
6
- // typebox TSchema. Structurally a TSchema is just a JSON Schema object, so the
7
- // draft-7 output of z.toJSONSchema (minus the $schema marker, matching what
8
- // typebox emits) is cast across the boundary. typebox itself is a type-only
9
- // import — it never appears in the runtime bundle.
10
- function toolSchema(schema) {
11
- const { $schema: _$schema, ...rest } = zod_1.z.toJSONSchema(schema, { target: 'draft-7' });
12
- return rest;
13
- }
@@ -1,8 +0,0 @@
1
- import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
2
- declare const AddPoliciesSchema: import("typebox/type").TSchema;
3
- export type AddPoliciesDetails = {
4
- success: boolean;
5
- message: string;
6
- };
7
- export declare const addPoliciesTool: ToolDefinition<typeof AddPoliciesSchema, AddPoliciesDetails>;
8
- export {};
@@ -1,99 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addPoliciesTool = void 0;
4
- const harness_1 = require("@agentic-kit/harness");
5
- const zod_1 = require("zod");
6
- const context_1 = require("../context");
7
- const add_policies_to_table_1 = require("../policy/add-policies-to-table");
8
- const schema_resolve_1 = require("../schema-resolve");
9
- const tool_schema_1 = require("../tool-schema");
10
- const DEFAULT_ROLE = 'authenticated';
11
- const CrudOperationSchema = zod_1.z.enum(['create', 'read', 'update', 'delete']);
12
- const PolicyEntrySchema = zod_1.z.object({
13
- policy_type: zod_1.z
14
- .string()
15
- .describe('Policy type id. Supported: AuthzAllowAll, AuthzDenyAll, AuthzAppMembership, AuthzDirectOwner, AuthzEntityMembership, AuthzOrgHierarchy, AuthzPublishable (these auto-create columns via their Data* node), AuthzRelatedMemberList, AuthzRelatedEntityMembership. Not supported (use the policies UI): AuthzDirectOwnerAny, AuthzMemberList, AuthzTemporal, AuthzComposite.'),
16
- operations: zod_1.z
17
- .array(CrudOperationSchema)
18
- .min(1)
19
- .describe('CRUD operations the policy applies to: any subset of ["create","read","update","delete"].'),
20
- role_name: zod_1.z
21
- .string()
22
- .describe('PostgreSQL role the policy applies to. Defaults to "authenticated".')
23
- .optional(),
24
- is_permissive: zod_1.z
25
- .boolean()
26
- .describe('PERMISSIVE (default true) vs RESTRICTIVE — most policies should be permissive.')
27
- .optional(),
28
- data: zod_1.z
29
- .record(zod_1.z.string(), zod_1.z.unknown())
30
- .describe('Type-specific shared data. AuthzDirectOwner: { entity_field: "owner_id" }. AuthzAppMembership: { permission?, is_admin?, is_owner? }. Empty object {} for AuthzAllowAll / AuthzDenyAll.')
31
- .optional(),
32
- node_data: zod_1.z
33
- .record(zod_1.z.string(), zod_1.z.unknown())
34
- .describe('Optional data for the underlying Data* node (has-module policies only).')
35
- .optional(),
36
- });
37
- const AddPoliciesZod = zod_1.z.object({
38
- table_name: zod_1.z
39
- .string()
40
- .describe('Name of the existing table to attach the policies to. Use describe_schema first to verify it exists.'),
41
- policies: zod_1.z
42
- .array(PolicyEntrySchema)
43
- .min(1)
44
- .describe('One or more policies to add. Each entry becomes one secure_table_provision call.'),
45
- });
46
- const AddPoliciesSchema = (0, tool_schema_1.toolSchema)(AddPoliciesZod);
47
- function buildOperations(roleName, isPermissive) {
48
- const config = { roleName, isPermissive, policyData: {}, isCustomized: false };
49
- return { create: config, read: config, update: config, delete: config };
50
- }
51
- exports.addPoliciesTool = {
52
- name: 'add_policies',
53
- label: 'Add policies',
54
- description: 'Add one or more RLS policies to an existing table. Has-module policies (AuthzDirectOwner, AuthzEntityMembership, AuthzOrgHierarchy, AuthzPublishable) auto-create the columns they need — call directly, do not add columns first.',
55
- promptSnippet: 'add_policies: attach RLS policies to an existing table (one call can add many). Gated.',
56
- parameters: AddPoliciesSchema,
57
- async execute(_id, params, _signal, _onUpdate, ctx) {
58
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
59
- if (!resolved.context) {
60
- return {
61
- content: [{ type: 'text', text: resolved.reason }],
62
- details: { success: false, message: resolved.reason },
63
- };
64
- }
65
- const { modules, databaseId, schemaId } = resolved.context;
66
- try {
67
- const schema = await (0, schema_resolve_1.resolveSchema)(resolved.context);
68
- const table = (0, schema_resolve_1.resolveTable)(schema, params.table_name);
69
- const policies = params.policies.map((entry) => {
70
- const config = (0, harness_1.getPolicyProvisioningConfig)(entry.policy_type);
71
- const defaults = (0, harness_1.getPolicyFieldDefaults)(entry.policy_type);
72
- const mergedData = { ...defaults, ...(entry.data ?? {}) };
73
- const nodeData = entry.node_data ?? (0, harness_1.buildNodeData)(entry.policy_type, mergedData);
74
- return {
75
- policyType: entry.policy_type,
76
- dataNodeType: config?.dataNodeType,
77
- nodeData,
78
- sharedPolicyData: mergedData,
79
- operations: buildOperations(entry.role_name ?? DEFAULT_ROLE, entry.is_permissive ?? true),
80
- enabledOperations: entry.operations,
81
- };
82
- });
83
- await (0, add_policies_to_table_1.addPoliciesToExistingTable)({
84
- client: modules,
85
- databaseId,
86
- schemaId,
87
- tableId: table.id,
88
- policies,
89
- });
90
- const count = params.policies.length;
91
- const message = `Added ${count} ${count === 1 ? 'policy' : 'policies'} to ${params.table_name}`;
92
- return { content: [{ type: 'text', text: message }], details: { success: true, message } };
93
- }
94
- catch (err) {
95
- const message = err instanceof Error ? err.message : 'Failed to add policies';
96
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
97
- }
98
- },
99
- };
@@ -1,14 +0,0 @@
1
- import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
2
- export type AddRecordsDetails = {
3
- success: boolean;
4
- message: string;
5
- tableName?: string;
6
- columns?: string[];
7
- rows?: Record<string, unknown>[];
8
- createdCount?: number;
9
- asOf?: string;
10
- needsAuth?: boolean;
11
- };
12
- declare const AddRecordsSchema: import("typebox/type").TSchema;
13
- export declare const addRecordsTool: ToolDefinition<typeof AddRecordsSchema, AddRecordsDetails>;
14
- export {};