npm package: @potentially/ptp
Description: A JavaScript/TypeScript SDK for the Potentially Prompt Templating Protocol (PTP). Provides types, validators, and helpers.
Author: Sukhveer Sanghera
Latest version: 0.1.5

# Prompt Templating Protocol (PTP)

The Prompt Templating Protocol is an open, model-agnostic contract for describing prompts, model targets, and multi-step workflows so they can move cleanly between engines, vendors, and products. This package ships the canonical TypeScript types, Zod validators, and curated examples for the protocol.

## Why PTP?

The internet’s most durable protocols—HTTP, TCP/IP, DNS, TLS—earned adoption because they balanced stability with extensibility. They set a small normative core, left space for innovation, and encoded negotiation so legacy clients never broke. PTP 1.1 borrows directly from that DNA.

### Lessons from the Internet’s Standards

- **HTTP**: clear verbs, consistent status codes, negotiable headers (Content-Type, Accept), and optional features (Keep-Alive, caching) that gracefully fall back.
- **TCP/IP**: strict layering and end-to-end reliability while allowing intermediate hops to be ignorant of payload semantics. Versioning happens at the IP header, not in band payload.
- **DNS**: a compact schema with built-in extension records (EDNS, TXT) that made feature growth possible without rethinking the core lookup flow.
- **TLS**: explicit handshake negotiation, cipher suite registries, and version intolerance testing that protects old clients while encouraging new best practices.

From these we distilled four design commitments for PTP:

1. **Stable core, optional surface** – schemas define a normative core while extensions cover vendor-specific features.
2. **Explicit negotiation** – objects can declare version ranges, required capabilities, and optional features before execution.
3. **Discoverable metadata** – rich metadata and links make templates indexable, auditable, and reviewable (like RFC registries).
4. **Predictable fallbacks** – workflows describe branching, failure handling, and output contracts so orchestration platforms can recover gracefully.

## PTP 1.1 Highlights

- Semantic version strings on every object (`ptp_version`) for clean negotiation.
- Expanded `metadata` (tags, status, license, links) for discoverability and governance.
- Rich `inputs` with JSON Schema hints, formats, and examples—mirroring HTTP content negotiation.
- Target descriptors (`interface`, `modalities`, `constraints`) so execution engines can map to specific model endpoints.
- Chat-native `template` parts with roles, media types, and conditional rendering.
- Formal `outputs`, `extensions`, and `compliance` blocks so downstream tools know what to expect and what optional modules are required.
- Workflows gain branching, optional steps, and failure routing inspired by proven orchestration patterns.

## Installation

```bash
npm install @potentially/ptp
```

## TypeScript Usage

```ts
import type { PromptTemplate } from '@potentially/ptp';

const summarizer: PromptTemplate = {
  ptp_version: '1.1.0',
  metadata: {
    id: 'text-summarizer-v2',
    name: 'Text Summarizer',
    version: 2,
    description: 'Summarizes long-form content into structured bullet points.',
    tags: ['summarization', 'benchmark'],
    status: 'beta',
  },
  negotiation: {
    minimum_version: '1.0.0',
    required_capabilities: ['text-generation'],
    optional_capabilities: ['embedding'],
    default_locale: 'en-US',
  },
  inputs: [
    {
      name: 'article_text',
      type: 'string',
      description: 'Raw text to summarize.',
      required: true,
      format: 'markdown',
      schema: { type: 'string', minLength: 50 },
    },
    {
      name: 'tone',
      type: 'string',
      description: 'Desired tone for the summary.',
      required: false,
      default: 'neutral',
      schema: { type: 'string', enum: ['neutral', 'analytical', 'playful'] },
    },
  ],
  target: {
    capability: 'text-generation',
    interface: 'openai.chat.completions',
    version: '2024-05-01',
    modalities: ['text'],
    parameters: { temperature: 0.4, max_tokens: 220 },
    constraints: { max_latency_ms: 6000 },
  },
  template: [
    {
      id: 'system_context',
      type: 'text',
      role: 'system',
      media_type: 'text/plain',
      content: 'You are a precise summarization assistant that returns exactly three bullet points.',
    },
    {
      id: 'user_prompt',
      type: 'text',
      role: 'user',
      media_type: 'text/markdown',
      content: 'Summarize the following article in a {{tone}} tone:\n\n{{article_text}}',
    },
  ],
  outputs: [
    {
      name: 'summary_bullets',
      type: 'string',
      description: 'Three bullet point summary in markdown.',
      schema: { type: 'string' },
    },
  ],
  extensions: [
    {
      id: 'ptp://extensions/rendering/chatml',
      version: '1.0.0',
      required: false,
      description: 'Adds chat role semantics to template parts.',
    },
  ],
  compliance: {
    standards: ['SOC2-ready'],
    notes: 'Avoids storing user content beyond execution.',
  },
};
```

### Compile a Prompt Template

```ts
import {
  compilePromptTemplate,
  MissingInputError,
} from '@potentially/ptp';

const { template: completedTemplate } = compilePromptTemplate(
  summarizer,
  {
    article_text: rawMarkdown,
    tone: 'analytical',
  }
);

// completedTemplate.template now contains text with all {{placeholders}} resolved.
```

The compiler resolves required inputs, applies defaults, evaluates simple conditions, and inline substitutes `{{placeholders}}`. It throws a `MissingInputError`, `InvalidInputTypeError`, or `UnresolvedPlaceholderError` when strict validation fails so you can surface actionable feedback to callers.

## Validation

```ts
import { validatePromptTemplate, validateWorkflow } from '@potentially/ptp/validator';

const candidate = JSON.parse(input);
const result = validatePromptTemplate(candidate);

if (!result.success) {
  console.error('PTP validation failed', result.error.errors);
}
```

The validators enforce semantic version formatting, negotiation bounds, and the richer metadata/extension contracts introduced in v1.1.

## Data Model Reference

### PromptTemplate

| Field | Purpose | Notes |
| --- | --- | --- |
| `ptp_version` | Semantic version (major.minor[.patch]) | Enables negotiation across tooling. |
| `metadata` | Governance + discovery details | Includes `tags`, `status`, `links`, lifecycle timestamps. |
| `negotiation` | Capability + version handshake | Mirrors TLS/HTTP negotiation to agree on features safely. |
| `inputs` | Inputs with schema hints | JSON Schema snippets improve validation, UI, and documentation. |
| `target` | Execution intent | Defines capability, interface, version, parameters, and constraints. |
| `template` | Ordered multi-modal prompt parts | Supports chat roles, MIME types, conditional rendering. |
| `outputs` | Named contracts | Downstream systems can bind outputs deterministically. |
| `extensions` | Optional feature modules | Think MIME types or TLS extensions—self-describing and negotiable. |
| `compliance` | Certifications and safeguards | Advertises safety or regulatory posture. |
| `annotations` | Free-form metadata | For analytics, ownership info, or policy hooks. |

### Workflow

- Shares the same `ptp_version`, `metadata`, `negotiation`, `extensions`, and `compliance` shapes.
- `workflow_inputs` reuses input schema hints for orchestration-layer validation.
- `steps` now support `description`, `condition`, `metadata`, and structured `on_failure` fallbacks.
- `output` is still a mapping expression, but can reference branching logic (`step.output || fallback.output`).

See concrete JSON specimens in [`examples/text-summarizer.json`](examples/text-summarizer.json), [`examples/image-style-transfer.json`](examples/image-style-transfer.json), and [`examples/blog-creation.json`](examples/blog-creation.json).

## Adoption Playbook

1. **Model vendors**: advertise supported `capability`, `interface`, and `extensions` to enable automated compatibility checks.
2. **Tooling platforms**: surface `negotiation` blocks for runtime planning (similar to TLS cipher negotiation dashboards).
3. **Prompt engineers**: treat `metadata` and `annotations` as audit trails—fill in authorship, lifecycle status, and governance notes.
4. **Security and compliance teams**: rely on `compliance` to assert safe defaults, and use validators in CI to reject non-compliant templates.

## Roadmap

- Registry service for discovering and signing PTP templates.
- Extension catalog (ALPN-style) to prevent namespace collisions.
- Negotiation helpers for auto-downgrading to legacy capabilities when required.

## License

MIT © Potentially